问:
Missing required parameters for [Route: homepage.edit] with link in layout
I'm new to Laravel 5.4 and php and I'm having some trouble to do my routing, so I wish you would explain to me what's going on !

I'm developing a back office for my future projects, and for my current project I need to be able to update data sent to the homepage. The edit of the page and the update of the data is now fully functional, I'm just having some trouble to do the link in the layout. Pretty sure it's a trivial problem, yet i'm having trouble figuring it out.

Here is my code :

web.php :

```<code>Route::group(['prefix' => 'admin',  'middleware' => 'admin'], function()
{
  Route::resource('homepage', 'Admin\HomeController');
});
</code>```

HomeController :`

```<code> public function edit($id) {
    $contentExists = Homepage::first();
    $homepage = Homepage::findOrFail($id);
    return view('admin/homepage/edit', compact('homepage', 'contentExists'));
}`
</code>```

In the layout :

```<code><ul class="list-unstyled">
 <li>
  <a href="{{ route('homepage.edit') }}">Page d'accueil</a>
 </li>
</ul>
</code>```

Now for that I know I need to pass a parameter to the route, so I did like so :

```<code><ul class="list-unstyled">
 <li>
  <a href="{{ route('homepage.edit', $homepage) }}">Page d'accueil</a>
 </li>
</ul>
</code>```

But then it says the homepage variable is not defined, and I have no idea where I can define this variable since I'm in the layout, and also have no idea what needs to be inside this variable, what's his purpose... Can you help me with that ?

答:
route second parameter, must be an array like this for example:</p>

```<code>route('homepage.edit', ['id' => 2])
</code>```

Body:
I'm new to Laravel 5.4 and php and I'm having some trouble to do my routing, so I wish you would explain to me what's going on !

I'm developing a back office for my future projects, and for my current project I need to be able to update data sent to the homepage. The edit of the page and the update of the data is now fully functional, I'm just having some trouble to do the link in the layout. Pretty sure it's a trivial problem, yet i'm having trouble figuring it out.

Here is my code :

web.php :

Route::group(['prefix' => 'admin',  'middleware' => 'admin'], function()
{
  Route::resource('homepage', 'Admin\HomeController');
});

HomeController :`

 public function edit($id) {
    $contentExists = Homepage::first();
    $homepage = Homepage::findOrFail($id);
    return view('admin/homepage/edit', compact('homepage', 'contentExists'));
}`

In the layout :

  Page d'accueil

Now for that I know I need to pass a parameter to the route, so I did like so :

  Page d'accueil

But then it says the homepage variable is not defined, and I have no idea where I can define this variable since I'm in the layout, and also have no idea what needs to be inside this variable, what's his purpose... Can you help me with that ?

Body:
route second parameter, must be an array like this for example:

route('homepage.edit', ['id' => 2])


来源: stackexchange

问:
SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session
I am currently getting this error:

System.Data.SqlClient.SqlException: New transaction is not allowed because there are other threads running in the session.

while running this code:

```<code>public class ProductManager : IProductManager
{
    #region Declare Models
    private RivWorks.Model.Negotiation.RIV_Entities _dbRiv = RivWorks.Model.Stores.RivEntities(AppSettings.RivWorkEntities_connString);
    private RivWorks.Model.NegotiationAutos.RivFeedsEntities _dbFeed = RivWorks.Model.Stores.FeedEntities(AppSettings.FeedAutosEntities_connString);
    #endregion

    public IProduct GetProductById(Guid productId)
    {
        // Do a quick sync of the feeds...
        SyncFeeds();
        ...
        // get a product...
        ...
        return product;
    }

    private void SyncFeeds()
    {
        bool found = false;
        string feedSource = "AUTO";
        switch (feedSource) // companyFeedDetail.FeedSourceTable.ToUpper())
        {
            case "AUTO":
                var clientList = from a in _dbFeed.Client.Include("Auto") select a;
                foreach (RivWorks.Model.NegotiationAutos.Client client in clientList)
                {
                    var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a;
                    foreach (RivWorks.Model.Negotiation.AutoNegotiationDetails companyFeedDetail in companyFeedDetailList)
                    {
                        if (companyFeedDetail.FeedSourceTable.ToUpper() == "AUTO")
                        {
                            var company = (from a in _dbRiv.Company.Include("Product") where a.CompanyId == companyFeedDetail.CompanyId select a).First();
                            foreach (RivWorks.Model.NegotiationAutos.Auto sourceProduct in client.Auto)
                            {
                                foreach (RivWorks.Model.Negotiation.Product targetProduct in company.Product)
                                {
                                    if (targetProduct.alternateProductID == sourceProduct.AutoID)
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found)
                                {
                                    var newProduct = new RivWorks.Model.Negotiation.Product();
                                    newProduct.alternateProductID = sourceProduct.AutoID;
                                    newProduct.isFromFeed = true;
                                    newProduct.isDeleted = false;
                                    newProduct.SKU = sourceProduct.StockNumber;
                                    company.Product.Add(newProduct);
                                }
                            }
                            _dbRiv.SaveChanges();  // ### THIS BREAKS ### //
                        }
                    }
                }
                break;
        }
    }
}
</code>```

Model #1 - This model sits in a database on our Dev Server.
Model #1 http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/bdb2b000-6e60-4af0-a7a1-2bb6b05d8bc1/Model1.png

Model #2 - This model sits in a database on our Prod Server and is updated each day by automatic feeds.  alt text http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/4260259f-bce6-43d5-9d2a-017bd9a980d4/Model2.png

Note - The red circled items in Model #1 are the fields I use to "map" to Model #2.  Please ignore the red circles in Model #2: that is from another question I had which is now answered.

Note:  I still need to put in an isDeleted check so I can soft delete it from DB1 if it has gone out of our client's inventory.

All I want to do, with this particular code, is connect a company in DB1 with a client in DB2, get their product list from DB2 and INSERT it in DB1 if it is not already there.  First time through should be a full pull of inventory.  Each time it is run there after nothing should happen unless new inventory came in on the feed over night.

So the big question - how to I solve the transaction error I am getting?  Do I need to drop and recreate my context each time through the loops (does not make sense to me)?

答: Just put context.SaveChanges() after end of your foreach(loop).

ContentLicense: CC BY-SA 3.0

Body:
I am currently getting this error:

System.Data.SqlClient.SqlException: New transaction is not allowed because there are other threads running in the session.

while running this code:

public class ProductManager : IProductManager
{
    #region Declare Models
    private RivWorks.Model.Negotiation.RIV_Entities _dbRiv = RivWorks.Model.Stores.RivEntities(AppSettings.RivWorkEntities_connString);
    private RivWorks.Model.NegotiationAutos.RivFeedsEntities _dbFeed = RivWorks.Model.Stores.FeedEntities(AppSettings.FeedAutosEntities_connString);
    #endregion

    public IProduct GetProductById(Guid productId)
    {
        // Do a quick sync of the feeds...
        SyncFeeds();
        ...
        // get a product...
        ...
        return product;
    }

    private void SyncFeeds()
    {
        bool found = false;
        string feedSource = "AUTO";
        switch (feedSource) // companyFeedDetail.FeedSourceTable.ToUpper())
        {
            case "AUTO":
                var clientList = from a in _dbFeed.Client.Include("Auto") select a;
                foreach (RivWorks.Model.NegotiationAutos.Client client in clientList)
                {
                    var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a;
                    foreach (RivWorks.Model.Negotiation.AutoNegotiationDetails companyFeedDetail in companyFeedDetailList)
                    {
                        if (companyFeedDetail.FeedSourceTable.ToUpper() == "AUTO")
                        {
                            var company = (from a in _dbRiv.Company.Include("Product") where a.CompanyId == companyFeedDetail.CompanyId select a).First();
                            foreach (RivWorks.Model.NegotiationAutos.Auto sourceProduct in client.Auto)
                            {
                                foreach (RivWorks.Model.Negotiation.Product targetProduct in company.Product)
                                {
                                    if (targetProduct.alternateProductID == sourceProduct.AutoID)
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found)
                                {
                                    var newProduct = new RivWorks.Model.Negotiation.Product();
                                    newProduct.alternateProductID = sourceProduct.AutoID;
                                    newProduct.isFromFeed = true;
                                    newProduct.isDeleted = false;
                                    newProduct.SKU = sourceProduct.StockNumber;
                                    company.Product.Add(newProduct);
                                }
                            }
                            _dbRiv.SaveChanges();  // ### THIS BREAKS ### //
                        }
                    }
                }
                break;
        }
    }
}

Model #1 - This model sits in a database on our Dev Server.
Model #1 http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/bdb2b000-6e60-4af0-a7a1-2bb6b05d8bc1/Model1.png

Model #2 - This model sits in a database on our Prod Server and is updated each day by automatic feeds.  alt text http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/4260259f-bce6-43d5-9d2a-017bd9a980d4/Model2.png

Note - The red circled items in Model #1 are the fields I use to "map" to Model #2.  Please ignore the red circles in Model #2: that is from another question I had which is now answered.

Note:  I still need to put in an isDeleted check so I can soft delete it from DB1 if it has gone out of our client's inventory.

All I want to do, with this particular code, is connect a company in DB1 with a client in DB2, get their product list from DB2 and INSERT it in DB1 if it is not already there.  First time through should be a full pull of inventory.  Each time it is run there after nothing should happen unless new inventory came in on the feed over night.

So the big question - how to I solve the transaction error I am getting?  Do I need to drop and recreate my context each time through the loops (does not make sense to me)?


问:
JQuery '.css' not functioning properly on Firefox - works perfectly on Google Chrome
I have a sort of abstract art piece on the main page of my portfolio that moves about depending on where the mouse cursor is.

This animation works perfectly on Safari, Google Chrome and Opera.

The issue on Firefox is seems to be only when the middle block attempts to move down

Here's a link to my portfolio: http://benjaminthomasgibbs.co.uk/

Okay I know my css code is not properly formatted, I like it this way - could that be the problem:

JS:

```<code>// MIDDLE SLATE ANIMATION

$(document).ready(function() {
    $('#slateMid').mouseenter(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    })
    $('#slateMid').mouseleave(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    })
})
</code>```

HTML:

```<code><div id="changeBottomLeft">
</div>
<div id="changeBottomRight">
</div>
<div id="slate">
</div>
<div id="slateMid">
</div>
<div id="slateEnd">
</div>
</code>```

答:
I am not completly sure if i understand you question, but i think this is your problem.

The middle slate behaves very shaky because the enter and leave events are fired way to often. This make the animation look strange and wonky, but it will also take a lot from the device to process it.

That is why you should use a debounce, more in this article if you are interested: debounce

The code snippet below will make sure that your mouse enter / leave events won't be triggered more than once every 50 ms

```<code>    function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
$('#slateMid').on('mouseleave', debounce(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    },50));

$('#slateMid').on('mouseenter', debounce(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    },50));
</code>```

Body:
I have a sort of abstract art piece on the main page of my portfolio that moves about depending on where the mouse cursor is.

This animation works perfectly on Safari, Google Chrome and Opera.

The issue on Firefox is seems to be only when the middle block attempts to move down

Here's a link to my portfolio: http://benjaminthomasgibbs.co.uk/

Okay I know my css code is not properly formatted, I like it this way - could that be the problem:

JS:

// MIDDLE SLATE ANIMATION

$(document).ready(function() {
    $('#slateMid').mouseenter(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    })
    $('#slateMid').mouseleave(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    })
})

HTML:

Body:
I am not completly sure if i understand you question, but i think this is your problem.

The middle slate behaves very shaky because the enter and leave events are fired way to often. This make the animation look strange and wonky, but it will also take a lot from the device to process it.

That is why you should use a debounce, more in this article if you are interested: debounce

The code snippet below will make sure that your mouse enter / leave events won't be triggered more than once every 50 ms

    function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
$('#slateMid').on('mouseleave', debounce(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    },50));

$('#slateMid').on('mouseenter', debounce(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    },50));


问:
Python timeout context manager with threads
I have timeout context manager that works perfectly with signals but it raises error in multithread mode because signals work only in main thread.

```<code>def timeout_handler(signum, frame):
    raise TimeoutException()

@contextmanager
def timeout(seconds):
    old_handler = signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)
        signal.signal(signal.SIGALRM, old_handler)
</code>```

I've seen decorator implementation of timeout but I don't know how to pass yield inside class derived from threading.Thread. My variant won't work.

```<code>@contextmanager
def timelimit(seconds):
    class FuncThread(threading.Thread):
        def run(self):
            yield

    it = FuncThread()
    it.start()
    it.join(seconds)

    if it.isAlive():
        raise TimeoutException()
</code>```

答:
I know it's late but I'm only just reading this, but what about creating your own signaller/context manager? I'm new to python would love feedback from experienced devs this implementation.

This is based off of the answer from "Mr Fooz"

```<code>class TimeoutSignaller(Thread):
    def __init__(self, limit, handler):
        Thread.__init__(self)
        self.limit = limit
        self.running = True
        self.handler = handler
        assert callable(handler), "Timeout Handler needs to be a method"

    def run(self):
        timeout_limit = datetime.datetime.now() + datetime.timedelta(seconds=self.limit)
        while self.running:
            if datetime.datetime.now() >= timeout_limit:
                self.handler()
                self.stop_run()
                break

    def stop_run(self):
        self.running = False

class ProcessContextManager:
    def __init__(self, process, seconds=0, minutes=0, hours=0):
        self.seconds = (hours * 3600) + (minutes * 60) + seconds
        self.process = process
        self.signal = TimeoutSignaller(self.seconds, self.signal_handler)

    def __enter__(self):
        self.signal.start()
        return self.process

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.signal.stop_run()

    def signal_handler(self):
        # Make process terminate however you like
        # using self.process reference
        raise TimeoutError("Process took too long to execute")
</code>```

Use case:

```<code>with ProcessContextManager(my_proc) as p:
    # do stuff e.g.
    p.execute()
</code>```

Body:
I have timeout context manager that works perfectly with signals but it raises error in multithread mode because signals work only in main thread.

def timeout_handler(signum, frame):
    raise TimeoutException()

@contextmanager
def timeout(seconds):
    old_handler = signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)
        signal.signal(signal.SIGALRM, old_handler)

I've seen decorator implementation of timeout but I don't know how to pass yield inside class derived from threading.Thread. My variant won't work.

@contextmanager
def timelimit(seconds):
    class FuncThread(threading.Thread):
        def run(self):
            yield

    it = FuncThread()
    it.start()
    it.join(seconds)

    if it.isAlive():
        raise TimeoutException()

Body:
I know it's late but I'm only just reading this, but what about creating your own signaller/context manager? I'm new to python would love feedback from experienced devs this implementation.

This is based off of the answer from "Mr Fooz"

class TimeoutSignaller(Thread):
    def __init__(self, limit, handler):
        Thread.__init__(self)
        self.limit = limit
        self.running = True
        self.handler = handler
        assert callable(handler), "Timeout Handler needs to be a method"

    def run(self):
        timeout_limit = datetime.datetime.now() + datetime.timedelta(seconds=self.limit)
        while self.running:
            if datetime.datetime.now() >= timeout_limit:
                self.handler()
                self.stop_run()
                break

    def stop_run(self):
        self.running = False

class ProcessContextManager:
    def __init__(self, process, seconds=0, minutes=0, hours=0):
        self.seconds = (hours * 3600) + (minutes * 60) + seconds
        self.process = process
        self.signal = TimeoutSignaller(self.seconds, self.signal_handler)

    def __enter__(self):
        self.signal.start()
        return self.process

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.signal.stop_run()

    def signal_handler(self):
        # Make process terminate however you like
        # using self.process reference
        raise TimeoutError("Process took too long to execute")

Use case:

with ProcessContextManager(my_proc) as p:
    # do stuff e.g.
    p.execute()


问:
How to create a byte[] image intent to share with Email
I am trying to create a byte[] image intent to share with the email app on my Xamarin.Android application. So far I have the following:

```<code>public void ShareAsync(byte[] image, string message)
{
    if (string.IsNullOrEmpty(message) || image == null)
        return;

    var sharingIntent = new Intent();
    sharingIntent.SetAction(Intent.ActionSend);
    sharingIntent.SetType("image/*");
    sharingIntent.PutExtra(Intent.ExtraStream, image);
    sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(sharingIntent, message));
}
</code>```

This pops up the share dialog and I can click the email app but it returns a blank email.

Is it possible to share a byte[] with the email app so that the image appears as part of the body or an attachment?

答:
That depends on the email app if it will accept the image as a byte array, which I'm sure won't work for most part of email apps for the reason of that you can't put a lot of data in the intent. It's size is limited to 1 MB of data, so you won't be able to pass byte array larger than 1 MB in any case, even if the email app supported this type of image sharing.

So the short answer is that there is no way.

Body:
I am trying to create a byte[] image intent to share with the email app on my Xamarin.Android application. So far I have the following:

public void ShareAsync(byte[] image, string message)
{
    if (string.IsNullOrEmpty(message) || image == null)
        return;

    var sharingIntent = new Intent();
    sharingIntent.SetAction(Intent.ActionSend);
    sharingIntent.SetType("image/*");
    sharingIntent.PutExtra(Intent.ExtraStream, image);
    sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
    Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(sharingIntent, message));
}

This pops up the share dialog and I can click the email app but it returns a blank email.

Is it possible to share a byte[] with the email app so that the image appears as part of the body or an attachment?


问:
Uncaught Error: Unexpected value 'PropDecoratorFactory' imported by the module 'AppModule'. Please add a @NgModule annotation
I'm building a simple AngularJS 2/s app, and I try to pass a variable from a nested child component to the parent component, so the parent can change it, like so:

Child:

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    @Component({
      selector: 'app-copm-player',
      templateUrl: './copm-player.component.html',
      styleUrls: ['./copm-player.component.css']
    })
    export class CopmPlayerComponent implements OnInit {
      // @Input('isRoundStart') isRoundStart: boolean = false;
      isRoundStart: boolean = false;
      // @Input('RandNum') randNums = 0;
      randNums = 0;
      constructor() { }
      ngOnInit() {
      }

    }</code>```

```

<p>Parent:</p>

```

    import { Component, OnInit, ViewChild, Input} from '@angular/core';
    import {CopmPlayerComponent} from './copm-player/copm-player.component';

    @Component({
      selector: 'app-players-board',
      templateUrl: './players-board.component.html',
      styleUrls: ['./players-board.component.css'],

    })
    export class PlayersBoardComponent implements OnInit {
      @ViewChild(CopmPlayerComponent) compPlayer: CopmPlayerComponent;
      onStartRound(){
        console.log(this.compPlayer.isRoundStart);

        this.compPlayer.isRoundStart = true;
        console.log(this.compPlayer.isRoundStart);

      }
      constructor() { }

      ngOnInit() {
      }

    }```
</div>
</div>

</code>```

my IDE says there is no probem, but when I try to run the entire app I get this error messsage:

```<code>> Uncaught Error: Unexpected value 'PropDecoratorFactory' imported by the module 'AppModule'. Please add a @NgModule annotation.
    at syntaxError (compiler.es5.js:1689)
    at compiler.es5.js:15373
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.es5.js:15356)
    at JitCompiler._loadModules (compiler.es5.js:26679)
    at JitCompiler._compileModuleAndComponents (compiler.es5.js:26652)
    at JitCompiler.compileModuleAsync (compiler.es5.js:26581)
    at PlatformRef_._bootstrapModuleWithZone (core.es5.js:4595)
    at PlatformRef_.bootstrapModule (core.es5.js:4581)
    at Object.107 (main.ts:10)
</code>```

The wierd thing is I couldn't find any decorator name "PropDecoratorFactory", and I see no such decleration in app.module.ts:

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { Input } from '@angular/core';
    import { ViewChild } from '@angular/core';
    import { Output } from '@angular/core';
    import { AppComponent } from './app.component';
    import { HeaderComponent } from './header/header.component';
    import { PlayersBoardComponent } from './players-board/players-board.component';
    import { PlayerComponent } from './players-board/player/player.component';
    import { ScoresComponent } from './players-board/scores/scores.component';
    import { CopmPlayerComponent } from './players-board/copm-player/copm-player.component';

    @NgModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        PlayersBoardComponent,
        PlayerComponent,
        ScoresComponent,
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ViewChild
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }</code>```

```

Can anyone tell me what the problem is? What can I do to fix it?
Thanks

答:
You shall remove ViewChild from list of imports in AppModule.</p>

```<code>imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ViewChild <--- Remove this one
  ],
</code>```

Body:
I'm building a simple AngularJS 2/s app, and I try to pass a variable from a nested child component to the parent component, so the parent can change it, like so:

Child:

    @Component({
      selector: 'app-copm-player',
      templateUrl: './copm-player.component.html',
      styleUrls: ['./copm-player.component.css']
    })
    export class CopmPlayerComponent implements OnInit {
      // @Input('isRoundStart') isRoundStart: boolean = false;
      isRoundStart: boolean = false;
      // @Input('RandNum') randNums = 0;
      randNums = 0;
      constructor() { }
      ngOnInit() {
      }

    }

Parent:

    import { Component, OnInit, ViewChild, Input} from '@angular/core';
    import {CopmPlayerComponent} from './copm-player/copm-player.component';

    @Component({
      selector: 'app-players-board',
      templateUrl: './players-board.component.html',
      styleUrls: ['./players-board.component.css'],

    })
    export class PlayersBoardComponent implements OnInit {
      @ViewChild(CopmPlayerComponent) compPlayer: CopmPlayerComponent;
      onStartRound(){
        console.log(this.compPlayer.isRoundStart);

        this.compPlayer.isRoundStart = true;
        console.log(this.compPlayer.isRoundStart);

      }
      constructor() { }

      ngOnInit() {
      }

    }

my IDE says there is no probem, but when I try to run the entire app I get this error messsage:

> Uncaught Error: Unexpected value 'PropDecoratorFactory' imported by the module 'AppModule'. Please add a @NgModule annotation.
    at syntaxError (compiler.es5.js:1689)
    at compiler.es5.js:15373
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.es5.js:15356)
    at JitCompiler._loadModules (compiler.es5.js:26679)
    at JitCompiler._compileModuleAndComponents (compiler.es5.js:26652)
    at JitCompiler.compileModuleAsync (compiler.es5.js:26581)
    at PlatformRef_._bootstrapModuleWithZone (core.es5.js:4595)
    at PlatformRef_.bootstrapModule (core.es5.js:4581)
    at Object.107 (main.ts:10)

The wierd thing is I couldn't find any decorator name "PropDecoratorFactory", and I see no such decleration in app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { Input } from '@angular/core';
    import { ViewChild } from '@angular/core';
    import { Output } from '@angular/core';
    import { AppComponent } from './app.component';
    import { HeaderComponent } from './header/header.component';
    import { PlayersBoardComponent } from './players-board/players-board.component';
    import { PlayerComponent } from './players-board/player/player.component';
    import { ScoresComponent } from './players-board/scores/scores.component';
    import { CopmPlayerComponent } from './players-board/copm-player/copm-player.component';

    @NgModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        PlayersBoardComponent,
        PlayerComponent,
        ScoresComponent,
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ViewChild
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

Can anyone tell me what the problem is? What can I do to fix it?
Thanks

Body:
You shall remove ViewChild from list of imports in AppModule.

imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ViewChild <--- Remove this one
  ],


问:
traslate query "delete join" from postgres to oracle
Hallo to everyone and thanks for the attention.I have to "traslate" from postgres to oracle this "delete join query"

```<code>DELETE FROM AAA USING BBB WHERE (AAA.date = BBB.date)
 AND (AAA.idtipo = BBB.idtipo)
 AND (AAA.tariffario = BBB.tariffario)
 AND (BBB.IDOrigine = 20 )
</code>```

Thanks !!
Gian

答:
Use exists:

```<code>DELETE FROM AAA
   WHERE EXISTS (SELECT 1
                 FROM BBB
                 WHERE (AAA.date = BBB.date) AND
                       (AAA.idtipo = BBB.idtipo) AND
                       (AAA.tariffario = BBB.tariffario) AND
                       (BBB.IDOrigine = 20 )
                );
</code>```

This is standard SQL and should work in both Postgres and Oracle (and other databases as well).

Body:
Hallo to everyone and thanks for the attention.I have to "traslate" from postgres to oracle this "delete join query"

DELETE FROM AAA USING BBB WHERE (AAA.date = BBB.date)
 AND (AAA.idtipo = BBB.idtipo)
 AND (AAA.tariffario = BBB.tariffario)
 AND (BBB.IDOrigine = 20 )

Thanks !!
Gian

Body:
Use exists:

DELETE FROM AAA
   WHERE EXISTS (SELECT 1
                 FROM BBB
                 WHERE (AAA.date = BBB.date) AND
                       (AAA.idtipo = BBB.idtipo) AND
                       (AAA.tariffario = BBB.tariffario) AND
                       (BBB.IDOrigine = 20 )
                );

This is standard SQL and should work in both Postgres and Oracle (and other databases as well).


问:
Extract a function name inside a macro
In C, we often have to run such code

```<code>if (! somefun(x, y, z)) {
    perror("somefun")
}
</code>```

Is it possible to create a macro which, used as follows:

```<code>#define chkerr ...
chkerr(somefun(x, y, z));
</code>```

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

```<code>chkerr(somefun, x, y, z)
</code>```

答:
You can use the original call format:

```<code>chkerr(somefun(x, y, z));
</code>```

With a macro and a helper function:

```<code>#define chkerr(fcall) \
    if (!fcall) { \
        perror(extract_fname(#fcall)); \
    }
const char *extract_fname(const char *fcall);
</code>```

The extract_fname function would get text and return everything until the open parenthesis.

Title: Extract a function name inside a macro

Body:
In C, we often have to run such code

if (! somefun(x, y, z)) {
    perror("somefun")
}

Is it possible to create a macro which, used as follows:

#define chkerr ...
chkerr(somefun(x, y, z));

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

chkerr(somefun, x, y, z)

Body:
You can use the original call format:

chkerr(somefun(x, y, z));

With a macro and a helper function:

#define chkerr(fcall) \
    if (!fcall) { \
        perror(extract_fname(#fcall)); \
    }
const char *extract_fname(const char *fcall);

The extract_fname function would get text and return everything until the open parenthesis.


问:
AsyncTask onPostExecute never gets called
I am not sure what I am doing wrong but onPostExecute never gets called.

Created a base class called BaseActivity.java

From my original Activity I extended this class.

Placed PostToOpenFeint class inside BaseActivity

Called it from the UI thread from the main activity my doing:

```<code>new PostToOpenFeint.execute();
</code>```

The onPreExecute(), doInBackground(..) gets triggered, but for some reason the onPostExecute never gets called.

Thank you in Advance!

Dave

```<code> private class PostToOpenFeint extends AsyncTask<Void, Void, Void> {
  /*
   * (non-Javadoc)
   *
   * @see android.os.AsyncTask#doInBackground(Params[])
   */
  @Override
  protected Void doInBackground(Void... params) {
   // does all the work here
   return null;
  }

  /*
   * (non-Javadoc)
   *
   * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
   */
  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   super.onPostExecute(result);
   Toast.makeText(MainScreen.this, "Done syncing", Toast.LENGTH_LONG).show();
  }

  /*
   * (non-Javadoc)
   *
   * @see android.os.AsyncTask#onPreExecute()
   */
  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   super.onPreExecute();
   Toast.makeText(MainScreen.this, "About to sync all your scores", Toast.LENGTH_LONG).show();
  }
</code>```

Looking into it more, this is what I was able to observe. For example if I place this call:

```<code> new PostToOpenFeint.execute();
</code>```

right after onCreate of the Activity, then everything works fine. If I place this call say inside a button listener.

```<code>settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
   new PostToOpenFeint.execute();
}
});
</code>```

The onPostExecute() never gets called, not sure what I am doing wrong. The restriction I read was to call this from UI Thread and I am calling it from UI thread.

答: Maybe the code in doInBackground() never returns?</p>

ContentLicense: CC BY-SA 2.5

Body:
I am not sure what I am doing wrong but onPostExecute never gets called.

Created a base class called BaseActivity.java

From my original Activity I extended this class.

Placed PostToOpenFeint class inside BaseActivity

Called it from the UI thread from the main activity my doing:

new PostToOpenFeint.execute();

The onPreExecute(), doInBackground(..) gets triggered, but for some reason the onPostExecute never gets called.

Thank you in Advance!

Dave

 private class PostToOpenFeint extends AsyncTask<Void, Void, Void> {
  /*
   * (non-Javadoc)
   *
   * @see android.os.AsyncTask#doInBackground(Params[])
   */
  @Override
  protected Void doInBackground(Void... params) {
   // does all the work here
   return null;
  }

  /*
   * (non-Javadoc)
   *
   * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
   */
  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   super.onPostExecute(result);
   Toast.makeText(MainScreen.this, "Done syncing", Toast.LENGTH_LONG).show();
  }

  /*
   * (non-Javadoc)
   *
   * @see android.os.AsyncTask#onPreExecute()
   */
  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   super.onPreExecute();
   Toast.makeText(MainScreen.this, "About to sync all your scores", Toast.LENGTH_LONG).show();
  }

Looking into it more, this is what I was able to observe. For example if I place this call:

 new PostToOpenFeint.execute();

right after onCreate of the Activity, then everything works fine. If I place this call say inside a button listener.

settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
   new PostToOpenFeint.execute();
}
});

The onPostExecute() never gets called, not sure what I am doing wrong. The restriction I read was to call this from UI Thread and I am calling it from UI thread.


问:
Match any word of a List/Array in a Sentence java
I have an List of word like below

```<code>List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");
</code>```

How can I understand a String Contains any one of the word of the List. like....

```<code>String name1 = "Adam Smith";      // false (not found)
String name2 = "Late H Milton";   // true  (found Late)
String name3 = "S/O Furi Kerman"; // true  (found S/O)
String name4 = "Conl Faruk";      // false (not found)
String name5 = "Furi Kerman WO";  // true  (found WO)
</code>```

Regular Expression highly appreciated.

答:
```<code>boolean containsForbiddenName = forbiddenWordList.stream()
     .anyMatch(forbiddenName -> name.toLowerCase()
          .contains(forbiddenName.toLowerCase()));
</code>```

Body:
I have an List of word like below

List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");

How can I understand a String Contains any one of the word of the List. like....

String name1 = "Adam Smith";      // false (not found)
String name2 = "Late H Milton";   // true  (found Late)
String name3 = "S/O Furi Kerman"; // true  (found S/O)
String name4 = "Conl Faruk";      // false (not found)
String name5 = "Furi Kerman WO";  // true  (found WO)

Regular Expression highly appreciated.


问:
Why do my pagination displays the max number of pages when it's supposed to display only 1 or 2 pages?
Search.php

Why do my pagination display the max number of pages when my query searched 7 results that only needs to display 1 page

```<code>                <?php // $s=$ _GET[ 's']; $catnum=$ _GET[ 'catnum']; $type=$ _GET[ 'type']; $low=$ _GET[ 'low']; $high=$ _GET[ 'high']; $unit_size_x=$ _GET[ 'unit_size_x']; $unit_size_y=$ _GET[ 'unit_size_y']; $post_tag=$ _GET[ 'post_tag']; // if($catnum){ // $taxquerysp[]=a rray( // 'taxonomy'=>'property_categories', // 'include_children'=>false, // 'field'=>'term_id', // 'operator'=>'AND' // ); // } // if($post_tag){ // $taxquerysp[] = array( // 'taxonomy'=>'property_categories', // 'include_children'=>false, // 'field'=>'slug', // 'operator'=>'AND' // ); // } // if($type){ // $metaquerysp[] = array( // 'key'=>'type', // 'value'=> $type, // 'compare'=>'=', // ); // } $metaquerysp[] = array( 'key'=>'monthly_rent', 'value'=>array( $low, $high ), 'compare'=>'BETWEEN', 'type'=>'NUMERIC', ); $metaquerysp[] = array( 'key'=>'unit_size', 'value'=>array( $unit_size_x, $unit_size_y ), 'compare'=>'BETWEEN', 'type'=>'NUMERIC', ); $metaquerysp['relation'] = 'AND'; ?>

                <?php $paged=g et_query_var( 'paged') ? get_query_var( 'paged') : 1; $args=a rray( 'post_type'=> 'property', 'posts_per_page' => 9, 'orderby' => 'DATE', 'paged' => $paged, // 's' =>$s // 'tax_query' => $taxquerysp, 'meta_query' => $metaquerysp ); ?>
                <?php $query=n ew WP_Query( $args ); ?>

                <div class="mtb30" style=" display: block;">
                    <?php if($query -> have_posts()): ?>
                    <?php while($query -> have_posts()): $query->the_post();?>

                            <p>
                                <?php the_excerpt(); ?>
                            </p>
                        </div>
                    </div>
                    <?php endwhile; ?>
                    <?php else: ?>

                    <?php endif; ?>
                </div>

                <?php wp_reset_postdata();?>

            </div>
        </div>

    <?php if (function_exists( "pagination")) { pagination($wp_query->max_num_pages); } ?>
</code>```

Here is the url of my work link

答:
You're storing the filtered results in the variable $query, but later, for your pagination, you're using $wp_query instead.

It should work if you change:

```<code>pagination($wp_query->max_num_pages);
</code>```

to

```<code>pagination($query->max_num_pages);
</code>```

That should give you the max_num_pages for the query you actually made.

Body:
Search.php

Why do my pagination display the max number of pages when my query searched 7 results that only needs to display 1 page

                <?php // $s=$ _GET[ 's']; $catnum=$ _GET[ 'catnum']; $type=$ _GET[ 'type']; $low=$ _GET[ 'low']; $high=$ _GET[ 'high']; $unit_size_x=$ _GET[ 'unit_size_x']; $unit_size_y=$ _GET[ 'unit_size_y']; $post_tag=$ _GET[ 'post_tag']; // if($catnum){ // $taxquerysp[]=a rray( // 'taxonomy'=>'property_categories', // 'include_children'=>false, // 'field'=>'term_id', // 'operator'=>'AND' // ); // } // if($post_tag){ // $taxquerysp[] = array( // 'taxonomy'=>'property_categories', // 'include_children'=>false, // 'field'=>'slug', // 'operator'=>'AND' // ); // } // if($type){ // $metaquerysp[] = array( // 'key'=>'type', // 'value'=> $type, // 'compare'=>'=', // ); // } $metaquerysp[] = array( 'key'=>'monthly_rent', 'value'=>array( $low, $high ), 'compare'=>'BETWEEN', 'type'=>'NUMERIC', ); $metaquerysp[] = array( 'key'=>'unit_size', 'value'=>array( $unit_size_x, $unit_size_y ), 'compare'=>'BETWEEN', 'type'=>'NUMERIC', ); $metaquerysp['relation'] = 'AND'; ?>

                <?php $paged=g et_query_var( 'paged') ? get_query_var( 'paged') : 1; $args=a rray( 'post_type'=> 'property', 'posts_per_page' => 9, 'orderby' => 'DATE', 'paged' => $paged, // 's' =>$s // 'tax_query' => $taxquerysp, 'meta_query' => $metaquerysp ); ?>
                <?php $query=n ew WP_Query( $args ); ?>

                    <?php if($query -> have_posts()): ?>
                    <?php while($query -> have_posts()): $query->the_post();?>

                                <?php the_excerpt(); ?>

                    <?php endwhile; ?>
                    <?php else: ?>

                    <?php endif; ?>

                <?php wp_reset_postdata();?>

    <?php if (function_exists( "pagination")) { pagination($wp_query->max_num_pages); } ?>

Here is the url of my work link

Body:
You're storing the filtered results in the variable $query, but later, for your pagination, you're using $wp_query instead.

It should work if you change:

pagination($wp_query->max_num_pages);

to

pagination($query->max_num_pages);

That should give you the max_num_pages for the query you actually made.


问:
Angular: Many components listen to key events - refactor?
In a couple of my angular components I listen to key events

```<code>@HostListener('window:keydown', ['$event']) keyInput(event: KeyboardEvent) {
   if (this.isActive) {
      if (event.keyCode === 27) {
         // do something
      }
   }
 }
</code>```

In this case it is just one key, but I have them with more too

Anyway, I see duplicate code in my project here. So, is this acceptable or should I refactor this ? If so, what would be the preferred way?

答:
I would create a service that other components can subscribe to when the event occurs. For example:

@Injectable()
public class KeyEventService {
    private keydown$: Observable;

    constructor() {
        this.keydown$ = Observable.fromEvent(window, "keydown");
    }

    public getEscapeKeyListener() {
        return this.keydown$.filter((event: KeyboardEvent) => event.keyCode === 27);
    }
}
```

<p>This allows you to setup the listener for the event once and then filter it to the appropriate keypress. The public methods return observables that filter on specific keys or multiple keys without having to setup a new observable. Then in your component you would use it like this:</p>

<pre class="lang-js prettyprint-override"><code>@Component({})
public class MyComponent implements OnInit, OnDestroy {
    private keyListenerSub: Subscription;

    constructor(private keyEventSvc: KeyEventService) { }

    ngOnInit() {
        this.keyListenerSub = this.keyEventSvc.getEscapeKeyListener().subscribe(() => {
            /* respond to keypress */
        });
    }

    ngOnDestroy() {
        this.keyListenerSub.unsubscribe();
    }
}
</code>```

This allows you to set up the listener only once and then in your components you can just take the appropriate action when the event you want occurs.

Body:
In a couple of my angular components I listen to key events

@HostListener('window:keydown', ['$event']) keyInput(event: KeyboardEvent) {
   if (this.isActive) {
      if (event.keyCode === 27) {
         // do something
      }
   }
 }

In this case it is just one key, but I have them with more too

Anyway, I see duplicate code in my project here. So, is this acceptable or should I refactor this ? If so, what would be the preferred way?

Body:
I would create a service that other components can subscribe to when the event occurs. For example:

@Injectable()
public class KeyEventService {
    private keydown$: Observable;

    constructor() {
        this.keydown$ = Observable.fromEvent(window, "keydown");
    }

    public getEscapeKeyListener() {
        return this.keydown$.filter((event: KeyboardEvent) => event.keyCode === 27);
    }
}

This allows you to setup the listener for the event once and then filter it to the appropriate keypress. The public methods return observables that filter on specific keys or multiple keys without having to setup a new observable. Then in your component you would use it like this:

@Component({})
public class MyComponent implements OnInit, OnDestroy {
    private keyListenerSub: Subscription;

    constructor(private keyEventSvc: KeyEventService) { }

    ngOnInit() {
        this.keyListenerSub = this.keyEventSvc.getEscapeKeyListener().subscribe(() => {
            /* respond to keypress */
        });
    }

    ngOnDestroy() {
        this.keyListenerSub.unsubscribe();
    }
}

This allows you to set up the listener only once and then in your components you can just take the appropriate action when the event you want occurs.


问:
Multiple optional parameters for report
My report has 2 required parameters (Source; Location and 2 optional ones Access Type; Access Complication) I've tested the query and can prove that works correctly. The report also works if I populate every param.

Without a complication param, all complications should return, but no patients. If only access type is chosen, it should get a list of patients with all complications assigned to the chosen access types. But I get no records if either of the parameters is left out.

I tried this hasvalue formula in the select expert, to no avail

```<code>(not hasValue({?AccessType}) OR {Command.AccessType} = {?AccessType})
 and
(not hasValue({?AccessComplication) OR {Command.AccessComplication} <= {?AccessComplication})
</code>```

If I set a new formula for Access Type in the select expert, then for Access Complication with the above hasvalue formula, then whichever one I do second overwrites the first. They don't seem to be able to exist alongside each other

答:
When used in a formula, optional parameters become mandatory parameters. End of story.

To achieve something similar, send your param as all or * (which means all records in SQL). Before selecting all the data, check your "optional" parameter values, and if they have all or * write a selection formula without including those parameters.

Pseudo code should look like this for 2 mandatory and 2 optional params:

```<code>if param3 = "all" or param4 = "all"
    if param3 = "all" and param4 = "all" select data only with param1 and param 2
    else
        if param3 = "all" select data without param3
        if param4 = "all" select data without param4
else select data with all params
</code>```

Title: Multiple optional parameters for report

Body:
My report has 2 required parameters (Source; Location and 2 optional ones Access Type; Access Complication) I've tested the query and can prove that works correctly. The report also works if I populate every param.

Without a complication param, all complications should return, but no patients. If only access type is chosen, it should get a list of patients with all complications assigned to the chosen access types. But I get no records if either of the parameters is left out.

I tried this hasvalue formula in the select expert, to no avail

(not hasValue({?AccessType}) OR {Command.AccessType} = {?AccessType})
 and
(not hasValue({?AccessComplication) OR {Command.AccessComplication} <= {?AccessComplication})

If I set a new formula for Access Type in the select expert, then for Access Complication with the above hasvalue formula, then whichever one I do second overwrites the first. They don't seem to be able to exist alongside each other

Body:
When used in a formula, optional parameters become mandatory parameters. End of story.

To achieve something similar, send your param as all or * (which means all records in SQL). Before selecting all the data, check your "optional" parameter values, and if they have all or * write a selection formula without including those parameters.

Pseudo code should look like this for 2 mandatory and 2 optional params:

if param3 = "all" or param4 = "all"
    if param3 = "all" and param4 = "all" select data only with param1 and param 2
    else
        if param3 = "all" select data without param3
        if param4 = "all" select data without param4
else select data with all params


问:
How to store arrays in MySQL?
I have two tables in MySQL. Table Person has the following columns:

id
name
fruits

The fruits column may hold null or an array of strings like ('apple', 'orange', 'banana'), or ('strawberry'), etc. The second table is Table Fruit and has the following three columns:

fruit_name
color
price

apple
red
2

orange
orange
3

-----------
--------
------

So how should I design the fruits column in the first table so that it can hold array of strings that take values from the fruit_name column in the second table? Since there is no array data type in MySQL, how should I do it?

答:
Use database field type BLOB to store arrays.

Ref: http://us.php.net/manual/en/function.serialize.php

Return Values

Returns a string containing a byte-stream representation of value that
can be stored anywhere.

Note that this is a binary string which may include null bytes, and
needs to be stored and handled as such. For example, serialize()
output should generally be stored in a BLOB field in a database,
rather than a CHAR or TEXT field.

ContentLicense: CC BY-SA 4.0

Title: How to store arrays in MySQL?


问:
Custom post type not displaying in custom wp query loop
I'm trying not to repeat questions that've already been asked but I haven't been able to debug this so far - I'm sure it's a small thing I'm missing!

I have a single-project.php template that I'd like to include a sidebar with all project custom post types as links. I only seem to be getting 'post' post_type, not my custom post_type (project)

Registered custom post type in functions.php

```<code>function custom_post_type() {
$labels = array(
'name'                  => _x( 'Project', 'Post Type General Name', 'text_domain' ),
    'singular_name'         => _x( 'Project', 'Post Type Singular Name', 'text_domain' ),
    'menu_name'             => __( 'Projects', 'text_domain' ),
    'name_admin_bar'        => __( 'Projects', 'text_domain' ),
    'archives'              => __( 'Item Archives', 'text_domain' ),
    'attributes'            => __( 'Item Attributes', 'text_domain' ),
    'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
    'all_items'             => __( 'All Projects', 'text_domain' ),
    'add_new_item'          => __( 'Add New Item', 'text_domain' ),
    'add_new'               => __( 'Add New', 'text_domain' ),
    'new_item'              => __( 'New Item', 'text_domain' ),
    'edit_item'             => __( 'Edit Item', 'text_domain' ),
    'update_item'           => __( 'Update Item', 'text_domain' ),
    'view_item'             => __( 'View Item', 'text_domain' ),
    'view_items'            => __( 'View Items', 'text_domain' ),
    'search_items'          => __( 'Search Item', 'text_domain' ),
    'not_found'             => __( 'Not found', 'text_domain' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
    'featured_image'        => __( 'Featured Image', 'text_domain' ),
    'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
    'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
    'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
    'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
    'items_list'            => __( 'Items list', 'text_domain' ),
    'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
    'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
);
$args = array(
    'label'                 => __( 'Project', 'text_domain' ),
    'description'           => __( 'Spaceworks projects', 'text_domain' ),
    'labels'                => $labels,
    'supports'              => array( ),
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_position'         => 5,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'post',
);
register_post_type( 'project', $args );

}
add_action( 'init', 'custom_post_type', 0 );
</code>```

Register custom taxonomy in functions.php

```<code>function my_taxonomies_project() {
$labels = array(
'name'              => _x( 'Project Categories', 'taxonomy general name' ),
'singular_name'     => _x( 'Project Category', 'taxonomy singular name' ),
'search_items'      => __( 'Search Project Categories' ),
'all_items'         => __( 'All Project Categories' ),
'parent_item'       => __( 'Parent Project Category' ),
'parent_item_colon' => __( 'Parent Project Category:' ),
'edit_item'         => __( 'Edit Project Category' ),
'update_item'       => __( 'Update Project Category' ),
'add_new_item'      => __( 'Add New Project Category' ),
'new_item_name'     => __( 'New Project Category' ),
'menu_name'         => __( 'Project Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'project_category', 'project', $args );
}
add_action( 'init', 'my_taxonomies_project', 0 );`
</code>```

Single project template: single-project.php

```<code><?php
get_header();

while ( have_posts() ) : the_post(); ?>

<div class="projects">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php the_content(); ?>
</div>

<?php
endwhile;
wp_reset_query();
?>

<div class="col-12 col-lg-3 col-xl-3 hidden-lg-up allProjects">
#project loop for mobile

<?php
$tax_query_args = array(
    array(
        'post_type'         => array('post', 'project'),
     ),
);

$taxQuery = new WP_Query( $tax_query_args );

if ($taxQuery->have_posts())
while ($taxQuery->have_posts() ) : $taxQuery->the_post();
?>

<div class="projectCard">
<a href="<?php echo get_permalink(); ?>">
<p><?php the_title() ?></p>
</a>
</div>

<?php endwhile; wp_reset_query();

get_footer();
?>
</code>```

Can anyone spot an issue? This has been bugging me for a few days!
All the best

答:
Change

```<code>$tax_query_args = array(
    array(
        'post_type'         => array('post', 'project'),
     ),
);
</code>```

to

```<code>$tax_query_args = array(
    'post_type' => array('post', 'project')
);
</code>```

Quick edit:

When using the WP_Query class to make a query, and then you call the the_post method, use wp_reset_postdata after the closing while statement.

No need to reset the query, since it hasn't changed. :)

Body:
I'm trying not to repeat questions that've already been asked but I haven't been able to debug this so far - I'm sure it's a small thing I'm missing!

I have a single-project.php template that I'd like to include a sidebar with all project custom post types as links. I only seem to be getting 'post' post_type, not my custom post_type (project)

Registered custom post type in functions.php

function custom_post_type() {
$labels = array(
'name'                  => _x( 'Project', 'Post Type General Name', 'text_domain' ),
    'singular_name'         => _x( 'Project', 'Post Type Singular Name', 'text_domain' ),
    'menu_name'             => __( 'Projects', 'text_domain' ),
    'name_admin_bar'        => __( 'Projects', 'text_domain' ),
    'archives'              => __( 'Item Archives', 'text_domain' ),
    'attributes'            => __( 'Item Attributes', 'text_domain' ),
    'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
    'all_items'             => __( 'All Projects', 'text_domain' ),
    'add_new_item'          => __( 'Add New Item', 'text_domain' ),
    'add_new'               => __( 'Add New', 'text_domain' ),
    'new_item'              => __( 'New Item', 'text_domain' ),
    'edit_item'             => __( 'Edit Item', 'text_domain' ),
    'update_item'           => __( 'Update Item', 'text_domain' ),
    'view_item'             => __( 'View Item', 'text_domain' ),
    'view_items'            => __( 'View Items', 'text_domain' ),
    'search_items'          => __( 'Search Item', 'text_domain' ),
    'not_found'             => __( 'Not found', 'text_domain' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
    'featured_image'        => __( 'Featured Image', 'text_domain' ),
    'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
    'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
    'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
    'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
    'items_list'            => __( 'Items list', 'text_domain' ),
    'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
    'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
);
$args = array(
    'label'                 => __( 'Project', 'text_domain' ),
    'description'           => __( 'Spaceworks projects', 'text_domain' ),
    'labels'                => $labels,
    'supports'              => array( ),
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_position'         => 5,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'post',
);
register_post_type( 'project', $args );

}
add_action( 'init', 'custom_post_type', 0 );

Register custom taxonomy in functions.php

function my_taxonomies_project() {
$labels = array(
'name'              => _x( 'Project Categories', 'taxonomy general name' ),
'singular_name'     => _x( 'Project Category', 'taxonomy singular name' ),
'search_items'      => __( 'Search Project Categories' ),
'all_items'         => __( 'All Project Categories' ),
'parent_item'       => __( 'Parent Project Category' ),
'parent_item_colon' => __( 'Parent Project Category:' ),
'edit_item'         => __( 'Edit Project Category' ),
'update_item'       => __( 'Update Project Category' ),
'add_new_item'      => __( 'Add New Project Category' ),
'new_item_name'     => __( 'New Project Category' ),
'menu_name'         => __( 'Project Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'project_category', 'project', $args );
}
add_action( 'init', 'my_taxonomies_project', 0 );`

Single project template: single-project.php

<?php
get_header();

while ( have_posts() ) : the_post(); ?>

<?php the_title( '
', '
' ); ?>
<?php the_content(); ?>

<?php
endwhile;
wp_reset_query();
?>

#project loop for mobile

<?php
$tax_query_args = array(
    array(
        'post_type'         => array('post', 'project'),
     ),
);

$taxQuery = new WP_Query( $tax_query_args );

if ($taxQuery->have_posts())
while ($taxQuery->have_posts() ) : $taxQuery->the_post();
?>

<a href="<?php echo get_permalink(); ?>">

<?php the_title() ?>

<?php endwhile; wp_reset_query();

get_footer();
?>

Can anyone spot an issue? This has been bugging me for a few days!
All the best

Body:
Change

$tax_query_args = array(
    array(
        'post_type'         => array('post', 'project'),
     ),
);

to

$tax_query_args = array(
    'post_type' => array('post', 'project')
);

Quick edit:

When using the WP_Query class to make a query, and then you call the the_post method, use wp_reset_postdata after the closing while statement.

No need to reset the query, since it hasn't changed. :)


问:
How to implement push notification for multiple Android apps?
Our products still target OS 1.5+, so C2DM in Froyo is not an option.

I think wrap a persistent TCP connection in a service would be feasible. But I'm still wondering how to use one service to receive notifications for multiple applications. I don't want to create service and connection for each of my apps.

Should I try to register the same service in all my apps, or release the service as a single app?

Thanks in advance.

答:
You can have a look at what Urban Airship has done with their implementation of push notifications for Android pre-2.2. They have a centralized application called AirMail Control Panel which configures push settings for multiple applications that use their push service.

The documentation is here.


问:
Download Module on NPM start
I want to know if there is a easy way to download file before other code runs. I need file.js to be downloaded first from my server because I am requiring it in my app on different places. I know I can do something like that.

```<code>let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
    function(response) {
    response.pipe(file);
});
</code>```

But if I assume correctly, the file is written asynchronously. So when I require that file I have just empty object or error.

So what is the best way to download that file synchronously at first on npm start?

答:
You can get such result using npm script pre hooks.

Assuming your start-up script is called "start" , in your package.json add
script called "prestart" in wich you want to run script that executes file downloading. and in will be automatically run when you call npm run start

For example:

package.json :

```<code>{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "prestart": "node pre-start.js"
  },
  "author": "",
  "license": "ISC"
}
</code>```

index.js:

```<code>const value = require('./new-file.json');
console.log(value);
</code>```

pre-start.js:

```<code>const fs = require('fs');

setTimeout(function() {
    const value = {
        "one" : 1,
        "two" : 2
    };

    fs.writeFileSync('new-file.json', JSON.stringify(value));
}, 1000)
</code>```

Here is a link to article with more detailed information:
http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html

The other way is to run your other code after file is written:

```<code>let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
    function(response) {
    response.pipe(file);
    file.on('finish',function(){
      // run your code here
    }
});
</code>```

Title: Download Module on NPM start

Body:
I want to know if there is a easy way to download file before other code runs. I need file.js to be downloaded first from my server because I am requiring it in my app on different places. I know I can do something like that.

let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
    function(response) {
    response.pipe(file);
});

But if I assume correctly, the file is written asynchronously. So when I require that file I have just empty object or error.

So what is the best way to download that file synchronously at first on npm start?

Body:
You can get such result using npm script pre hooks.

Assuming your start-up script is called "start" , in your package.json add
script called "prestart" in wich you want to run script that executes file downloading. and in will be automatically run when you call npm run start

For example:

package.json :

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "prestart": "node pre-start.js"
  },
  "author": "",
  "license": "ISC"
}

index.js:

const value = require('./new-file.json');
console.log(value);

pre-start.js:

const fs = require('fs');

setTimeout(function() {
    const value = {
        "one" : 1,
        "two" : 2
    };

    fs.writeFileSync('new-file.json', JSON.stringify(value));
}, 1000)

Here is a link to article with more detailed information:
http://www.marcusoft.net/2015/08/pre-and-post-hooks-for-npm-scripting.html

The other way is to run your other code after file is written:

let file = fs.createWriteStream(path.join(__dirname, 'file.js'));
let request = http.get("http://expample.com/file.js",
    function(response) {
    response.pipe(file);
    file.on('finish',function(){
      // run your code here
    }
});


问:
Make a function
I have this function:

```<code>def gnumeric_func (data, columns):
  data[columns] = data[columns].apply(lambda x: pd.factorize(x)[0])
  return data
column_list = data.iloc[:, 7:14]
gnumeric_func (data, column_list)
</code>```

How to implement iloc without causing any errors like this:

```<code> Must pass DataFrame with boolean values only
</code>```

答:
I think help this sample:</p>

```<code>df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':list('aaabbb'),
                   'E':list('autrob'),
                   'F':list('etreeb')})

print (df)
   A  B  C  D  E  F
0  a  4  7  a  a  e
1  b  5  8  a  u  t
2  c  4  9  a  t  r
3  d  5  4  b  r  e
4  e  5  2  b  o  e
5  f  4  3  b  b  b

def gnumeric_func (data, columns):
  data[columns] = data[columns].apply(lambda x: pd.factorize(x)[0])
  return data

#select columns names by positions
column_list = df.columns[3:5]
print (column_list)
Index(['D', 'E'], dtype='object')

df2 = gnumeric_func(df, column_list)
print (df2)
   A  B  C  D  E  F
0  a  4  7  0  0  e
1  b  5  8  0  1  t
2  c  4  9  0  2  r
3  d  5  4  1  3  e
4  e  5  2  1  4  e
5  f  4  3  1  5  b
</code>```

Title: Make a function

Body:
I have this function:

def gnumeric_func (data, columns):
  data[columns] = data[columns].apply(lambda x: pd.factorize(x)[0])
  return data
column_list = data.iloc[:, 7:14]
gnumeric_func (data, column_list)

How to implement iloc without causing any errors like this:

 Must pass DataFrame with boolean values only

Body:
I think help this sample:

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':list('aaabbb'),
                   'E':list('autrob'),
                   'F':list('etreeb')})

print (df)
   A  B  C  D  E  F
0  a  4  7  a  a  e
1  b  5  8  a  u  t
2  c  4  9  a  t  r
3  d  5  4  b  r  e
4  e  5  2  b  o  e
5  f  4  3  b  b  b

def gnumeric_func (data, columns):
  data[columns] = data[columns].apply(lambda x: pd.factorize(x)[0])
  return data

#select columns names by positions
column_list = df.columns[3:5]
print (column_list)
Index(['D', 'E'], dtype='object')

df2 = gnumeric_func(df, column_list)
print (df2)
   A  B  C  D  E  F
0  a  4  7  0  0  e
1  b  5  8  0  1  t
2  c  4  9  0  2  r
3  d  5  4  1  3  e
4  e  5  2  1  4  e
5  f  4  3  1  5  b


问:
JS - How to add a button into a div with appendChid
I want to create a sidebar using only JavaScript, but I can't add the close button to the div.
I tried this:

```<code>var sideb = document.createElement("Div");
    sideb.style.height = "100%";
    sideb.style.width = "0px";
    sideb.style.backgroundColor = "rgb(30,30,30)";
    sideb.style.top = "0px";
    sideb.style.right = "0px";
    sideb.style.margin = "0px";
    sideb.style.padding = "0px";
    sideb.style.position = "fixed"

    document.body.appendChild(sideb);

var close = document.createElement("Button");
    close.innerText = "close";
    close.onclick = close;

    document.body.sideb.appendChild(close)
</code>```

But it's not working.

答:
```<code>document.body.sideb.appendChild(close)
</code>```

body doesn't have a property/key called sideb

you just need

```<code>sideb.appendChild(close)
</code>```

Body:
I want to create a sidebar using only JavaScript, but I can't add the close button to the div.
I tried this:

var sideb = document.createElement("Div");
    sideb.style.height = "100%";
    sideb.style.width = "0px";
    sideb.style.backgroundColor = "rgb(30,30,30)";
    sideb.style.top = "0px";
    sideb.style.right = "0px";
    sideb.style.margin = "0px";
    sideb.style.padding = "0px";
    sideb.style.position = "fixed"

    document.body.appendChild(sideb);

var close = document.createElement("Button");
    close.innerText = "close";
    close.onclick = close;

    document.body.sideb.appendChild(close)

But it's not working.

Body:
document.body.sideb.appendChild(close)

body doesn't have a property/key called sideb

you just need

sideb.appendChild(close)


问:
knockout contentditable binding with array values
I am trying to create a custom binding to edit content with HTML5 on a table following this link example and I can't get it to work with an observableArray().

The table is being show in the view with foreach data-bindig like this:

```<code>        <tbody data-bind="foreach: customers">
            <tr data-bind="attr: {id: $index}">
                <td style="text-align: center;">
                    <span class="label label-primary" data-bind="html: Id"></span>
                </td>
                <td data-bind="html: Name, attr: {id: 'Nome'}, contentEditable: true"></td>
            </tr>
        </tbody>
</code>```

The view model is this:

function ViewModel() {

```<code>        var self = this;

        self.data = '@jsonList';
        self.customers = ko.observableArray(JSON.parse(self.data));
        self.editable = ko.observable(false);

        for (i = 0; i < self.customers().length; i++) {

            self.customers()[i]['Details'] = '/Anagrafica/Details/' + self.customers()[i]['Id'];

            self.customers()[i]['Delete'] = '/Anagrafica/Delete/' + self.customers()[i]['Id'];

        };

        ko.bindingHandlers.htmlEdit= {

            update: function (element, valueAccessor) {
                var value = ko.unwrap(valueAccessor());
            }
        };

        ko.bindingHandlers.contentEditable = {

            init: function (element, valueAccessor, allBindingsAccessor) {
                var value = ko.unwrap(valueAccessor()),
                    htmlEdit= allBindingsAccessor().htmlEdit;

                $(element).on("input", function () {
                    if (ko.isWriteableObservable(htmlEdit)) {
                        htmlEdit(this.innerHTML);
                    }
                });
            },

            update: function (element, valueAccessor) {
                var value = ko.unwrap(valueAccessor());
                element.contentEditable = value;
                $(element).trigger("input");
            }

        };
    };

    var viewModel = new ViewModel();

    ko.applyBindings(viewModel);
</code>```

At the moment I am confused on the code itself, because I don't understand how to set it to point to the elements on the array.

Note: The array is populated, I have no problems in show the content.

Edit: here I add the JSFiddle https://jsfiddle.net/wxn34p45/ for a better read of the code

答:
Looks like you had a spelling mistake Name instead of name:

```<code><td data-bind="html: name, attr: {id: 'Nome'}, contentEditable: true"></td>
</code>```

Also customers was not an observableArray (in your fiddle at least):

```<code>self.customers = ko.observableArray([{"Id":1111,"name":" [Malena]"},{"Id":2222,"name":" [Maria]"},{"Id":3333,"name":" [Merio]"},{"Id":4444,"name":" [Milena]"}]);
</code>```

I have updated the fiddle (also got it running with knockout, and I have displayed a copy of the ViewModel to help with debugging), the content is now editable.

```<code><h4>View Model</h4>
  <pre data-bind="text: ko.toJSON($data, null, 2)">```
```

<p>Is this now giving the desired effect?</p>

<p>https://jsfiddle.net/asindlemouat/wxn34p45/1/</p>

<p><strong>EDIT</strong> </p>

<p>With the further information provided I have managed to make this editable, I have removed the editable from the customers array and used the one in the ViewModel.</p>

<p>As it is looping through the customers array you need to call the editable observable in the ViewModel using $parent.editable. </p>

```

```

Updated fiddle: https://jsfiddle.net/asindlemouat/wxn34p45/8/

Body:
I am trying to create a custom binding to edit content with HTML5 on a table following this link example and I can't get it to work with an observableArray().

The table is being show in the view with foreach data-bindig like this:

The view model is this:

function ViewModel() {

        var self = this;

        self.data = '@jsonList';
        self.customers = ko.observableArray(JSON.parse(self.data));
        self.editable = ko.observable(false);

        for (i = 0; i < self.customers().length; i++) {

            self.customers()[i]['Details'] = '/Anagrafica/Details/' + self.customers()[i]['Id'];

            self.customers()[i]['Delete'] = '/Anagrafica/Delete/' + self.customers()[i]['Id'];

        };

        ko.bindingHandlers.htmlEdit= {

            update: function (element, valueAccessor) {
                var value = ko.unwrap(valueAccessor());
            }
        };

        ko.bindingHandlers.contentEditable = {

            init: function (element, valueAccessor, allBindingsAccessor) {
                var value = ko.unwrap(valueAccessor()),
                    htmlEdit= allBindingsAccessor().htmlEdit;

                $(element).on("input", function () {
                    if (ko.isWriteableObservable(htmlEdit)) {
                        htmlEdit(this.innerHTML);
                    }
                });
            },

            update: function (element, valueAccessor) {
                var value = ko.unwrap(valueAccessor());
                element.contentEditable = value;
                $(element).trigger("input");
            }

        };
    };

    var viewModel = new ViewModel();

    ko.applyBindings(viewModel);

At the moment I am confused on the code itself, because I don't understand how to set it to point to the elements on the array.

Note: The array is populated, I have no problems in show the content.

Edit: here I add the JSFiddle https://jsfiddle.net/wxn34p45/ for a better read of the code

Body:
Looks like you had a spelling mistake Name instead of name:

<td data-bind="html: name, attr: {id: 'Nome'}, contentEditable: true"></td>

Also customers was not an observableArray (in your fiddle at least):

self.customers = ko.observableArray([{"Id":1111,"name":" [Malena]"},{"Id":2222,"name":" [Maria]"},{"Id":3333,"name":" [Merio]"},{"Id":4444,"name":" [Milena]"}]);

I have updated the fiddle (also got it running with knockout, and I have displayed a copy of the ViewModel to help with debugging), the content is now editable.

<h4>View Model</h4>
  <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>

Is this now giving the desired effect?

https://jsfiddle.net/asindlemouat/wxn34p45/1/

EDIT

With the further information provided I have managed to make this editable, I have removed the editable from the customers array and used the one in the ViewModel.

As it is looping through the customers array you need to call the editable observable in the ViewModel using $parent.editable.

<tbody data-bind="foreach: customers">
  <tr data-bind="attr: {id: $index}">
    <td style="text-align: center;">
      <span class="label label-primary" data-bind="html: Id"></span>
    </td>
    <td data-bind="html: name, attr: {id: 'Nome'}, contentEditable: $parent.editable"></td>
    <td></td>
  </tr>
</tbody>

Updated fiddle: https://jsfiddle.net/asindlemouat/wxn34p45/8/


问:
Migrate orders, products, categories, customers from Magento 1.5 to Magento 2.0
I have Magento store with old version 1.5.0.1.

I want to migrate data from Magento 1 to Magento 2.

It has 5000 products, 1000 orders, 4000 customers. Now I am going to create my website with Magento 2.1.7 version. I want to migrate all data like orders, products, categories, customers from Magento old server 1.5 to new server 2.1.7.

Can anyone tell me please what is the best way to migrate data?

Thanks in advance.

答:
For up-gradation you can use https://www.ubertheme.com/magento-extensions-2-x/magento-2-data-migration-pro/ this module.

or export all data in csv format and upload the csv in magento2 according to magento2 or customer password is md5 in magento 1 you need to use the below extension to support md5 password
https://github.com/sinisa86/Sinwashere_LegacyAuthentication


问:
SQL SERVER 2008. How to select one row only based on dates
```<code>Select MIN([appdate]), CustID, CustAtt, Surname, Firstname, itemType
From table
Where appDate > (getdate())
Group by CustID, CustAtt

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 51406   27/EY08  E        EX      13/09/2017     Gas
 51406   27/EY09  E        EX      11/12/2017     Solid A
 51406   27/EY10  E        EX      06/06/2018     Liquid A
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      30/08/2017     Solid
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 53248   16/EK15  J        JX      17/07/2017     Solid B
 89835   911528   K        KX      08/05/2018     Solid B
</code>```

The above is a snippet of my output from the above script,  but isn't giving me the desired output. I want to only select one row for each CustID & CustAtt from my dataset based on the appdate column.

The desired output should include the next earliest date from current date, in the case the dates are the same any given row is acceptable:
The output table should yield:

```<code>CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 89835   911528   K        KX      08/05/2018     Solid B
</code>```

答:
You have to use HAVING keyword. It can filter "after group".

```<code>SELECT
 MIN([appdate]),
 id,
 type
FROM
 [table]
WHERE
 appdate > GETDATE()
GROUP BY
 id, type
HAVING
  COUNT(*) > 1 -- select only records, that have duplicates, based on our "group by"
ORDER BY
 id
</code>```

added 12.07.17:
(for revised question)

Count row number (partion by CustID & CustAtt, order by appDate) and then select first one for each one.

```<code>;WITH cte AS (
    SELECT
        *,
        Row_number() OVER(
          PARTITION BY CustID, CustAtt ORDER BY appDate
        ) row_number
    FROM
        table
    )
SELECT
  *
FROM
  cte
WHERE
  row_number = 1
</code>```

Body:
Select MIN([appdate]), CustID, CustAtt, Surname, Firstname, itemType
From table
Where appDate > (getdate())
Group by CustID, CustAtt

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 51406   27/EY08  E        EX      13/09/2017     Gas
 51406   27/EY09  E        EX      11/12/2017     Solid A
 51406   27/EY10  E        EX      06/06/2018     Liquid A
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      30/08/2017     Solid
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 53248   16/EK15  J        JX      17/07/2017     Solid B
 89835   911528   K        KX      08/05/2018     Solid B

The above is a snippet of my output from the above script,  but isn't giving me the desired output. I want to only select one row for each CustID & CustAtt from my dataset based on the appdate column.

The desired output should include the next earliest date from current date, in the case the dates are the same any given row is acceptable:
The output table should yield:

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX
 67119   413555   D        DX
 51406   27/EY07  E        EX      14/07/2017     Liquid
 82820   410053   F        FX
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 89835   911528   K        KX      08/05/2018     Solid B

Body:
You have to use HAVING keyword. It can filter "after group".

SELECT
 MIN([appdate]),
 id,
 type
FROM
 [table]
WHERE
 appdate > GETDATE()
GROUP BY
 id, type
HAVING
  COUNT(*) > 1 -- select only records, that have duplicates, based on our "group by"
ORDER BY
 id

added 12.07.17:
(for revised question)

Count row number (partion by CustID & CustAtt, order by appDate) and then select first one for each one.

;WITH cte AS (
    SELECT
        *,
        Row_number() OVER(
          PARTITION BY CustID, CustAtt ORDER BY appDate
        ) row_number
    FROM
        table
    )
SELECT
  *
FROM
  cte
WHERE
  row_number = 1


问:
Parse send an image in Cloud Code as parameter
I want to send a picture as a parameter without saving before in Parse. I use the javascriptSDK</p>

```<code>Parse.Cloud.run("saveImage", { photo:???, title:title, description:description}).then(function(result) {
}, function(error) {});
</code>```

答:
You upload the image data as parameter of your cloud code function, e.g. with iOS SDK:

```<code>PFCloud.callFunction(inBackground: "uploadImage", withParameters: ["imageData": image.highQualityJPEGData]]) { (response, error) in
    ...
}
</code>```

On the server you save the image file:

```<code>Parse.Cloud.define("uploadImage", function(request, response) {

    var imageData = request.params.imageData;
    var imageFile = new Parse.File("image.png", imageData, "image/png");

    imageFile.save(null, {useMasterKey: true})
    .then(
        function() {
            response.success();
        },
        function(error) {
            response.error(error.message);
        }
    );
});
</code>```

Body:
I want to send a picture as a parameter without saving before in Parse. I use the javascriptSDK

Parse.Cloud.run("saveImage", { photo:???, title:title, description:description}).then(function(result) {
}, function(error) {});

Body:
You upload the image data as parameter of your cloud code function, e.g. with iOS SDK:

PFCloud.callFunction(inBackground: "uploadImage", withParameters: ["imageData": image.highQualityJPEGData]]) { (response, error) in
    ...
}

On the server you save the image file:

Parse.Cloud.define("uploadImage", function(request, response) {

    var imageData = request.params.imageData;
    var imageFile = new Parse.File("image.png", imageData, "image/png");

    imageFile.save(null, {useMasterKey: true})
    .then(
        function() {
            response.success();
        },
        function(error) {
            response.error(error.message);
        }
    );
});


问:
Creating EditText with button
I must create EditText with button inside and assign functions which will run after pressing the button. Then I would like to make it reusable - somehow add it as an element to my Activity. I was wondering about extending EditTextView and adding button and creating functions inside of it.
Any suggestions/ tutorials?</p>

答:
If you want some icon or button inside edit text you can achieve like this,

Note: In this just I am using setCompoundDrawablesWithIntrinsicBounds,
  So if you want to change the icon position you can achieve that using
  setCompoundDrawablesWithIntrinsicBounds in setIcon.

Create some CustomEditText like this,

```<code>public class MKEditText extends AppCompatEditText {

    public interface IconClickListener {
        public void onClick();
    }

    private IconClickListener mIconClickListener;

    private static final String TAG = MKEditText.class.getSimpleName();

    private final int EXTRA_TOUCH_AREA = 50;
    private Drawable mDrawable;
    private boolean touchDown;

    public MKEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MKEditText(Context context) {
        super(context);
    }

    public MKEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void showRightIcon() {
        mDrawable = ContextCompat.getDrawable(getContext(), R.drawable.ic_android_black_24dp);

        setIcon();
    }

    public void setIconClickListener(IconClickListener iconClickListener) {
        mIconClickListener = iconClickListener;
    }

    private void setIcon() {
        Drawable[] drawables = getCompoundDrawables();

        setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], mDrawable, drawables[3]);

        setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        setSelection(getText().length());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int right = getRight();
        final int drawableSize = getCompoundPaddingRight();
        final int x = (int) event.getX();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (x + EXTRA_TOUCH_AREA >= right - drawableSize && x <= right + EXTRA_TOUCH_AREA) {
                    touchDown = true;
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (x + EXTRA_TOUCH_AREA >= right - drawableSize && x <= right + EXTRA_TOUCH_AREA && touchDown) {
                    touchDown = false;
                    if (mIconClickListener != null) {
                        mIconClickListener.onClick();
                    }
                    return true;
                }
                touchDown = false;
                break;

        }
        return super.onTouchEvent(event);
    }
}
</code>```

If you want to change the touch area you can change the
  EXTRA_TOUCH_AREA values default I gave as 50.

And for Enable the button and click listener you can call from your Activity or Fragment like this,

```<code>MKEditText mkEditText = (MKEditText) findViewById(R.id.password);
mkEditText.showRightIcon();
mkEditText.setIconClickListener(new MKEditText.IconClickListener() {
            @Override
            public void onClick() {
              // You can do action here. ex you can start activity here like this
               startActivityForResult(new Intent(MainActivity.this, SampleActivity.class), 1);
            }
        });
</code>```

Title: Creating EditText with button

Body:
If you want some icon or button inside edit text you can achieve like this,

Note: In this just I am using setCompoundDrawablesWithIntrinsicBounds,
  So if you want to change the icon position you can achieve that using
  setCompoundDrawablesWithIntrinsicBounds in setIcon.

Create some CustomEditText like this,

public class MKEditText extends AppCompatEditText {

    public interface IconClickListener {
        public void onClick();
    }

    private IconClickListener mIconClickListener;

    private static final String TAG = MKEditText.class.getSimpleName();

    private final int EXTRA_TOUCH_AREA = 50;
    private Drawable mDrawable;
    private boolean touchDown;

    public MKEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MKEditText(Context context) {
        super(context);
    }

    public MKEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void showRightIcon() {
        mDrawable = ContextCompat.getDrawable(getContext(), R.drawable.ic_android_black_24dp);

        setIcon();
    }

    public void setIconClickListener(IconClickListener iconClickListener) {
        mIconClickListener = iconClickListener;
    }

    private void setIcon() {
        Drawable[] drawables = getCompoundDrawables();

        setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], mDrawable, drawables[3]);

        setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        setSelection(getText().length());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int right = getRight();
        final int drawableSize = getCompoundPaddingRight();
        final int x = (int) event.getX();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (x + EXTRA_TOUCH_AREA >= right - drawableSize && x <= right + EXTRA_TOUCH_AREA) {
                    touchDown = true;
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (x + EXTRA_TOUCH_AREA >= right - drawableSize && x <= right + EXTRA_TOUCH_AREA && touchDown) {
                    touchDown = false;
                    if (mIconClickListener != null) {
                        mIconClickListener.onClick();
                    }
                    return true;
                }
                touchDown = false;
                break;

        }
        return super.onTouchEvent(event);
    }
}

If you want to change the touch area you can change the
  EXTRA_TOUCH_AREA values default I gave as 50.

And for Enable the button and click listener you can call from your Activity or Fragment like this,

MKEditText mkEditText = (MKEditText) findViewById(R.id.password);
mkEditText.showRightIcon();
mkEditText.setIconClickListener(new MKEditText.IconClickListener() {
            @Override
            public void onClick() {
              // You can do action here. ex you can start activity here like this
               startActivityForResult(new Intent(MainActivity.this, SampleActivity.class), 1);
            }
        });