问:
How can JavaScript check if element is a specific color?
I have a piece of code that needs to check if an element matches a color, and if it does, change it. Otherwise it is set to a default color.

var caps = $("#caps");
if (caps.css('background-color') == "rgb(225, 0, 0)") {
  $('body').on('click', '#caps', function(event) {
    $('.clight').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    $('#l2').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    event.preventDefault();
  } else {
    $('.clight').css('background-color', 'white');
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.caps {
  /* Caps button CSS */
  width: 70px;
  font-size: 12px;
  line-height: 12px;
}

.clight {
  /* Caps button light CSS */
  width: 10px;
  height: 10px;
  top: 10px;
  margin-left: 1px;
  background-color: grey;
  position: relative;
  border-radius: 50%;
}</code>```

 Caps
Lock

```

It doesn't work however. All I am trying to do is to switch on the caps lock light when you click, and switch it back of if you click it again, almost like a toggle.

答:
I found the solution to be very simple:</p>

```<code>$('body').on('click', '#caps', function(event){
      $('.clight, #l2').toggleClass('on');
});
</code>```

Body:
I have a piece of code that needs to check if an element matches a color, and if it does, change it. Otherwise it is set to a default color.

var caps = $("#caps");
if (caps.css('background-color') == "rgb(225, 0, 0)") {
  $('body').on('click', '#caps', function(event) {
    $('.clight').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    $('#l2').css({
      'background-color': 'red',
      'box-shadow': '0px 0px 20px yellow'
    });
    event.preventDefault();
  } else {
    $('.clight').css('background-color', 'white');
  });

.caps {
  /* Caps button CSS */
  width: 70px;
  font-size: 12px;
  line-height: 12px;
}

.clight {
  /* Caps button light CSS */
  width: 10px;
  height: 10px;
  top: 10px;
  margin-left: 1px;
  background-color: grey;
  position: relative;
  border-radius: 50%;
}

 Caps
Lock

It doesn't work however. All I am trying to do is to switch on the caps lock light when you click, and switch it back of if you click it again, almost like a toggle.

Body:
I found the solution to be very simple:

$('body').on('click', '#caps', function(event){
      $('.clight, #l2').toggleClass('on');
});


来源: stackexchange

问:
Django: Model Form "object has no attribute 'cleaned_data'"
I am trying to make a search form for one of my classes. The model of the form is:

```<code>from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category

class SearchForm(forms.ModelForm):
    authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)
    category = ModelChoiceField (queryset=Category.objects.all(),required=False)
    class Meta:
        model = Book
        fields = ["title"]
</code>```

And the view I'm using is:

```<code>from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User

def search_book(request):
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            form = SearchForm(request.POST)
            stitle = form.cleaned_data['title']
            sauthor = form.cleaned_data['author']
            scategory = form.cleaned_data['category']
    else:
        form = SearchForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))
</code>```

The form shows up fine, but when I submit it I get an error: 'SearchForm' object has no attribute 'cleaned_data'

I'm not sure what's going on, can someone help me out? Thanks!

答:
For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to make a search form for one of my classes. The model of the form is:

from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category

class SearchForm(forms.ModelForm):
    authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)
    category = ModelChoiceField (queryset=Category.objects.all(),required=False)
    class Meta:
        model = Book
        fields = ["title"]

And the view I'm using is:

from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User

def search_book(request):
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            form = SearchForm(request.POST)
            stitle = form.cleaned_data['title']
            sauthor = form.cleaned_data['author']
            scategory = form.cleaned_data['category']
    else:
        form = SearchForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

The form shows up fine, but when I submit it I get an error: 'SearchForm' object has no attribute 'cleaned_data'

I'm not sure what's going on, can someone help me out? Thanks!


问:
Safari and IE ajax issues with subsequent calls (.then)
I've got this code:

```<code>var request1 = this.add(prod_id, pack_id_combination, button, pack_qty).then(function(rdata1){
  // this always works
  this.add(prod_id, case_id_combination, button, case_qty).then(function(rdata2){
    // this sometimes (random) doesn't work
  }.bind(this), function(req, status, error){ console.log('case error',req, status, error); });
}.bind(this), function(){ console.log('pack error'); });
</code>```

I omitted the rest of the code because it's a huge class and it's also  impossible to build a jsfiddle, too much things.

But here's the facts:

my js points to a php file returning data. It does ajax calls via the add() function (see below)

it always works for the first call, it sometimes doesn't work for the second call.

on the log, status = 'error', error = '' (empty, so no info here)

I also know for sure that the second add(), if called alone with the same params, will always work.

Furthermore, it has these problems ONLY in safari and IE, not in chrome, ff, android

Furthermore, it has these problems ONLY if tested online, while in my local environment always works properly.

Safari says it looses the connection. This is the only information I can get

the add() function is quite trivial:

```<code>add:function(idProduct, idCombination, callerElement, quantity){
    return $.ajax({
        type: 'POST'
        ,headers: { "cache-control": "no-cache" }
        ,url: baseUri + '?rand=' + new Date().getTime()
        ,cache: false
        ,dataType : "json"
        ,data: 'controller=cart&add=1&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): '')
        ,success:function(data, status, req){
            console.log('ok');
        }
        ,error:function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.responseText, textStatus, errorThrown);
        }
    });
},//end add()
</code>```

So, my question: is there a way to avoid this problem? Is it a common pitfall? Are there common practices to avoid this kind of issues?

答:
Ok, my issue was solved by using a GET request instead of a POST one.

Probably both Safari and IE are not able to correctly manage 2 subsequent ajax POST requests, at least in specific circumstances. Or, the jquery 2.1.3 (version used here) implementation has some kind of subtle  problems/bugs.

But since I often have random css/js issues with both IE (surprise...) and Safari (yes...), I guess it's them and not jquery.

ContentLicense: CC BY-SA 3.0

Body:
I've got this code:

var request1 = this.add(prod_id, pack_id_combination, button, pack_qty).then(function(rdata1){
  // this always works
  this.add(prod_id, case_id_combination, button, case_qty).then(function(rdata2){
    // this sometimes (random) doesn't work
  }.bind(this), function(req, status, error){ console.log('case error',req, status, error); });
}.bind(this), function(){ console.log('pack error'); });

I omitted the rest of the code because it's a huge class and it's also  impossible to build a jsfiddle, too much things.

But here's the facts:

my js points to a php file returning data. It does ajax calls via the add() function (see below)

it always works for the first call, it sometimes doesn't work for the second call.

on the log, status = 'error', error = '' (empty, so no info here)

I also know for sure that the second add(), if called alone with the same params, will always work.

Furthermore, it has these problems ONLY in safari and IE, not in chrome, ff, android

Furthermore, it has these problems ONLY if tested online, while in my local environment always works properly.

Safari says it looses the connection. This is the only information I can get

the add() function is quite trivial:

add:function(idProduct, idCombination, callerElement, quantity){
    return $.ajax({
        type: 'POST'
        ,headers: { "cache-control": "no-cache" }
        ,url: baseUri + '?rand=' + new Date().getTime()
        ,cache: false
        ,dataType : "json"
        ,data: 'controller=cart&add=1&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): '')
        ,success:function(data, status, req){
            console.log('ok');
        }
        ,error:function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.responseText, textStatus, errorThrown);
        }
    });
},//end add()

So, my question: is there a way to avoid this problem? Is it a common pitfall? Are there common practices to avoid this kind of issues?


问:
Why to use where clause even when Having can be used for the same purpose?
It is known that Having clause works same as where clause but where clause only works with present table columns and not aggregate columns.

Can we always use Having and is there some specific functionality which where is preferable than having, like performance issues?

答:
They reflect two different steps the dbms will do when executing a query. Take this example:

```<code>select  person_id, count(distinct child_id)
from    parenthood
where   child_age > 6
group by person_id
having  count(distinct child_id) > 1
</code>```

What you need to do is

filtering the total rows

aggregating the remaining rows

filtering the resulting groups

Writing that query like

```<code>select  person_id, count(distinct child_id)
from    parenthood
group by person_id
having  child_age > 6 and count(distinct child_id) > 1
</code>```

wouldn't change the steps the dbms would do, and would make the query a bit harder to understand.

In fact, while latest versions of MySQL allow some creative combinatinos of group by, aggregation functions and having, most dbms expect you to use having only in combination with group by, and only applied to aggregation functions, and will return an error otherwise.

Body:
They reflect two different steps the dbms will do when executing a query. Take this example:

select  person_id, count(distinct child_id)
from    parenthood
where   child_age > 6
group by person_id
having  count(distinct child_id) > 1

What you need to do is

filtering the total rows

aggregating the remaining rows

filtering the resulting groups

Writing that query like

select  person_id, count(distinct child_id)
from    parenthood
group by person_id
having  child_age > 6 and count(distinct child_id) > 1

wouldn't change the steps the dbms would do, and would make the query a bit harder to understand.

In fact, while latest versions of MySQL allow some creative combinatinos of group by, aggregation functions and having, most dbms expect you to use having only in combination with group by, and only applied to aggregation functions, and will return an error otherwise.


问:
QT: How to set resizeEvent for widget without overriding the widget class
I have a labels with images added through the designer, and I want to handle their resize event. So I want a specific function to be called once they are resized.
How should I do that?</p>

答:
You can install an event filter to the labels.

For more details you can see the Qt documentation about Event filters

Example:

```<code>MainWidget::MainWidget(QWidget* parent) : QWidget(parent)
{
   ui.setupUi(this);
   theLabel->installEventFilter(this);
}

bool MainWidget::eventFilter(QObject* o, QEvent* e)
{
    if(e->type() == QEvent::Resize)
    {
        //manage the resize event
    }
    return false;
}
</code>```

Body:
You can install an event filter to the labels.

For more details you can see the Qt documentation about Event filters

Example:

MainWidget::MainWidget(QWidget* parent) : QWidget(parent)
{
   ui.setupUi(this);
   theLabel->installEventFilter(this);
}

bool MainWidget::eventFilter(QObject* o, QEvent* e)
{
    if(e->type() == QEvent::Resize)
    {
        //manage the resize event
    }
    return false;
}


问:
How to get previous LI in multi-level UL/LI elements
I have following html code:

```<code><ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>
</code>```

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

答:
Hey you can do something like this.. i tested this locally and it's working...

```<code><ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>
</code>```

and jQuery like this

```<code>   <script type="text/javascript">
    $('li').on('click',function(event) {

    event.stopPropagation();

    if ($(this).children("ul").length > 0) {

       if($(this).prev('li').length > 0) {

         console.log($(this).prev('li').text());

       }

     } else if ($(this).prev('li').length > 0 && $(this).prev('li').children("ul").length > 0 ) {

       console.log($(this).prev('li').children("ul").find("li:last").text());

     } else if($(this).prev('li').length > 0) {

          console.log($(this).prev('li').clone().children().remove().end().text());

     } else if ($(this).is(":first-child"))  {

        console.log($(this).parent('ul').parent('li').clone().children().remove().end().text().trim());

     } else {

        console.log($(this).closest('ul').prev('li').text());

     }

     });
    </script>
</code>```

PS: Don't forget too include jQuery

Body:
I have following html code:

Parameter1

Group1

Parameter2

Parameter3

Parameter4

Group2

Parameter5

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

Body:
Hey you can do something like this.. i tested this locally and it's working...

<ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>

and jQuery like this

   <script type="text/javascript">
    $('li').on('click',function(event) {

    event.stopPropagation();

    if ($(this).children("ul").length > 0) {

       if($(this).prev('li').length > 0) {

         console.log($(this).prev('li').text());

       }

     } else if ($(this).prev('li').length > 0 && $(this).prev('li').children("ul").length > 0 ) {

       console.log($(this).prev('li').children("ul").find("li:last").text());

     } else if($(this).prev('li').length > 0) {

          console.log($(this).prev('li').clone().children().remove().end().text());

     } else if ($(this).is(":first-child"))  {

        console.log($(this).parent('ul').parent('li').clone().children().remove().end().text().trim());

     } else {

        console.log($(this).closest('ul').prev('li').text());

     }

     });
    </script>

PS: Don't forget too include jQuery

ContentLicense: CC BY-SA 4.0


问:
threads in cpp is giving error
```<code>int main()
{
    std::thread t1(processVideo, "video1.mp4");
    std::thread t2(processVideo, "video1.mp4");
    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
    t2.join();
    destroyAllWindows();
    return EXIT_SUCCESS;
}
void processVideo(char* videoFilename) {
//process the video file
}
</code>```

Whenever I run the code, I get the following error:

```<code>1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): error C2672: 'std::invoke': no matching overloaded function found

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): note: With the following template arguments:

1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): note: '_Callable=void (__cdecl *)(char *)'

1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): note: '_Types={const char *}'

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

I tried to add

```<code>std::thread t1(processVideo,this, "video1.mp4");
</code>```

but it is giving me error while compiling.

This only be used inside a nonstatic member function.

答:
The function void processVideo(char* videoFilename) takes a non-const char*.

The string "video1.mp4" is a const char*, which is incompatible with the function.

The error messages actually indicate this, but it's hard to see the wood for the trees.

Title: threads in cpp is giving error

Body:
int main()
{
    std::thread t1(processVideo, "video1.mp4");
    std::thread t2(processVideo, "video1.mp4");
    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
    t2.join();
    destroyAllWindows();
    return EXIT_SUCCESS;
}
void processVideo(char* videoFilename) {
//process the video file
}

Whenever I run the code, I get the following error:

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): error C2672: 'std::invoke': no matching overloaded function found

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): note: With the following template arguments:

1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): note: '_Callable=void (__cdecl *)(char *)'

1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\thr\xthread(240): note: '_Types={const char *}'

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I tried to add

std::thread t1(processVideo,this, "video1.mp4");

but it is giving me error while compiling.

This only be used inside a nonstatic member function.


问:
Caching linq result using HttpContext
I would like to cache LINQ result for minimize hitting to database:

```<code>var result= _db.Company.Select().ToList();
 HttpContext.Current.Cache.Add("actions",
     result,
     null,
     Cache.NoAbsoluteExpiration,
     TimeSpan.FromMinutes(30));
</code>```

But I get arguments null exceptions.

答:
This code throws compilation error in _db.Company.Select(), select method required func<arg> expression selector of fields, I can't determine why you have call select().

Please specify field selection like Select(x=>x.Id) or just use _db.Company.ToList().

Title: Caching linq result using HttpContext

Body:
I would like to cache LINQ result for minimize hitting to database:

var result= _db.Company.Select().ToList();
 HttpContext.Current.Cache.Add("actions",
     result,
     null,
     Cache.NoAbsoluteExpiration,
     TimeSpan.FromMinutes(30));

But I get arguments null exceptions.


问:
LARAVEL FACEBOOKPROVIDER
I'm having trouble with the recent facebook update with their API.

I was having an error that said

Laravel FacebookProvider Error. Undefined variable: access_token.

I found another question where they said to do this :

In vendor/laravel/socialite/src/Two/FacebookProvider.php

Replace

```<code>parse_str($body, $data);
return $access_token;
</code>```

With

```<code>parse_str($body, $data);
$json = json_decode(key($data));
return $json->access_token;
</code>```

After I made those changes, now i'm having this error

FatalErrorException in FacebookProvider.php line 67:
  Cannot access empty property

Here's the link : https://concoura.com

答:
I had the same problem and I solved with

composer require laravel/socialite:^2.0

Tested with Laravel 5.2 and 5.3

Title: LARAVEL FACEBOOKPROVIDER

Body:
I'm having trouble with the recent facebook update with their API.

I was having an error that said

Laravel FacebookProvider Error. Undefined variable: access_token.

I found another question where they said to do this :

In vendor/laravel/socialite/src/Two/FacebookProvider.php

Replace

parse_str($body, $data);
return $access_token;

With

parse_str($body, $data);
$json = json_decode(key($data));
return $json->access_token;

After I made those changes, now i'm having this error

FatalErrorException in FacebookProvider.php line 67:
  Cannot access empty property

Here's the link : https://concoura.com


问:
How to find a Shelveset using information provided by a CodeReviewRequest
If I have the name and the owner of the Shelveset, I can find it successfully using the following code:

```<code> foreach (Shelveset shelveset in
     versionControlServer.QueryShelvesets(workItem.
         Fields["Associated Context"].Value.ToString(), "NW\\LFreeman"))
</code>```

where workItem is an instance of a CodeReviewRequest workItem.

I can get the name of the CodeReviewRequest from workItem.Fields["Associated Context"]

If I set the owner to null as such, it returns an empty list.  It has been reported to me that this method will only work when the owner is specified as a string.

I am trying to figure out how to get the owner.

Using workItem.Fields["Associated Context Owner"].Value.ToString(), I am able to get the GUID of the owner.

The challenge is now how to convert the GUID to the expected owner which would be "NW\LFreeman".

When I print out the workItems.Fields["Associated Context Owner"].Value.ToString(), here's what I see:

```<code>c3741a78-1a44-4bf6-95b0-f360cd387f3e
</code>```

Is it possible to retrieve "NW\LFreeman" from this GUID?  If so, what method call will enable me to do this mapping?

Edit:

Here is the code that worked for me based on the answer and link given:

```<code>Guid ownerId = new Guid(codeReviewRequestWorkItem.Fields["Associated Context Owner"].Value.ToString());

Guid[] teamFoundationIds = new Guid[1];
teamFoundationIds[0] = ownerId;

TeamFoundationIdentity[] users = ims.ReadIdentities((Guid[])teamFoundationIds, MembershipQuery.None);

Shelveset[] shelves = vcs.QueryShelvesets(codeReviewRequestWorkItem.Fields["Associated Context"].Value.ToString(), users[0].UniqueName.ToString());
</code>```

答: IIdentityManagementService.ReadIdentities is what you are looking for.

Body:
If I have the name and the owner of the Shelveset, I can find it successfully using the following code:

 foreach (Shelveset shelveset in
     versionControlServer.QueryShelvesets(workItem.
         Fields["Associated Context"].Value.ToString(), "NW\\LFreeman"))

where workItem is an instance of a CodeReviewRequest workItem.

I can get the name of the CodeReviewRequest from workItem.Fields["Associated Context"]

If I set the owner to null as such, it returns an empty list.  It has been reported to me that this method will only work when the owner is specified as a string.

I am trying to figure out how to get the owner.

Using workItem.Fields["Associated Context Owner"].Value.ToString(), I am able to get the GUID of the owner.

The challenge is now how to convert the GUID to the expected owner which would be "NW\LFreeman".

When I print out the workItems.Fields["Associated Context Owner"].Value.ToString(), here's what I see:

c3741a78-1a44-4bf6-95b0-f360cd387f3e

Is it possible to retrieve "NW\LFreeman" from this GUID?  If so, what method call will enable me to do this mapping?

Edit:

Here is the code that worked for me based on the answer and link given:

Guid ownerId = new Guid(codeReviewRequestWorkItem.Fields["Associated Context Owner"].Value.ToString());

Guid[] teamFoundationIds = new Guid[1];
teamFoundationIds[0] = ownerId;

TeamFoundationIdentity[] users = ims.ReadIdentities((Guid[])teamFoundationIds, MembershipQuery.None);

Shelveset[] shelves = vcs.QueryShelvesets(codeReviewRequestWorkItem.Fields["Associated Context"].Value.ToString(), users[0].UniqueName.ToString());


问:
Filter ArrayObject (PHP)
I have my data in ArrayObject, simply representing an array. I need to filter the data, function array_filter() would work great. However, it does not work with ArrayObject as argument. What's the best way to treat with this? Is there any standard function which handles filtering for me?

Example:

```<code>$my_data = ArrayObject(array(1,2,3));
$result = array_object_filter($my_data, function($item) { return $item !== 2; });
</code>```

Is there any array_object_filter function?

答:
How about subclassing the ArrayObject and adding a new method to it:</p>

```<code>/**
 * Filters elements using a callback function.
 *
 * @param callable $callback The callback function to use
 *
 * @return self
 */
public function filter(/* callable */ $callback = null)
{
    $this->exchangeArray(array_filter($this->getArrayCopy(), $callback));
    return $this;
}
</code>```

Title: Filter ArrayObject (PHP)

Body:
I have my data in ArrayObject, simply representing an array. I need to filter the data, function array_filter() would work great. However, it does not work with ArrayObject as argument. What's the best way to treat with this? Is there any standard function which handles filtering for me?

Example:

$my_data = ArrayObject(array(1,2,3));
$result = array_object_filter($my_data, function($item) { return $item !== 2; });

Is there any array_object_filter function?

Body:
How about subclassing the ArrayObject and adding a new method to it:

/**
 * Filters elements using a callback function.
 *
 * @param callable $callback The callback function to use
 *
 * @return self
 */
public function filter(/* callable */ $callback = null)
{
    $this->exchangeArray(array_filter($this->getArrayCopy(), $callback));
    return $this;
}


问:
Select odd numbers and does not contain special characters
This is Table WWE :

```<code>    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |
</code>```

Col B is Varchar (100)

How do I select all rows consist of ODD NUMBERS ONLY and does not contain '%' or '*' or alphabets??

I know how to get ODD NUMBERS : colB % 2 <> 0

But I don't know how to EXCLUDE the special characters and to calculate the number as NUMBER since they're stored in VARCHAR

For example in this table, the output will be

```<code>| Dog | 13 |
</code>```

答:
Or use the ISNUMERIC function</p>

```<code>SELECT * FROM WWE WHERE ISNUMERIC(colB) = 1 AND colB % 2 <> 0
</code>```

Body:
This is Table WWE :

    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |

Col B is Varchar (100)

How do I select all rows consist of ODD NUMBERS ONLY and does not contain '%' or '*' or alphabets??

I know how to get ODD NUMBERS : colB % 2 <> 0

But I don't know how to EXCLUDE the special characters and to calculate the number as NUMBER since they're stored in VARCHAR

For example in this table, the output will be

| Dog | 13 |

Body:
Or use the ISNUMERIC function

SELECT * FROM WWE WHERE ISNUMERIC(colB) = 1 AND colB % 2 <> 0


问:
How can I run a Principal Component Analysis on data I have just accumulated in Python Pandas dataframe?
I have a series of functions that process some input data from a .csv file (which is composed of set of DNA sequences). I open the input file, extract the DNA sequences into a dict (called folder_contents in this example), and then take each DNA sequence to be processed by all the functions. The results are stored in a Pandas dataframe in the following code:

```<code>def data_assembler(folder_contents):
    df= DataFrame(columns= ['Column1','Column2','Column3])
    for candidate in folder_contents.keys()[:50]:
        score1= calculate_complex_mfe(folder_contents[candidate][3])
        score2= calculate_complex_ensemble_defect(folder_contents[candidate][3])
        score3= calculate_GC_content(folder_contents[candidate][1])
        df.loc[candidate]= [score1, score2, score3]
    df= df.sort(['score3'], ascending=False)
    df.to_csv(path.join(output, "DNAScoring.csv"))
</code>```

After having assembled this output data, I wanted to run a PCA in order to calculate the Eigenvalues of each scoring parameter and compare the influence of parameters on their data to each other. I have tried doing this by implementing:

```<code>from matplotlib import mlab

###data assembler function
pca= mlab.PCA(df, standardize=True)
df= df.sort(['score3'], ascending=False)
df.to_csv(path.join(output, "DNAScoring.csv"))
</code>```

And although a PCA object is made, I cannot seem to view its contents, or get it to print the values in a new column in my Pandas dataframe. I know that there are several packages that are capable of performing PCA on a dataframe, so I am trying to find which approach is the most appropriate for my dataframe.

答:
I usually did PCA reprojections with the PCA implementation included with scikit-learn, so I am not familiar with matplotlib's PCA, however I think that your problem is trivial: you are saving your PCA-reprojected data in the pca variable, but then you save to csv the original df DataFrame...

Check if pca is still a DataFrame and go with

```<code>pca.to_csv(path.join(output, "DNAScoring.csv"))
</code>```

Edit:
Reading these docs i fear that you are misusing this class: you need a data matrix as input, and since you are constructing a PCA object when you do pca= mlab.PCA(df, standardize=True), inside the pca variable you have a PCA object. Try to read those docs to better understand if you can do what you want to do with this PCA class.

If you can't do what you want to do, i suggest you to have a look to the scikit-learn (sklearn) library at http://scikit-learn.org

In particular, see the docs for sklearn.decomposition.PCA

Body:
I have a series of functions that process some input data from a .csv file (which is composed of set of DNA sequences). I open the input file, extract the DNA sequences into a dict (called folder_contents in this example), and then take each DNA sequence to be processed by all the functions. The results are stored in a Pandas dataframe in the following code:

def data_assembler(folder_contents):
    df= DataFrame(columns= ['Column1','Column2','Column3])
    for candidate in folder_contents.keys()[:50]:
        score1= calculate_complex_mfe(folder_contents[candidate][3])
        score2= calculate_complex_ensemble_defect(folder_contents[candidate][3])
        score3= calculate_GC_content(folder_contents[candidate][1])
        df.loc[candidate]= [score1, score2, score3]
    df= df.sort(['score3'], ascending=False)
    df.to_csv(path.join(output, "DNAScoring.csv"))

After having assembled this output data, I wanted to run a PCA in order to calculate the Eigenvalues of each scoring parameter and compare the influence of parameters on their data to each other. I have tried doing this by implementing:

from matplotlib import mlab

###data assembler function
pca= mlab.PCA(df, standardize=True)
df= df.sort(['score3'], ascending=False)
df.to_csv(path.join(output, "DNAScoring.csv"))

And although a PCA object is made, I cannot seem to view its contents, or get it to print the values in a new column in my Pandas dataframe. I know that there are several packages that are capable of performing PCA on a dataframe, so I am trying to find which approach is the most appropriate for my dataframe.

Body:
I usually did PCA reprojections with the PCA implementation included with scikit-learn, so I am not familiar with matplotlib's PCA, however I think that your problem is trivial: you are saving your PCA-reprojected data in the pca variable, but then you save to csv the original df DataFrame...

Check if pca is still a DataFrame and go with

pca.to_csv(path.join(output, "DNAScoring.csv"))

Edit:
Reading these docs i fear that you are misusing this class: you need a data matrix as input, and since you are constructing a PCA object when you do pca= mlab.PCA(df, standardize=True), inside the pca variable you have a PCA object. Try to read those docs to better understand if you can do what you want to do with this PCA class.

If you can't do what you want to do, i suggest you to have a look to the scikit-learn (sklearn) library at http://scikit-learn.org

In particular, see the docs for sklearn.decomposition.PCA


问:
Loop through checkbox form Laravel
I think I'm missing something small here. I'm new to Laravel and php. I'm getting an error when I try to submit this form with a foreach loop. Each interest should loop in a new insert into my table. Can you help guide me through this stackoverflow, I've read some other solutions but dont quite understand how to apply them to my problem? Here is everything I have:

ERROR:

```<code>ErrorException in InterestController.php line 45:
Trying to get property of non-object
</code>```

$interests = $inputs->interests;------->line 45

InterestController:

```<code>public function store(){

    //Get all the post values
    $inputs = Request::all();
    //From the post values get the array of interest ids that you are sending
    $interests = $inputs->interests;
    //For each interest id, save a new entry in the my_interest table
    foreach ($interests as $interest) {
        $interested_in = new MyInterests;
        $interested_in->user_id = Auth::id();
        $interested_in->interest_id = $interest;
        $interested_in->save();
            //dd($interests);
        }

    }
</code>```

HTML:

```<code>{!! Form::open(array('id'=> 'form1')) !!}

                             @foreach($interests as $interest)

                                    <div class = "form-group">
                                        <div class="col-md-6">
                                            <div class="checkbox">
                                              <label><input type="checkbox" name = "interests[]" value="{{$interest->id}}">{{$interest->name}}</label>
                                            </div>
                                        </div>
                                    </div>
                            @endforeach

                                {!! Form:: submit('Sumbit', ['class' => 'btn btn-primary form-control']) !!}
                                {!! Form::close() !!}
</code>```

答:
First check if interests is Set</p>

```<code>if(isset($interests)){
    foreach ($interests as $interest) {
        $interested_in = new MyInterests;
        $interested_in->user_id = Auth::id();
        $interested_in->interest_id = $interest;
        $interested_in->save();
        //dd($interests);
    }
}
</code>```

Title: Loop through checkbox form Laravel

Body:
I think I'm missing something small here. I'm new to Laravel and php. I'm getting an error when I try to submit this form with a foreach loop. Each interest should loop in a new insert into my table. Can you help guide me through this stackoverflow, I've read some other solutions but dont quite understand how to apply them to my problem? Here is everything I have:

ERROR:

ErrorException in InterestController.php line 45:
Trying to get property of non-object

$interests = $inputs->interests;------->line 45

InterestController:

public function store(){

    //Get all the post values
    $inputs = Request::all();
    //From the post values get the array of interest ids that you are sending
    $interests = $inputs->interests;
    //For each interest id, save a new entry in the my_interest table
    foreach ($interests as $interest) {
        $interested_in = new MyInterests;
        $interested_in->user_id = Auth::id();
        $interested_in->interest_id = $interest;
        $interested_in->save();
            //dd($interests);
        }

    }

HTML:

{!! Form::open(array('id'=> 'form1')) !!}

                             @foreach($interests as $interest)

                                              <input type="checkbox" name = "interests[]" value="{{$interest->id}}">{{$interest->name}}

                            @endforeach

                                {!! Form:: submit('Sumbit', ['class' => 'btn btn-primary form-control']) !!}
                                {!! Form::close() !!}

Body:
First check if interests is Set

if(isset($interests)){
    foreach ($interests as $interest) {
        $interested_in = new MyInterests;
        $interested_in->user_id = Auth::id();
        $interested_in->interest_id = $interest;
        $interested_in->save();
        //dd($interests);
    }
}


问:
How to make json to json object in c#?
I have a json wants to add square brackets on it (means wants to convert it to json object array) here is my json in response,

```<code>    {
  "exampleJson": {
    "test": [
      {
        "xf": "G",
        "sas": "24",
        "ras": 5,
        "asd": 4000,
        "rer": 200,
        "asda": 0
      },
    ],
  }
}
</code>```

Now i want this json to as below (Just square brackets before and to the end of the json)

```<code>    [{
  "exampleJson": {
    "test": [
      {
        "xf": "G",
        "sas": "24",
        "ras": 5,
        "asd": 4000,
        "rer": 200,
        "asda": 0
      },
    ],
  }
}]
</code>```

Apart from concatenation is there any way to achieve this ? And this is a JObject which i have created.

答:
The surrounding [] indicates an array is being returned rather than an object, so you need to make your outer container be a JArray:

```<code>var returnedArray = new JArray(jObject);
</code>```

Title: How to make json to json object in c#?

Body:
I have a json wants to add square brackets on it (means wants to convert it to json object array) here is my json in response,

    {
  "exampleJson": {
    "test": [
      {
        "xf": "G",
        "sas": "24",
        "ras": 5,
        "asd": 4000,
        "rer": 200,
        "asda": 0
      },
    ],
  }
}

Now i want this json to as below (Just square brackets before and to the end of the json)

    [{
  "exampleJson": {
    "test": [
      {
        "xf": "G",
        "sas": "24",
        "ras": 5,
        "asd": 4000,
        "rer": 200,
        "asda": 0
      },
    ],
  }
}]

Apart from concatenation is there any way to achieve this ? And this is a JObject which i have created.

Body:
The surrounding [] indicates an array is being returned rather than an object, so you need to make your outer container be a JArray:

var returnedArray = new JArray(jObject);


问:
Android: Are there any benefits to using @id over @+id performance wise?
I know that the + in @+id tells the compiler to add the id to the (R.id.???) resources. However i was wondering if there were performance benefits to be gained by not putting the + ?

Perhaps for example when dealing with complex list view layouts?

答:
By using @+id you are adding a reference to R, by using @id you will reuse an already existing reference in a generated R class. This can be done, for instance, to inform your activity where to find a specific widget in a layout, as it is the case when using a custom layout with ListActivity. You will then assign your ListView an already existing id of @id/android:list which is a predefined. Same goes with TabHost and TabWidget.

For the rest, no performance difference, I think...


问:
Rails sum values in an array of hashes
Following is an array of hashes:

```<code>array = [
  {loading: 10, avg: 15, total: 25 },
  {loading: 20, avg: 20, total: 40 },
  {loading: 30, avg: 25, total: 55 }
]
</code>```

I need to sum the values of each hash and the result should be a hash of same keys:

```<code>{loading: 60, avg: 60, total: 120}
</code>```

One way is to sum the values individually for each key and then merge in a hash like this:

```<code>loading = array.map { |h| h[:loading] }.sum
avg = array.map { |h| h[:avg] }.sum
total = array.map { |h| h[:total] }.sum

{loading: loading, avg: avg, total: total}
</code>```

Is there a better way to do it? because the keys may increase in the future.

答:
You could use each_with_object with a Hash and a default value:

```<code>array = [
  {loading: 10, avg: 15, total: 25 },
  {loading: 20, avg: 20, total: 40 },
  {loading: 30, avg: 25, total: 55 }
]

sum = Hash.new(0)

array.each_with_object(sum) do |hash, sum|
  hash.each { |key, value| sum[key] += value }
end
 # => {:loading=>60, :avg=>60, :total=>120}
</code>```

It will work with any number of keys, and won't complain if a key isn't present in all the hashes.

BTW, you can replace

```<code>array.map { |h| h[:loading] }.sum
</code>```

with

```<code>array.sum { |h| h[:loading] }
</code>```

Title: Rails sum values in an array of hashes

Body:
Following is an array of hashes:

array = [
  {loading: 10, avg: 15, total: 25 },
  {loading: 20, avg: 20, total: 40 },
  {loading: 30, avg: 25, total: 55 }
]

I need to sum the values of each hash and the result should be a hash of same keys:

{loading: 60, avg: 60, total: 120}

One way is to sum the values individually for each key and then merge in a hash like this:

loading = array.map { |h| h[:loading] }.sum
avg = array.map { |h| h[:avg] }.sum
total = array.map { |h| h[:total] }.sum

{loading: loading, avg: avg, total: total}

Is there a better way to do it? because the keys may increase in the future.

Body:
You could use each_with_object with a Hash and a default value:

array = [
  {loading: 10, avg: 15, total: 25 },
  {loading: 20, avg: 20, total: 40 },
  {loading: 30, avg: 25, total: 55 }
]

sum = Hash.new(0)

array.each_with_object(sum) do |hash, sum|
  hash.each { |key, value| sum[key] += value }
end
 # => {:loading=>60, :avg=>60, :total=>120}

It will work with any number of keys, and won't complain if a key isn't present in all the hashes.

BTW, you can replace

array.map { |h| h[:loading] }.sum

with

array.sum { |h| h[:loading] }


问:
Facebook login from v2.3 to v2.8 user ID changed
I updated my website's facebook login version from v2.3 to v2.8. With the v2.3 I had this id for my facebook profile (https://www.facebook.com/870521502969350) and with the v2.8 I have different id (https://www.facebook.com/1382401371781358). Both ID brings to my account. I used for testing the v2.8 with fb dev tool: https://developers.facebook.com/tools/explorer and here i see my old ID (870521502969350). How is it possible? how can i get back my old ID? (Users who login on my site again gets new profil because of the new ID thing)</p>

答:
This error because of you used the new facebook app_id.
Let's comeback the old id was used on V2.3</p>


问:
How to add server rendering in Angular Universal project
Help me please to understand how to use server rendering in Angular Universal.

What I've done. I visited Angular Universal official site. Setup Node.js. Downloaded recommended project Angular 2 Webpack Starter.
I'm working on Mac so use "> sudo npm install" to install node_modules.
Add server.js as recommended. Run "> node server.js" - however it doesn't work.

If I run "> npm start" the server starts on localhost:3000 - but it seems there are no server rendering. If I look at HTML-page there are only Angular's index.html.

What should I do to add the server rendering capabilities in the project?

Thanks a lot.

答:
Meanwhile, you can have a look on this example app (Angular 4.0.0, Universal support, Webpack, and a little more) https://github.com/ng-seed/universal

Will definitely give you more or less an idea about how to get it running.


问:
Running Octave-cli on Iterm/Zsh/Omgzsh in Mac OSX
It feels impossible to get it to run on any custom terminal. I know that octave-cli.app is there but it always opens in the standard terminal. Any ways to execute octave scripts like a compiler (or) run it interactively like an interpreter from Iterm?

Using Mac OSX 10.9+

Edit:
I know how to export path variables. But having searched the web can't find a way to do it. Is it even possible? I even tried it using homebrew to no avail.

答:
You can see the content of octave-cli.app, it's a script. Mine goes like this

```<code>open -a Terminal.app /usr/local/octave/3.8.0/bin/octave | logger 2>&1
</code>```

It specify the terminal application used to open octave. This is the reason of your problem, as I think.

The solution is linking octave-cli in system path, better locates at "/usr/local/bin". like

```<code>ln -s /usr/local/octave/3.8.0/bin/octave-cli /usr/local/bin/octave-cli
</code>```

Finally, octave can be accessed via any terminal(like iTerm) or shell(bash, zsh) by just type "octave-cli" command, which will be searched in system path and found to executed directly.

Body:
You can see the content of octave-cli.app, it's a script. Mine goes like this

open -a Terminal.app /usr/local/octave/3.8.0/bin/octave | logger 2>&1

It specify the terminal application used to open octave. This is the reason of your problem, as I think.

The solution is linking octave-cli in system path, better locates at "/usr/local/bin". like

ln -s /usr/local/octave/3.8.0/bin/octave-cli /usr/local/bin/octave-cli

Finally, octave can be accessed via any terminal(like iTerm) or shell(bash, zsh) by just type "octave-cli" command, which will be searched in system path and found to executed directly.


问:
create random arrays in javascript
I have a form that asks the user for maximum result in math drills, in order to build some drills:

```<code><input type="text" id="maxR" placeholder="type maximum result" />
<button id="activate" onclick="makeDrills()">MAKE</button>
<p id="drill"></p>
</code>```

And I want to translate all the drills options with their answers as arrays.

I need help with translating this sentence into java-script:

"While c > level add new array of theQ with the both the drill and it's result".

This is my attempts:

```<code><script>
  function theQ(quest, ans) {  // drills constructor
    this.question = quest;
    this.answer = ans;
  }

  var a, b, c ; // arguments
  var quests = [new theQ()]; // arrays holder
  var level = document.getElementById("maxR").value; // user input

  function makeDrills() { // button pushed
    var c = a+b; // pattern of each drill
    while (c > level) { // as long result smaller then user input
      var a = Math.floor(Math.random() * 10);  // choose random number
      var b = Math.floor(Math.random() * 10); // choose another random number
      quests.push("a+b", "c");  // add the drill to the arrays holder
    }
    document.getElementById("drill").innerHTML += quests; // print drills
  }
</script>
</code>```

I read similar questions and try to use their techniques but didn't succeed.

edited:
This code is for educational purpose:

a,b,c are arguments on a+b=c equation. I try to make math drills generator that the kid enter maximum result and push the button and then all possible drills options will appear. I need to put all the options as arrays because I want to use the options as sort of a test.

So for now I just want to understand how to create those arrays.

答:
Your code is kinda messy. didn't fully understand the purpose of the task, but first of all organize your code better. should look something like that:</p>

```<code>function makeDrills() { // button pushed
  var quests = []; // arrays holder
  var level = document.getElementById("maxR").value; // user input
  var a = Math.floor(Math.random() * 10);  // choose random number
  var b = Math.floor(Math.random() * 10);
  var c = a+b; // pattern of each drill

  while (c < level) { // as long result smaller then user input
    quests.push([a+"+"+b, c]);  // add the drill to the arrays holder
    a = Math.floor(Math.random() * 10);  // choose random number
    b = Math.floor(Math.random() * 10); // choose another random number
    c = a + b
  }
  document.getElementById("drill").innerHTML = quests; // print drills
}
</code>```

Title: create random arrays in javascript

Body:
I have a form that asks the user for maximum result in math drills, in order to build some drills:

<input type="text" id="maxR" placeholder="type maximum result" />
<button id="activate" onclick="makeDrills()">MAKE</button>

And I want to translate all the drills options with their answers as arrays.

I need help with translating this sentence into java-script:

"While c > level add new array of theQ with the both the drill and it's result".

This is my attempts:

I read similar questions and try to use their techniques but didn't succeed.

edited:
This code is for educational purpose:

a,b,c are arguments on a+b=c equation. I try to make math drills generator that the kid enter maximum result and push the button and then all possible drills options will appear. I need to put all the options as arrays because I want to use the options as sort of a test.

So for now I just want to understand how to create those arrays.

Body:
Your code is kinda messy. didn't fully understand the purpose of the task, but first of all organize your code better. should look something like that:

function makeDrills() { // button pushed
  var quests = []; // arrays holder
  var level = document.getElementById("maxR").value; // user input
  var a = Math.floor(Math.random() * 10);  // choose random number
  var b = Math.floor(Math.random() * 10);
  var c = a+b; // pattern of each drill

  while (c < level) { // as long result smaller then user input
    quests.push([a+"+"+b, c]);  // add the drill to the arrays holder
    a = Math.floor(Math.random() * 10);  // choose random number
    b = Math.floor(Math.random() * 10); // choose another random number
    c = a + b
  }
  document.getElementById("drill").innerHTML = quests; // print drills
}


问:
socket.io emit in loop until client responds?
I would like to emit a message to the client every X seconds until the client clicks a button and acknowledges receipt.

Any ideas on how I might accomplish this? New to Node but I am hoping I can get this done with Node and Sockets.io.

Thanks in advance for any insight or help to get me in the right direction.

答:
I think the best way to accomplish this would be to create a new class that extends the "vanilla" Node.js event class. You will need to require it first like so:

```<code>const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}
</code>```

https://nodejs.org/api/events.html

Once you've got your class, what you will need to do is creating a child process, to do so, you can refer to the official documentation here:

https://nodejs.org/api/child_process.html

Inside this process you can create your loop and send a message through the socket. The goal of extending the events class is to be able to create an Inside event emission which you can listen to detect specific events (like socket closed, or anything you'd like to track)

I hope this answers your question.

Body:
I think the best way to accomplish this would be to create a new class that extends the "vanilla" Node.js event class. You will need to require it first like so:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

https://nodejs.org/api/events.html

Once you've got your class, what you will need to do is creating a child process, to do so, you can refer to the official documentation here:

https://nodejs.org/api/child_process.html

Inside this process you can create your loop and send a message through the socket. The goal of extending the events class is to be able to create an Inside event emission which you can listen to detect specific events (like socket closed, or anything you'd like to track)

I hope this answers your question.


问:
Better SQL Replace
I wanted to know if there is a better way of writing this Update.

```<code>update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl
</code>```

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

答:
On the Oracle you can use translate function. </p>

```<code>update Alumni_Export_New set phone = translate(phone, '- ()', '') from tbl
</code>```

Title: Better SQL Replace

Body:
I wanted to know if there is a better way of writing this Update.

update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

Body:
On the Oracle you can use translate function.

update Alumni_Export_New set phone = translate(phone, '- ()', '') from tbl


问:
oAuth Laravel API Route for Mobile
Our challenge is below for our latest project. With the advent of the Laravel Passport API we thought of giving it a try instead of using the old https://mattstauffer.co/blog/introducing-laravel-passport that I guess everybody was using prior to larval 5.3.

So our challenge is how to implement Laravel Passport for our mobile apps since we need to register users through an API instead of the VUE login element provided in latest laravel.

Any help will be mush appreciated.

答:
Laravel Passport API as if now doesn't support creating the user credentials other than using their VUE view component . So there is no way you can do that. So if that is very important for your business/project then I would advise sticking to Javascript for creating access/api tokens instead using standard Laravel Passport oAuth implementation.

The ideal diagnosis for such issue is to implement your own logic of handling creating tokens and oAuth user in respective tables in Laravel.

Title: oAuth Laravel API Route for Mobile


问:
Checkboxes don't stay checked after pagination
Whenever I check a checkbox on a listing page, save it then go to page eg 2 (using pagination) and check something there and save it the checkbox on my first page is unchecked. I thought about using AJAX to save checked checkboxes to grails session but don't know how to do that - I'm beginner with JS and using views. Could someone help me out?
Here is the part with listing all companies and checkboxes in my gsp:

```<code> <g:form name="company-list-form" action="listCompany">

    <div>
        <g:textField id="search-field" name="query" value="${params.query}"/>

        <span>
            <g:checkBox id="only-blockades-box" name="onlyBlockades" class="submit-on-change" value="${params.onlyBlockades}" title="Pokaż tylko blokady"/>
            <label for="only-blockades-box">Tylko blokady</label>
        </span>

        <g:actionSubmit value="${message(code: 'default.buttons.search', default: 'Szukaj')}" action="listCompany" class="button_orange"/>
        <g:link action="listCompany" class="button_gray"><g:message code="default.buttons.clean" default="Wyczyść"/></g:link>
    </div>

    <div class="padding-top">
        <table class="table_td company-list-table">
            <tbody>
            <tr class="gray2">
                <th class="first">Id</th>
                <th style="max-width: 100px;">Nazwa</th>
                <th>Id Kontrahenta</th>
                <th title="Dostęp do TPO">TPO</th>
                <th style="width: 20px;" title="Dostawa bezpośrednio do magazynu">Dostawa bezpośrednio</th>
                <th style="width: 20px;" title="Możliwość potwierdzania zamówień">Potwierdzanie zamówień</th>
                <th style="width: 20px;" title="Możliwość importowania awizacji z XLS">Import z Excel</th>
                <th style="width: 20px;" title="Możliwość awizowania zamówionych indeksów">Awizacja zam. indeksów</th>
                <th style="width: 20px;" title="Możliwość awizowania tygodniowego">Awizacja tyg.</th>
                <th style="width: 20px;" title="Dostęp jedynie do awizowania tygodniowego">Tylko awizacja tyg.</th>
                <th title="Limit AGD przypadający na każdą kratkę okna prywatnego">AGD</th>
                <th title="Limit rowerów przypadający na każdą kratkę okna prywatnego">Rowery</th>
                <th>Blokady</th>
                <th class="is-blocked-th">Zablokowany?</th>
            </tr>
            <g:each in="${companyInstanceList}" var="company" status="i">
                <tr class="${(i % 2) == 0 ? 'even' : 'odd'} table_td_gray2 ${i + 1 == companyInstanceList?.size() ? 'last' : ''}">
                    <td class="first" style="text-decoration: underline;">
                        <g:link action="editCompany" id="${company?.id}">${company?.id}</g:link>
                    </td>
                    <td>
                        ${company?.name}
                    </td>
                    <td>
                        ${company?.idKontrahenta}
                    </td>
                    <td>
                        <g:checkBox name="tpoAccess.${company?.id}" id="tpo-access-${company?.id}"
                                    checked="${company?.tpoAccess}"/>
                    </td>
                    <td>
                        <g:checkBox name="directDeliveryAvailable.${company?.id}"
                                    id="direct-delivery-available-${company?.id}"
                                    checked="${company?.directDeliveryAvailable}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToOrderConfirmation.${company?.id}"
                                    id="access-to-order-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderConfirmation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToXlsImport.${company?.id}"
                                    id="access-to-xls-import-${company?.id}"
                                    checked="${company?.accessToXlsImport}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToOrderedProductsAvisation.${company?.id}"
                                    id="access-to-ordered-products-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderedProductsAvisation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToLimitedAvisation.${company?.id}"
                                    id="access-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessToLimitedAvisation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessOnlyToLimitedAvisation.${company?.id}"
                                    id="access-only-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessOnlyToLimitedAvisation}"/>
                    </td>
                    <td>
                        <input type="text" name="agdPrivateWindowLimit.${company?.id}"
                               value="${company?.agdPrivateWindowLimit}"
                               class="shortText" id="agd-private-window-limit-${company?.id}"
                               onchange="validateLimits('agdPrivateWindowLimit.${company?.id}')">
                    </td>
                    <td>
                        <input type="text" name="bicyclePrivateWindowLimit.${company?.id}"
                               value="${company?.bicyclePrivateWindowLimit}"
                               class="shortText" id="bicycle-private-window-limit-${company?.id}"
                               onchange="validateLimits('bicyclePrivateWindowLimit.${company.id}')">
                    </td>
                    <td>
                        <g:link class="button_gray" controller="productGroup" action="list" params="[companyId: company?.id, query: params.query ?: '']">
                            Blokady
                        </g:link>
                    </td>
                    <td>
                        <g:if test="${company?.findBlockades()}">
                            <span title="Dostawca ma aktywne blokady grup towarowych." class="bold large">
                                ✓
                            </span>
                        </g:if>
                    </td>
                </tr>
            </g:each>
            </tbody>
        </table>
    </div>

    <div class="paginateButtons">
        <g:paginate controller="company" action="listCompany" total="${companyInstanceTotal}"
                    params="[query: params.query ?: '']"/>
    </div>

    <div style="float:right;">
        <g:link action="createCompany" class="button_orange">
            <g:message code="default.button.create.label" default="Utwórz"/>
        </g:link>
        <g:actionSubmit action="updateCompanies" name="companyListSubmit" class="button_orange" value="Zapisz"/>
    </div>

</g:form>
</code>```

Here is my javascript file associated with that view:

```<code>    function validateLimits(name) {
    document.getElementsByName(name)[0].value = document.getElementsByName(name)[0].value.replace(/[A-Za-z!@#$%^&*" "]/g, "");
    var quantity = document.getElementsByName(name)[0].value;
    var toBeAvised = 9999;
    if (quantity.indexOf(',') > -1 || quantity.indexOf('.') > -1 || /*quantity == "" ||*/ isNaN(quantity)) {
        alert("Limit musi być liczbą całkowitą");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) > toBeAvised) {
        alert("Podana liczba jest większa niż maksymalny limit równy " +toBeAvised + ".");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) < 0) {
        alert("Limit musi być liczbą dodatnią!");
        document.getElementsByName(name)[0].value = '';
    }
}
</code>```

And here is controller method (listCompany):

```<code> def listCompany(Integer max) {
        Person person = Person.read(springSecurityService.principal.id)
        Company comp = person?.company

        params.max = Math.min(max ?: 25, 100)
        params.offset = params.offset ?: 0
        params.readOnly = true

        String q = (params.query as String)?.toLowerCase() ?: ""

        def query = Company.where {
            id != comp?.id
            name =~ "%$q%" || idKontrahenta as String =~ "%$q%"
            if (params.onlyBlockades == "on") {
                id in ProductGroupBlockade.findAllByCompanyIsNotNullAndEnabled(true)*.companyId
            }
        }
        List<Company> companyInstanceList = query.list([max: params.int("max"), offset: params.int("offset"), sort: "name"])
        Integer count = query.count()
        if (flash.message) {
            params.errors = flash.message
        }
        [companyInstanceList: companyInstanceList, companyInstanceTotal: count, companySaved: params.companySaved, errors: params.errors]
    }
</code>```

How I could fix that so my checkboxes stay checked after saving? Right now they become unchecked whenever I go to next page and save some checkboxes there.

答:
I tend to use DataTables for situations like this but it depends on the amount of data you're dealing with to how you go about it.

If you have a relatively small data set, say 1000 rows or fewer you can use a plain DataTable, if you have more than this then you may want to use a server side processing DataTable.

Using a DataTable you would do away with all the Grails pagination, give your table an ID and just create the table in javascript like:

```<code>    <script type="text/javascript">
        $(document).ready( function() {
            $( '#companyListTable' ).DataTable();
        } );
    </script>
</code>```

All the pagination is handled in javascript and check boxes are preserved when navigating through the table pagination.

Body:
Whenever I check a checkbox on a listing page, save it then go to page eg 2 (using pagination) and check something there and save it the checkbox on my first page is unchecked. I thought about using AJAX to save checked checkboxes to grails session but don't know how to do that - I'm beginner with JS and using views. Could someone help me out?
Here is the part with listing all companies and checkboxes in my gsp:

 <g:form name="company-list-form" action="listCompany">

        <g:textField id="search-field" name="query" value="${params.query}"/>

            <g:checkBox id="only-blockades-box" name="onlyBlockades" class="submit-on-change" value="${params.onlyBlockades}" title="Pokaż tylko blokady"/>
            Tylko blokady

        <g:actionSubmit value="${message(code: 'default.buttons.search', default: 'Szukaj')}" action="listCompany" class="button_orange"/>
        <g:link action="listCompany" class="button_gray"><g:message code="default.buttons.clean" default="Wyczyść"/></g:link>

                Id
                Nazwa
                Id Kontrahenta
                TPO
                Dostawa bezpośrednio
                Potwierdzanie zamówień
                Import z Excel
                Awizacja zam. indeksów
                Awizacja tyg.
                Tylko awizacja tyg.
                AGD
                Rowery
                Blokady
                Zablokowany?

            <g:each in="${companyInstanceList}" var="company" status="i">

                        <g:link action="editCompany" id="${company?.id}">${company?.id}</g:link>

                        ${company?.name}

                        ${company?.idKontrahenta}

                        <g:checkBox name="tpoAccess.${company?.id}" id="tpo-access-${company?.id}"
                                    checked="${company?.tpoAccess}"/>

                        <g:checkBox name="directDeliveryAvailable.${company?.id}"
                                    id="direct-delivery-available-${company?.id}"
                                    checked="${company?.directDeliveryAvailable}"/>

                        <g:checkBox name="accessToOrderConfirmation.${company?.id}"
                                    id="access-to-order-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderConfirmation}"/>

                        <g:checkBox name="accessToXlsImport.${company?.id}"
                                    id="access-to-xls-import-${company?.id}"
                                    checked="${company?.accessToXlsImport}"/>

                        <g:checkBox name="accessToOrderedProductsAvisation.${company?.id}"
                                    id="access-to-ordered-products-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderedProductsAvisation}"/>

                        <g:checkBox name="accessToLimitedAvisation.${company?.id}"
                                    id="access-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessToLimitedAvisation}"/>

                        <g:checkBox name="accessOnlyToLimitedAvisation.${company?.id}"
                                    id="access-only-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessOnlyToLimitedAvisation}"/>

                        <input type="text" name="agdPrivateWindowLimit.${company?.id}"
                               value="${company?.agdPrivateWindowLimit}"
                               class="shortText" id="agd-private-window-limit-${company?.id}"
                               onchange="validateLimits('agdPrivateWindowLimit.${company?.id}')">

                        <input type="text" name="bicyclePrivateWindowLimit.${company?.id}"
                               value="${company?.bicyclePrivateWindowLimit}"
                               class="shortText" id="bicycle-private-window-limit-${company?.id}"
                               onchange="validateLimits('bicyclePrivateWindowLimit.${company.id}')">

                        <g:link class="button_gray" controller="productGroup" action="list" params="[companyId: company?.id, query: params.query ?: '']">
                            Blokady
                        </g:link>

                        <g:if test="${company?.findBlockades()}">

                                ✓

                        </g:if>

            </g:each>

        <g:paginate controller="company" action="listCompany" total="${companyInstanceTotal}"
                    params="[query: params.query ?: '']"/>

        <g:link action="createCompany" class="button_orange">
            <g:message code="default.button.create.label" default="Utwórz"/>
        </g:link>
        <g:actionSubmit action="updateCompanies" name="companyListSubmit" class="button_orange" value="Zapisz"/>

</g:form>

Here is my javascript file associated with that view:

    function validateLimits(name) {
    document.getElementsByName(name)[0].value = document.getElementsByName(name)[0].value.replace(/[A-Za-z!@#$%^&*" "]/g, "");
    var quantity = document.getElementsByName(name)[0].value;
    var toBeAvised = 9999;
    if (quantity.indexOf(',') > -1 || quantity.indexOf('.') > -1 || /*quantity == "" ||*/ isNaN(quantity)) {
        alert("Limit musi być liczbą całkowitą");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) > toBeAvised) {
        alert("Podana liczba jest większa niż maksymalny limit równy " +toBeAvised + ".");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) < 0) {
        alert("Limit musi być liczbą dodatnią!");
        document.getElementsByName(name)[0].value = '';
    }
}

And here is controller method (listCompany):

 def listCompany(Integer max) {
        Person person = Person.read(springSecurityService.principal.id)
        Company comp = person?.company

        params.max = Math.min(max ?: 25, 100)
        params.offset = params.offset ?: 0
        params.readOnly = true

        String q = (params.query as String)?.toLowerCase() ?: ""

        def query = Company.where {
            id != comp?.id
            name =~ "%$q%" || idKontrahenta as String =~ "%$q%"
            if (params.onlyBlockades == "on") {
                id in ProductGroupBlockade.findAllByCompanyIsNotNullAndEnabled(true)*.companyId
            }
        }
        List<Company> companyInstanceList = query.list([max: params.int("max"), offset: params.int("offset"), sort: "name"])
        Integer count = query.count()
        if (flash.message) {
            params.errors = flash.message
        }
        [companyInstanceList: companyInstanceList, companyInstanceTotal: count, companySaved: params.companySaved, errors: params.errors]
    }

How I could fix that so my checkboxes stay checked after saving? Right now they become unchecked whenever I go to next page and save some checkboxes there.

Body:
I tend to use DataTables for situations like this but it depends on the amount of data you're dealing with to how you go about it.

If you have a relatively small data set, say 1000 rows or fewer you can use a plain DataTable, if you have more than this then you may want to use a server side processing DataTable.

Using a DataTable you would do away with all the Grails pagination, give your table an ID and just create the table in javascript like:

    <script type="text/javascript">
        $(document).ready( function() {
            $( '#companyListTable' ).DataTable();
        } );
    </script>

All the pagination is handled in javascript and check boxes are preserved when navigating through the table pagination.


问:
Batch file value in variable
I tried scripting.

```<code>SET variable=command
</code>```

I expected in variable return string of command. If I build condition like that

```<code>IF %variable%==expected string doSomething
</code>```

I'm not sure what I saw. It was like %variable% contained command and command was executed, but if I typed in command line %variable% I saw expected string.

I would glad for explanation.

答:
```<code>IF "%variable%"=="expected string" doSomething
</code>```

The quotes make the value enclosed appear as a single token.

Title: Batch file value in variable

Body:
I tried scripting.

SET variable=command

I expected in variable return string of command. If I build condition like that

IF %variable%==expected string doSomething

I'm not sure what I saw. It was like %variable% contained command and command was executed, but if I typed in command line %variable% I saw expected string.

I would glad for explanation.

Body:
IF "%variable%"=="expected string" doSomething

The quotes make the value enclosed appear as a single token.


问:
Firebase authenticate as admin
Is there a way I can authenticate with Firebase as an administrator of a firebase for full read/write access to it (already has security rules protecting parts of it), or will I have to write a security rule that somehow allows me access to the full firebase, for example by providing a certain password/key.

Is there a standard or suggested way of doing this?

答:
See this for the 'latest' documentation.

authWithCustomToken is now signInWithCustomToken (firebase version 3.x)

Example from the documentation:

```<code>firebase.auth().signInWithCustomToken(token).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    if (errorCode === 'auth/invalid-custom-token') {
        alert('The token you provided is not valid.');
    } else {
        console.error(error);
    }
});
</code>```

Title: Firebase authenticate as admin

Body:
See this for the 'latest' documentation.

authWithCustomToken is now signInWithCustomToken (firebase version 3.x)

Example from the documentation:

firebase.auth().signInWithCustomToken(token).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    if (errorCode === 'auth/invalid-custom-token') {
        alert('The token you provided is not valid.');
    } else {
        console.error(error);
    }
});


问:
How to use svg images on button in MD (md-icon)
I have tried this form and it does not work:

```<code><button md-icon-button color="primary">
  <md-icon md-svg-src="./assets/img/sprites.svg">menu</md-icon>
</button>
</code>```

and this:

```<code><md-icon svgSrc="./assets/img/sprites.svg">menu</md-icon>
</code>```

How can i put svg images on the buttons.

Update:

I'm looking at this,

```<code><button md-icon-button color="primary">
<img src="./assets/img/sprites.svg" style="max-width:25%"/>
</button>
</code>```

but I do not know if it will be the right way.

答:
Somewhere in your code inject the MdIconRegistry:

```<code>import { MdIconRegistry } from '@angular/material';
import { DomSanitizer } from '@angular/platform-browser';

constructor(
    private mdIconRegistry: MdIconRegistry,
    private sanitizer: DomSanitizer) {
...
</code>```

later on register your svgs (ngOnInit() is a good place):

```<code>ngOnInit() {
    this.mdIconRegistry.addSvgIconInNamespace('img', 'sprites',
        this.sanitizer.bypassSecurityTrustResourceUrl('/assets/img/sprites.svg'));
}
</code>```

Then in your component you can use your svg:

```<code><md-icon svgIcon="img:sprites" color="primary"></md-icon>
</code>```

Body:
I have tried this form and it does not work:

<button md-icon-button color="primary">
  <md-icon md-svg-src="./assets/img/sprites.svg">menu</md-icon>
</button>

and this:

<md-icon svgSrc="./assets/img/sprites.svg">menu</md-icon>

How can i put svg images on the buttons.

Update:

I'm looking at this,

<button md-icon-button color="primary">

</button>

but I do not know if it will be the right way.

Body:
Somewhere in your code inject the MdIconRegistry:

import { MdIconRegistry } from '@angular/material';
import { DomSanitizer } from '@angular/platform-browser';

constructor(
    private mdIconRegistry: MdIconRegistry,
    private sanitizer: DomSanitizer) {
...

later on register your svgs (ngOnInit() is a good place):

ngOnInit() {
    this.mdIconRegistry.addSvgIconInNamespace('img', 'sprites',
        this.sanitizer.bypassSecurityTrustResourceUrl('/assets/img/sprites.svg'));
}

Then in your component you can use your svg:

<md-icon svgIcon="img:sprites" color="primary"></md-icon>


问:
Can't figure out how to make a python coin toss program loop back to a certain point once the whole process of the toss has been completed
I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.

Here is my code:

```<code>import random
def main():
    name = eval(input("Hello user, please enter your name: "))
    print("Hello", name ,"This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N):")
    if yn == Y:

    elif yn == N:
        print("Ok have a nice day!")

    heads = 0
    tails = 0
    count = tails + heads
    count = int(input("Enter the amount of times you would like the coin to     flip: "))
    if count <= 0:
        print("Silly rabbit, that won't work")
    while tails + heads < count:
        coin = random.randint(1, 2)
        if coin ==1:

            heads = heads + 1
        elif coin == 2:

            tails = tails + 1
    print("you flipped", count , "time(s)")
    print("you flipped heads", heads , "time(s)")
    print("you flipped tails", tails , "time(s)")
main()
</code>```

Here is the sample output that I'm looking for:

Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!
```

答: I think you should say on line 6 if yn == 'Y' and not if yn == Y. You treat Y as a variable while it is actually a string from the input.

Body:
I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.

Here is my code:

import random
def main():
    name = eval(input("Hello user, please enter your name: "))
    print("Hello", name ,"This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N):")
    if yn == Y:

    elif yn == N:
        print("Ok have a nice day!")

    heads = 0
    tails = 0
    count = tails + heads
    count = int(input("Enter the amount of times you would like the coin to     flip: "))
    if count <= 0:
        print("Silly rabbit, that won't work")
    while tails + heads < count:
        coin = random.randint(1, 2)
        if coin ==1:

            heads = heads + 1
        elif coin == 2:

            tails = tails + 1
    print("you flipped", count , "time(s)")
    print("you flipped heads", heads , "time(s)")
    print("you flipped tails", tails , "time(s)")
main()

Here is the sample output that I'm looking for:

Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!


问:
How to use global scss files in angular-cli project
I am new to Angular 4 and to the Angular-CLI.
I cannot find any solution how to use root scss/css files for the whole application.
Thereby, my question, how to use global scss files in the project?</p>

答:
Create a styles folder in the src folder, then you can import everything there into styles.scss which is also in the src folder. This is how mine looks:

```<code>// Vendors
@import './styles/vendors/_exports';

// Utils
@import './styles/utils/_exports';

// Globals
@import './styles/globals/_exports';

// Partials
@import './styles/partials/_exports';

// Components
@import './styles/components/_exports';
</code>```

Every _exports file is importing all the files in the particular folder to make it easier to import it into the styles.scss file.

I hope this helps.

EDIT:

As pointed out in the comments, make sure that styles.scss is added to styles in the angular-cli.jsonfile or it will not work.

Body:
Create a styles folder in the src folder, then you can import everything there into styles.scss which is also in the src folder. This is how mine looks:

// Vendors
@import './styles/vendors/_exports';

// Utils
@import './styles/utils/_exports';

// Globals
@import './styles/globals/_exports';

// Partials
@import './styles/partials/_exports';

// Components
@import './styles/components/_exports';

Every _exports file is importing all the files in the particular folder to make it easier to import it into the styles.scss file.

I hope this helps.

EDIT:

As pointed out in the comments, make sure that styles.scss is added to styles in the angular-cli.jsonfile or it will not work.


问:
help with a two table linq query
I want to display categories and subcategories like so:

Category 1

  Subcategory 1

  Subcategory 2

  Subcategory 3

Category 2

  Subcategory 5

  Subcategory 6

  Subcategory 7

In other words, foreach category, display the subcategories that belong to each one underneath.

My two tables are like so:

Category-

CategoryID

Name

SubCategory-

SubCategoryID

SubCategoryName

CategoryID

I have a foreign key from category to subcategory a one to many.

Here is where I got in the code, which display all sub categories foreach category.

```<code>public void displayLinqCategory()
{
    MyDataContext dbm = new MyDataContext();

    var q = from category in dbm.Categories
            join subCat in dbm.SubCategories
            on category.CategoryID equals subCat.CategoryID
            select new { category.Name, subCat.SubCategoryName };

    resultSpan.InnerHtml += "<table>";
    foreach (var c in q)
    {
        resultSpan.InnerHtml += "<tr><td>" + c.Name + "</td></tr>";
        foreach (var s in q)
        {
            resultSpan.InnerHtml += "<tr><td>   " + s.SubCategoryName + "</td></td>";
        }

    }
    resultSpan.InnerHtml += "</table>";
}
</code>```

答:
If you have navigational properties in your model:

```<code>MyDataContext dbm = new MyDataContext();

var groups = dbm.SubCategories
          .Select(x=> new { CatName = x.Category.Name, x.SubCategoryName });
          .GroupBy(x=>x.CatName);

resultSpan.InnerHtml += "<table>";
foreach (var group in groups)
{
    resultSpan.InnerHtml += "<tr><td>" + group.Key + "</td></tr>";
    foreach (var s in group)
    {
        resultSpan.InnerHtml += "<tr><td>   " + s.SubCategoryName + "</td></td>";
    }

}
resultSpan.InnerHtml += "</table>";
</code>```

if you didn't add references to your model you still can achieve what you need using GroupJoin

```<code>var groups = dbm.Categories
   .GroupJoin(
        dbm.SubCategories,
        x => x.CategoryID,
        x => x.CategoryID,
        (x, y) => new {Category = x.CategoryName, SubCategories = y.Select(s=>s.SubCategoryName)}
);
</code>```

Title: help with a two table linq query

Body:
I want to display categories and subcategories like so:

Category 1

  Subcategory 1

  Subcategory 2

  Subcategory 3

Category 2

  Subcategory 5

  Subcategory 6

  Subcategory 7

In other words, foreach category, display the subcategories that belong to each one underneath.

My two tables are like so:

Category-

CategoryID

Name

SubCategory-

SubCategoryID

SubCategoryName

CategoryID

I have a foreign key from category to subcategory a one to many.

Here is where I got in the code, which display all sub categories foreach category.

public void displayLinqCategory()
{
    MyDataContext dbm = new MyDataContext();

    var q = from category in dbm.Categories
            join subCat in dbm.SubCategories
            on category.CategoryID equals subCat.CategoryID
            select new { category.Name, subCat.SubCategoryName };

    resultSpan.InnerHtml += "
";
    foreach (var c in q)
    {
        resultSpan.InnerHtml += "
" + c.Name + "
";
        foreach (var s in q)
        {
            resultSpan.InnerHtml += "
   " + s.SubCategoryName + "		";
        }

    }
    resultSpan.InnerHtml += "
";
}

Body:
If you have navigational properties in your model:

MyDataContext dbm = new MyDataContext();

var groups = dbm.SubCategories
          .Select(x=> new { CatName = x.Category.Name, x.SubCategoryName });
          .GroupBy(x=>x.CatName);

resultSpan.InnerHtml += "<table>";
foreach (var group in groups)
{
    resultSpan.InnerHtml += "<tr><td>" + group.Key + "</td></tr>";
    foreach (var s in group)
    {
        resultSpan.InnerHtml += "<tr><td>&nbsp;&nbsp;&nbsp;" + s.SubCategoryName + "</td></td>";
    }

}
resultSpan.InnerHtml += "</table>";

if you didn't add references to your model you still can achieve what you need using GroupJoin

var groups = dbm.Categories
   .GroupJoin(
        dbm.SubCategories,
        x => x.CategoryID,
        x => x.CategoryID,
        (x, y) => new {Category = x.CategoryName, SubCategories = y.Select(s=>s.SubCategoryName)}
);