问:
c# code to set an attribute of a class of a group of controls
i have researched but none of the direct method was found to do this task.what i am trying to do is,i have some asp:textboxes which have same class

```<code><asp:TextBox ID="txtItemAmnt5"  class="totaltextbox" runat="server" Width="106px"></asp:TextBox>
</code>```

and with the help of c# code i want to hide all the textboxes which belongs to the same class.one of the indirect approach is this, which is irritating. does any one have smarter code

```<code> for (int j =1 ; j <=9 ; j++)
        {

            TextBox objtxt = this.Master.FindControl("ContentPlaceHolder1").FindControl("txt"+j.ToString()) as TextBox;

            objtxt.Visible= true;
            }
</code>```

答:
I recomend to do it in client side using Javascript, you get better performance and can do it using 1 line of code using jquery for instance:

```<code>$(".myClass").hide();
</code>```

https://api.jquery.com/class-selector/

Body:
i have researched but none of the direct method was found to do this task.what i am trying to do is,i have some asp:textboxes which have same class

<asp:TextBox ID="txtItemAmnt5"  class="totaltextbox" runat="server" Width="106px"></asp:TextBox>

and with the help of c# code i want to hide all the textboxes which belongs to the same class.one of the indirect approach is this, which is irritating. does any one have smarter code

 for (int j =1 ; j <=9 ; j++)
        {

            TextBox objtxt = this.Master.FindControl("ContentPlaceHolder1").FindControl("txt"+j.ToString()) as TextBox;

            objtxt.Visible= true;
            }

Body:
I recomend to do it in client side using Javascript, you get better performance and can do it using 1 line of code using jquery for instance:

$(".myClass").hide();

https://api.jquery.com/class-selector/


来源: stackexchange

问:
How can force update an ios app
We had developed an ios app and uploaded it to ios server after sometime time some we had done some changes,So new build with new version had uploaded but the users that are having old version is not reflecting with new changes and we had not set any flag or something regard for force update in previous build so can any one tell us how to prevent old version app users to use old version.Please tell how to do that.  </p>

答:
Step 1: Your Server provide a WebApi to indicate the latest version, and the updating is mandatory or not.

Step 2: Your iOS App call that WebApi to get the latest version information. Show a Model View like UIAlertView to inform user that there is a new version, to update it or not? The view provide 2 buttons "YES" and "Later".

Jump to the AppStore if user chose "YES".

Close the App by "exit(0)" if user chose "Later" and updating is mandatory. Close the confirm view and do nothing more if updating is not mandatory.

ContentLicense: CC BY-SA 3.0

Title: How can force update an ios app


问:
Display specific content for target audiences depending on Member Group Extending Umbraco
Is it possible to display specific content for target audiences depending on Member Group?

Current "Public Access" mechanism allows us to provide role based restrictions for the selected page. In this case we would be able to create number of different pages depending on the number of Member Groups and assign restrictions.

I was wondering if it is possible to show different page content depending on the Member Group (on the same URL) or can I do it with different Modules? Does Umbraco already have the logic if "Member Group A" is assinged to "Module A" he shows "Module A"? Or "Member Group B" is assigned to "Module B" he shows "Module B"?

Thanks In advance!

答:
I believe this will have to be done through custom logic... You can however use Umbraco's services (see the link below):

Umbraco - MemberGroup Service

You can use this class to determine the group the current Member belongs to. Once you have determined this, you just simply need to alternate between the different bits of content you wish to show to each different group.

Example node:
FaqNode

RegisteredUserNotes

NonRegisteredUserNotes

OtherGroupNotes etc.

Hopefully this makes sense...

Regards

Craig


问:
What does Mirah offer over JRuby,Groovy and Scala?
What does Mirah language offer over JRuby,Groovy and Scala?</p>

答:
I use Mirah everyday on Google AppEngine.

Here are my reasons to use Mirah:

no runtime library

very nice syntax

as fast as Java

Having Java under the hood is very helpful too:

solid typesystem

well documented

known solutions for common problems

I did some Groovy, lot of JRuby and none of Scala.
If you know these, try Mirah.
If not, I'd go with JRuby.

ContentLicense: CC BY-SA 2.5


问:
Setting remaining time variable as time from now to midnight?
Hi I'm new to JavaScript and can't seem to understand how to change this code.

I'd like to change this so the remaining time is from when the users loads the page until midnight. For example if it's 7pm the remaining time will be 5hours 0minutes 0seconds, or if it was 7:45pm remaining time would be 4hours 15minutes 0seconds.

```<code>function startTimer(start, duration, display) {
    var diff, minutes, seconds;
    function timer(){
        diff = duration - (((Date.now() - start) / 1000) | 0);
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (diff <= 0) {
            clearInterval(inti);
            document.getElementById("countdownhere").innerHTML
</code>```

EDIT: oops here's the full code, thanks to Jonas W for pointing this out!

```<code>var d = new Date();

(function($){$.fn.progressbar=function(){var a="<p>Countdown Timer!</p>"+"<div class='progressbar'><div style='width:100%'></div></div>";this.addClass('items-count');this.html(a+this.html());updateMeter(this);var b=this;

{$("#progress_bar").progressbar();var tag="ctdn-12-12".match(/\d+/g);var hour=14;var theDaysBox=$("#numdays");var theHoursBox=$("#numhours");var theMinsBox=$("#nummins");var theSecsBox=$("#numsecs");var d=new Date();var n=d.getDay();var date=1;var gg=0;var hh=0;var ii=0;var nsec=0-d.getSeconds();if(nsec<0){nsec=60-d.getSeconds();gg=1}var nmin=0-d.getMinutes()-gg;if(nmin<0){nmin=60-d.getMinutes()-gg;hh=1}var nhrs=14-d.getHours()-hh;if(nhrs<0){nhrs=38-d.getHours()-hh;ii=1}var ndat=date-1;if(ndat<0){var mmon=d.getMonth();ndat=30+date-d.getDate()-ii}theSecsBox.html(nsec);theMinsBox.html(nmin);theHoursBox.html(nhrs);theDaysBox.html(ndat);var refreshId=setInterval(function(){var e=theSecsBox.text();var a=theMinsBox.text();var c=theHoursBox.text();var b=theDaysBox.text();if(e==0&&a==0&&c==0&&b==0){}else{if(e==0&&a==0&&c==0){theDaysBox.html(b-1);theHoursBox.html("23");theMinsBox.html("59");theSecsBox.html("59")}else{if(e==0&&a==0){theHoursBox.html(c-1);theMinsBox.html("59");theSecsBox.html("59")}else{if(e==0){theMinsBox.html(a-1);theSecsBox.html("59")}else{theSecsBox.html(e-1)}}}}},1000);});</script>

<div class="items-count" id="progress_bar"></div><div id="clock-ticker" class="clearfix"><div class="block"><span class="flip-top" id="numdays">0</span><br><span class="label">Days</span></div><div class="block"><span class="flip-top" id="numhours">1</span><br><span class="label">Hours</span></div><div class="block"><span class="flip-top" id="nummins">23</span><br><span class="label">Minutes</span></div><div class="block"><span class="flip-top" id="numsecs">36</span><br><span class="label">Seconds</span></div>
</code>```

答:
Maybe:

```<code>var midnight=new Date();
midnight.setHours(0);
midnight.setDate(midnight.getDate()+1);
var display=document.body;
startTimer(new Date(),midnight,display);
</code>```

SetHours sets the Date to todays midnight, then we get the next day...

Body:
Hi I'm new to JavaScript and can't seem to understand how to change this code.

I'd like to change this so the remaining time is from when the users loads the page until midnight. For example if it's 7pm the remaining time will be 5hours 0minutes 0seconds, or if it was 7:45pm remaining time would be 4hours 15minutes 0seconds.

function startTimer(start, duration, display) {
    var diff, minutes, seconds;
    function timer(){
        diff = duration - (((Date.now() - start) / 1000) | 0);
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (diff <= 0) {
            clearInterval(inti);
            document.getElementById("countdownhere").innerHTML

EDIT: oops here's the full code, thanks to Jonas W for pointing this out!

var d = new Date();

(function($){$.fn.progressbar=function(){var a="
Countdown Timer!
"+"

";this.addClass('items-count');this.html(a+this.html());updateMeter(this);var b=this;

{$("#progress_bar").progressbar();var tag="ctdn-12-12".match(/\d+/g);var hour=14;var theDaysBox=$("#numdays");var theHoursBox=$("#numhours");var theMinsBox=$("#nummins");var theSecsBox=$("#numsecs");var d=new Date();var n=d.getDay();var date=1;var gg=0;var hh=0;var ii=0;var nsec=0-d.getSeconds();if(nsec<0){nsec=60-d.getSeconds();gg=1}var nmin=0-d.getMinutes()-gg;if(nmin<0){nmin=60-d.getMinutes()-gg;hh=1}var nhrs=14-d.getHours()-hh;if(nhrs<0){nhrs=38-d.getHours()-hh;ii=1}var ndat=date-1;if(ndat<0){var mmon=d.getMonth();ndat=30+date-d.getDate()-ii}theSecsBox.html(nsec);theMinsBox.html(nmin);theHoursBox.html(nhrs);theDaysBox.html(ndat);var refreshId=setInterval(function(){var e=theSecsBox.text();var a=theMinsBox.text();var c=theHoursBox.text();var b=theDaysBox.text();if(e==0&&a==0&&c==0&&b==0){}else{if(e==0&&a==0&&c==0){theDaysBox.html(b-1);theHoursBox.html("23");theMinsBox.html("59");theSecsBox.html("59")}else{if(e==0&&a==0){theHoursBox.html(c-1);theMinsBox.html("59");theSecsBox.html("59")}else{if(e==0){theMinsBox.html(a-1);theSecsBox.html("59")}else{theSecsBox.html(e-1)}}}}},1000);});</script>

0
Days

1
Hours

23
Minutes

36
Seconds

Body:
Maybe:

var midnight=new Date();
midnight.setHours(0);
midnight.setDate(midnight.getDate()+1);
var display=document.body;
startTimer(new Date(),midnight,display);

SetHours sets the Date to todays midnight, then we get the next day...


问:
Xcode 7.2 no matching provisioning profiles found
Before upgrading Xcode to 7.2, I was using Xcode 7.1.1 to build and distribute apps. I have upgraded to Xcode 7.2 and none of my provisioning profiles (matched to that particular app's bundle ID) match my installed certificates that were working in Xcode 7.1.1.

I only get:

Your build settings specify a provisioning profile with the UUID “some_number”, however, no such provisioning profile was found.

I have tried regenerating a .certSigningRequest to generate a new Certificate and Profile and made sure the Team in the General tab of the target is correct. Whenever I select a Provision Profile, all of my Code Signing Identities appear in the Identities in Keychain, but none of them will pair correctly.

It seems setting the Provision Profile to Automatic and the Code Signing Identity to iOS Developer will resolve this error, but the advantage of managing my Provisioning Profiles is gone as I believe Xcode then manages these.

Any thoughts on why setting my Provisioning Profiles and Code Signing Identities to anything but Automatic and iOS Developer produces this error?

答:
For everyone who didn't solve it yet, my Issue was answered by this:

https://stackoverflow.com/a/41202884/3953197


问:
Pushing an object with unique_ptr into vector in C++
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

```<code>#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}
</code>```

I get compiler errors when adding the new state object to the vector:

```<code>Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
</code>```

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

```<code>int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}
</code>```

答:
State is not copyable, but only moveable; But for states.push_back(nstate);, nstate is an lvalue (as a named variable), which can't be moved from. Then a copy is tried to perform but it's not allowed.

To solve it you could use std::move (to turn it to an rvalue):

```<code>states.push_back(std::move(nstate));
</code>```

LIVE

Note that after the move operation, the data member of nstate (including the vector and its content) will be moved too.

Body:
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}

I get compiler errors when adding the new state object to the vector:

Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}

Body:
State is not copyable, but only moveable; But for states.push_back(nstate);, nstate is an lvalue (as a named variable), which can't be moved from. Then a copy is tried to perform but it's not allowed.

To solve it you could use std::move (to turn it to an rvalue):

states.push_back(std::move(nstate));

LIVE

Note that after the move operation, the data member of nstate (including the vector and its content) will be moved too.


问:
Elasticsearch multisearch returns wrong response but single query returns correct response
Running the following query on Elasticsearch using official python client returns the wrong response but running them separately gives out the correct response.

Following object is passed as search_doc to elasticsearch.msearch():

```<code>[
  {
    'type': 1,
    'index': 'xyz'
  },
  {
    'query': {
      'bool': {
        'must': [
          {
            'match_phrase': {
              'messageid': 'DEL_1CKCJAR'
            }
          },
          {
            'regexp': {
              'dsn': '2.[0-9].[0-9]'
            }
          }
        ]
      }
    }
  },
  {
    'type': 1,
    'index': 'xyz'
  },
  {
    'query': {
      'bool': {
        'must': [
          {
            'match_phrase': {
              'messageid': 'DEL_1CKCJAR'
            }
          },
          {
            'regexp': {
              'dsn': '5.[0-9].[0-9]'
            }
          }
        ]
      }
    }
  },
  {
    'type': 1,
    'index': 'xyz'
  },
  {
    'query': {
      'bool': {
        'must': [
          {
            'match_phrase': {
              'messageid': 'DEL_1CKCJAR'
            }
          },
          {
            'regexp': {
              'dsn': '4.[0-9].[0-9]'
            }
          }
        ]
      }
    }
  }
]
</code>```

and returns the following response:

```<code>[
  {
    'took': 42,
    'hits': {
      'hits': [

      ],
      'total': 0,
      'max_score': None
    },
    'status': 200,
    'timed_out': False,
    '_shards': {
      'failed': 0,
      'total': 5,
      'successful': 5
    }
  },
  {
    'took': 41,
    'hits': {
      'hits': [

      ],
      'total': 0,
      'max_score': None
    },
    'status': 200,
    'timed_out': False,
    '_shards': {
      'failed': 0,
      'total': 5,
      'successful': 5
    }
  },
  {
    'took': 41,
    'hits': {
      'hits': [

      ],
      'total': 0,
      'max_score': None
    },
    'status': 200,
    'timed_out': False,
    '_shards': {
      'failed': 0,
      'total': 5,
      'successful': 5
    }
  }
]
</code>```

However, run separately on index xyz, a query such as follows:

```<code>{
  'query': {
    'bool': {
      'must': [
        {
          'match_phrase': {
            'messageid': 'DEL_1CKCJAR'
          }
        },
        {
          'regexp': {
            'dsn': '4.[0-9].[0-9]'
          }
        }
      ]
    }
  }
}
</code>```

returns the following response:

```<code>{
  "took": 6,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 18,
    "max_score": 2.7300916,
    "hits": [
      {
        "_index": "xyz",
        "_type": "log",
        "_id": "3A91F141442",
        "_score": 2.7300916,
        "_source": {
          "pid": "13034",
          "type": "log",
          "logsource": "localhost",
          "qid": "3A91F141442",
          "@timestamp": "2017-06-05T16:44:16.177Z",
          "@version": "1",
          "host": "localhost.localdomain",
          "client": "unknown[XXX.XXX.XXX.XXX]",
          "messageid": "20170606062113.12268.36913.DEL_1CKCJAR@localhost.localdomain>",
          "nrcpt": "1",
          "queuestatus": "queue active",
          "size": "1297",
          "from": "asdfasdfasdf@gmail.com",
          "reason": "(connect to mx2.hotmail.com[XXX.XXX.XXX.XXX]:25: Connection timed out)",
          "relayhost": "none",
          "result": "deferred",
          "delay": "8707",
          "to": "abcdefg@outlook.com",
          "dsn": "4.4.1"
        }
      },
    ....
}
</code>```

, which is the desired response. So far, I cannot figure out why the individual request works but the multi_search request does not.

Note: The Data being searched is Elasticsearch log data.

Any help is appreciated. :)

答:
I'd say that your multi search query uses the wrong type:

```<code>{
    'type': 1,
    'index': 'xyz'
}
</code>```

The documents returned by your single search query have the type log. Either leave out the type entirely or use log and your queries should return the desired results.

Body:
Running the following query on Elasticsearch using official python client returns the wrong response but running them separately gives out the correct response.

Following object is passed as search_doc to elasticsearch.msearch():

[
  {
    'type': 1,
    'index': 'xyz'
  },
  {
    'query': {
      'bool': {
        'must': [
          {
            'match_phrase': {
              'messageid': 'DEL_1CKCJAR'
            }
          },
          {
            'regexp': {
              'dsn': '2.[0-9].[0-9]'
            }
          }
        ]
      }
    }
  },
  {
    'type': 1,
    'index': 'xyz'
  },
  {
    'query': {
      'bool': {
        'must': [
          {
            'match_phrase': {
              'messageid': 'DEL_1CKCJAR'
            }
          },
          {
            'regexp': {
              'dsn': '5.[0-9].[0-9]'
            }
          }
        ]
      }
    }
  },
  {
    'type': 1,
    'index': 'xyz'
  },
  {
    'query': {
      'bool': {
        'must': [
          {
            'match_phrase': {
              'messageid': 'DEL_1CKCJAR'
            }
          },
          {
            'regexp': {
              'dsn': '4.[0-9].[0-9]'
            }
          }
        ]
      }
    }
  }
]

and returns the following response:

[
  {
    'took': 42,
    'hits': {
      'hits': [

      ],
      'total': 0,
      'max_score': None
    },
    'status': 200,
    'timed_out': False,
    '_shards': {
      'failed': 0,
      'total': 5,
      'successful': 5
    }
  },
  {
    'took': 41,
    'hits': {
      'hits': [

      ],
      'total': 0,
      'max_score': None
    },
    'status': 200,
    'timed_out': False,
    '_shards': {
      'failed': 0,
      'total': 5,
      'successful': 5
    }
  },
  {
    'took': 41,
    'hits': {
      'hits': [

      ],
      'total': 0,
      'max_score': None
    },
    'status': 200,
    'timed_out': False,
    '_shards': {
      'failed': 0,
      'total': 5,
      'successful': 5
    }
  }
]

However, run separately on index xyz, a query such as follows:

{
  'query': {
    'bool': {
      'must': [
        {
          'match_phrase': {
            'messageid': 'DEL_1CKCJAR'
          }
        },
        {
          'regexp': {
            'dsn': '4.[0-9].[0-9]'
          }
        }
      ]
    }
  }
}

returns the following response:

{
  "took": 6,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 18,
    "max_score": 2.7300916,
    "hits": [
      {
        "_index": "xyz",
        "_type": "log",
        "_id": "3A91F141442",
        "_score": 2.7300916,
        "_source": {
          "pid": "13034",
          "type": "log",
          "logsource": "localhost",
          "qid": "3A91F141442",
          "@timestamp": "2017-06-05T16:44:16.177Z",
          "@version": "1",
          "host": "localhost.localdomain",
          "client": "unknown[XXX.XXX.XXX.XXX]",
          "messageid": "20170606062113.12268.36913.DEL_1CKCJAR@localhost.localdomain>",
          "nrcpt": "1",
          "queuestatus": "queue active",
          "size": "1297",
          "from": "asdfasdfasdf@gmail.com",
          "reason": "(connect to mx2.hotmail.com[XXX.XXX.XXX.XXX]:25: Connection timed out)",
          "relayhost": "none",
          "result": "deferred",
          "delay": "8707",
          "to": "abcdefg@outlook.com",
          "dsn": "4.4.1"
        }
      },
    ....
}

, which is the desired response. So far, I cannot figure out why the individual request works but the multi_search request does not.

Note: The Data being searched is Elasticsearch log data.

Any help is appreciated. :)

Body:
I'd say that your multi search query uses the wrong type:

{
    'type': 1,
    'index': 'xyz'
}

The documents returned by your single search query have the type log. Either leave out the type entirely or use log and your queries should return the desired results.


问:
How to handle shared data between the controller and the view in ASP.NET MVC?
We have a model (say, List<string>). The function that builds the list is non-deterministic and the output is needed to be referenced in both controller and the view during the lifetime of the request. Since it's per-request, it cannot be static or singleton.

It's a common structure and it can be referenced from any view or controller.

Since we can't access controller from the view (by principle, and we agree), we cannot keep it in the controller. We're currently keeping it in the ViewData dictionary and initialize it in the controller, or the view (if the controller didn't need it).

We think that using ViewData for this purpose may not be ideal since it's not created to be consumed by a controller in the first place. Is there a better way to share common per-request data between Controller and the View? If not we'll stick with ViewData.

There is HttpContext.Items dictionary but I'm not sure if it fits to this purpose.

答:
the output is needed to be referenced in both controller and the view during the lifetime of the request

The way MVC works, the Action code in the Controller is executed, and the resulting data is passed to the view engine that draws the page using the info you passed either with the call to View(data) or in the ViewData dictionary.

I don't know what you are trying to do, but it sounds like it's more a problem of a bad approach than a technical one (I might be wrong, though).

Could you explain why you need the controller while the View is rendered? If you need any logic associated with the List (to process it or do anything with it) I would just create a new class that extends List<T>, add the logic to that class instead of the controller, and pass an object of that class to the View, either using View() or ViewData[].


问:
Ruby on Rails: Why a select box does not show the current object value?
Here is the relevant code from views/products/edit.html.erb:

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
  <%= render(:partial => "form", :locals => {:f => f}) %>
  <%= submit_tag("Update Product") %>
<% end %>
</code>```

from views/products/_form.html.erb:

```<code><%= select_with_new_option(f, :shop, :name, :id) %>
</code>```

and from helpers/products_helper.rb:

```<code>def select_options_with_create_new(objects, text_field, value_field, options={})
  object = objects.to_s.singularize
  all_objects = object.capitalize.constantize.all
  all_objects = all_objects.sort_by(&options[:order_by]) if options.has_key?(:order_by)
  select_options = all_objects.map{ |obj| [obj.send(text_field), obj.send(value_field)] }
  select_options << [wrap_create_new_option("create new #{object}".titleize), "new_#{object}"]
  options_for_select(select_options)
end

def wrap_create_new_option(str)
  ">> #{str} <<"
end

# By default, sorts by 'text_field'.
def select_with_new_option(f, object, text_field, value_field)
  f.select(:"#{object}_id", select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field))
end
</code>```

I expect the select box to be @product.shop_id by default, but this is not true (the first option is always the default value).

What am I missing ?

答:
Alright, I got it. Just remove options_for_select(select_options) in the select_options_with_create_new method.

The options_for_select assembles the 2-d array select_options into a string of html options, which is accepted by the select form helper, however, without assigning the selected attribute. Just pass the 2-d array to the select method as the second argument, it would assign the selected automatically.

Body:
Here is the relevant code from views/products/edit.html.erb:

<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
  <%= render(:partial => "form", :locals => {:f => f}) %>
  <%= submit_tag("Update Product") %>
<% end %>

from views/products/_form.html.erb:

<%= select_with_new_option(f, :shop, :name, :id) %>

and from helpers/products_helper.rb:

def select_options_with_create_new(objects, text_field, value_field, options={})
  object = objects.to_s.singularize
  all_objects = object.capitalize.constantize.all
  all_objects = all_objects.sort_by(&options[:order_by]) if options.has_key?(:order_by)
  select_options = all_objects.map{ |obj| [obj.send(text_field), obj.send(value_field)] }
  select_options << [wrap_create_new_option("create new #{object}".titleize), "new_#{object}"]
  options_for_select(select_options)
end

def wrap_create_new_option(str)
  ">> #{str} <<"
end

# By default, sorts by 'text_field'.
def select_with_new_option(f, object, text_field, value_field)
  f.select(:"#{object}_id", select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field))
end

I expect the select box to be @product.shop_id by default, but this is not true (the first option is always the default value).

What am I missing ?


问:
angular-chart.js : issue with pointHoverBorderColor property for line chart
I'm using input color as an object but property "pointHoverBorderColor" isn't working using :

angular : 1.5.3,

chart.js : 2.6.0,

angular-chart.js : 1.1.1.

```<code>vm.colors = [ { backgroundColor: "rgba(159,204,0, 0.2)",
pointBackgroundColor: "rgba(159,204,0, 1)",
pointHoverBackgroundColor: "rgba(159,204,0, 0.8)",
borderColor: "rgba(159,204,0, 1)",
pointBorderColor: '#fff',
pointHoverBorderColor: "rgba(159,204,0, 1)" },
"rgba(250,109,33,0.5)",
"#9a9a9a","rgb(233,177,69)" ];
</code>```

for

```<code><canvas id="line" class="chart chart-line" chart-data="vm.data"
chart-colors="vm.colors" chart-labels="vm.labels" chart-series="vm.series"
chart-options="vm.options" chart-dataset-override="vm.datasetOverride"
chart-click="vm.onClick"></canvas>
</code>```

Image is below, the point stays black when hovered:

答:
You are assigning dataset options for the wrong controller. Instead of assinging it to vm.colors , you need to assign it for vm.datasetOverride , like so ...

```<code>vm.datasetOverride = [{
   backgroundColor: "rgba(159,204,0, 0.2)",
   pointBackgroundColor: "rgba(159,204,0, 1)",
   pointHoverBackgroundColor: "rgba(159,204,0, 0.8)",
   borderColor: "rgba(159,204,0, 1)",
   pointBorderColor: '#fff',
   pointHoverBorderColor: "rgba(159,204,0, 1)",
   fill: false
}];
</code>```

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var app = angular.module('app', ['chart.js']);

app.controller("LineCtrl", ['$scope', function(vm) {
   vm.labels = ["January", "February", "March", "April", "May", "June"];
   vm.data = [
      [65, 59, 80, 81, 56, 55]
   ];
   vm.datasetOverride = [{
      backgroundColor: "rgba(159,204,0, 0.2)",
      pointBackgroundColor: "rgba(159,204,0, 1)",
      pointHoverBackgroundColor: "rgba(159,204,0, 0.8)",
      borderColor: "rgba(159,204,0, 1)",
      pointBorderColor: '#fff',
      pointHoverBorderColor: "rgba(159,204,0, 1)",
      fill: false
   }];
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/angular.chartjs/latest/angular-chart.min.js"></script>
<div ng-app="app" ng-controller="LineCtrl">
    <canvas id="line" class="chart chart-line" chart-data="data" chart-colors="colors" chart-labels="labels" chart-series="series" chart-options="options" chart-dataset-override="datasetOverride" chart-click="onClick"></canvas>
</div></code>```

Body:
I'm using input color as an object but property "pointHoverBorderColor" isn't working using :

angular : 1.5.3,

chart.js : 2.6.0,

angular-chart.js : 1.1.1.

vm.colors = [ { backgroundColor: "rgba(159,204,0, 0.2)",
pointBackgroundColor: "rgba(159,204,0, 1)",
pointHoverBackgroundColor: "rgba(159,204,0, 0.8)",
borderColor: "rgba(159,204,0, 1)",
pointBorderColor: '#fff',
pointHoverBorderColor: "rgba(159,204,0, 1)" },
"rgba(250,109,33,0.5)",
"#9a9a9a","rgb(233,177,69)" ];

for

<canvas id="line" class="chart chart-line" chart-data="vm.data"
chart-colors="vm.colors" chart-labels="vm.labels" chart-series="vm.series"
chart-options="vm.options" chart-dataset-override="vm.datasetOverride"
chart-click="vm.onClick"></canvas>

Image is below, the point stays black when hovered:

Body:
You are assigning dataset options for the wrong controller. Instead of assinging it to vm.colors , you need to assign it for vm.datasetOverride , like so ...

vm.datasetOverride = [{
   backgroundColor: "rgba(159,204,0, 0.2)",
   pointBackgroundColor: "rgba(159,204,0, 1)",
   pointHoverBackgroundColor: "rgba(159,204,0, 0.8)",
   borderColor: "rgba(159,204,0, 1)",
   pointBorderColor: '#fff',
   pointHoverBorderColor: "rgba(159,204,0, 1)",
   fill: false
}];

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var app = angular.module('app', ['chart.js']);

app.controller("LineCtrl", ['$scope', function(vm) {
   vm.labels = ["January", "February", "March", "April", "May", "June"];
   vm.data = [
      [65, 59, 80, 81, 56, 55]
   ];
   vm.datasetOverride = [{
      backgroundColor: "rgba(159,204,0, 0.2)",
      pointBackgroundColor: "rgba(159,204,0, 1)",
      pointHoverBackgroundColor: "rgba(159,204,0, 0.8)",
      borderColor: "rgba(159,204,0, 1)",
      pointBorderColor: '#fff',
      pointHoverBorderColor: "rgba(159,204,0, 1)",
      fill: false
   }];
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/angular.chartjs/latest/angular-chart.min.js"></script>
<div ng-app="app" ng-controller="LineCtrl">
    <canvas id="line" class="chart chart-line" chart-data="data" chart-colors="colors" chart-labels="labels" chart-series="series" chart-options="options" chart-dataset-override="datasetOverride" chart-click="onClick"></canvas>
</div>


问:
Should I use ArrayField or ManyToManyField for tags
I am trying to add tags to a model for a postgres db in django and I found two solutions:

using foreign keys:

```<code>class Post(models.Model):
    tags = models.ManyToManyField('tags')
    ...

class Tag(models.Model):
    name = models.CharField(max_length=140)
</code>```

using array field:

```<code>from django.contrib.postgres.fields import ArrayField

class Post(models.Model):
    tags = ArrayField(models.CharField(max_length=140))
    ...
</code>```

assuming that I don't care about supporting other database-backends in my code, what is a recommended solution ?

答:
If you use an Array field,

The size of each row in your DB is going to be a bit large thus Postgres is going to be using more toast tables

Every time you get the row, unless you specifically use defer the field or otherwise exclude it from the query via only, or values or something, you paying the cost of loading all those values every time you iterate across that row. If that's what you need then so be it.

Filtering based on values in that array, while possible isn't going to be as nice and the Django ORM doesn't make it as obvious as it does for M2M tables.

If you use M2M field,

You can filter more easily on those related values
Those fields are postponed by default, you can use prefetch_related if you need them and then get fancy if you want only a subset of those values loaded.

Total storage in the DB is going to be slightly higher with M2M because of keys, and extra id fields.

The cost of the joins in this case is completely negligible because of keys.

With that being said, the above answer doesn't belong to me. A while ago, I had stumbled upon this dilemma when I was learning Django. I had found the answer here in this question, Django Postgres ArrayField vs One-to-Many relationship.

Hope you get what you were looking for.

Body:
I am trying to add tags to a model for a postgres db in django and I found two solutions:

using foreign keys:

class Post(models.Model):
    tags = models.ManyToManyField('tags')
    ...

class Tag(models.Model):
    name = models.CharField(max_length=140)

using array field:

from django.contrib.postgres.fields import ArrayField

class Post(models.Model):
    tags = ArrayField(models.CharField(max_length=140))
    ...

assuming that I don't care about supporting other database-backends in my code, what is a recommended solution ?

ContentLicense: CC BY-SA 4.0


问:
Create a new Course with Google Apps Script - ClassRoom API
There is an error on line 11 stating:

Requested entity was not found. (line 11, file "Code")

line 11

```<code>createdCourse = Classroom.Courses.get('Bio10');
</code>```

The function:

```<code>function createA_NewCourse() {
  var courseNew,createdCourse;

  courseNew = Classroom.newCourse();

  courseNew.name = "10th Grade Biology";
  courseNew.id = "Bio10";

  Logger.log("course.name " + courseNew.name);//Verify that name was set

  createdCourse = Classroom.Courses.get('Bio10');//Try to get course by ID

  Logger.log(createdCourse)
}
</code>```

How is a new course created in Apps Script?

答:
As stated by @Dean Ransevycz, there should be a create() method.

Here's a sample code:

```<code>function createCourses() {

  var course;
  course = Classroom.newCourse();

  course.name = "10th Grade Biology";
  course.ownerId = "me";
  //course.id = "Bio10";

  course = Classroom.Courses.create(course);
  Logger.log('%s (%s)', course.name, course.id);

  var list = Classroom.Courses.list();
  Logger.log(list);

}
</code>```

You're getting an Requested entity was not found. error since you might be using the wrong course id. And I guess you can't set an ID when creating a course. (Source.)

Body:
There is an error on line 11 stating:

Requested entity was not found. (line 11, file "Code")

line 11

createdCourse = Classroom.Courses.get('Bio10');

The function:

function createA_NewCourse() {
  var courseNew,createdCourse;

  courseNew = Classroom.newCourse();

  courseNew.name = "10th Grade Biology";
  courseNew.id = "Bio10";

  Logger.log("course.name " + courseNew.name);//Verify that name was set

  createdCourse = Classroom.Courses.get('Bio10');//Try to get course by ID

  Logger.log(createdCourse)
}

How is a new course created in Apps Script?

Body:
As stated by @Dean Ransevycz, there should be a create() method.

Here's a sample code:

function createCourses() {

  var course;
  course = Classroom.newCourse();

  course.name = "10th Grade Biology";
  course.ownerId = "me";
  //course.id = "Bio10";

  course = Classroom.Courses.create(course);
  Logger.log('%s (%s)', course.name, course.id);

  var list = Classroom.Courses.list();
  Logger.log(list);

}

You're getting an Requested entity was not found. error since you might be using the wrong course id. And I guess you can't set an ID when creating a course. (Source.)


问:
How to set table width with phpword?
Documentation says that table width can be set in addTable, but I don't understand how to make it work. Also I need to set 100% width
I tried:

```<code>$table = $section->addTable(array(
  'width' => 100
));
$table = $section->addTable(array(
  'width' => '100'
));
$table = $section->addTable(array(
  'width' => '100%'
));
</code>```

But nothing seems to work. What should I write to make it work?

答:
When you look on the documentation (https://www.phpdocx.com/api-documentation/word-content/add-table-Word-document-with-PHP) I believe you are using it wrong.

$docx->addTable($valuesTable, $paramsTable); your options parameter should come after table values.

Something like this?

```<code>require_once 'classes/CreateDocx.inc';

$docx = new CreateDocx();

$valuesTable = array(
    array(
        11,12,13,14
    ),
    array(
        21,22,23,24
    ),
    array(
        31,32,33,34
    ),
);

$paramsTable = array(
  'width' => 100, // not sure if width 100 is valid parameter though check the documentation
);

$docx = $section->addTable($valuesTable, $paramsTable);
</code>```

Title: How to set table width with phpword?

Body:
Documentation says that table width can be set in addTable, but I don't understand how to make it work. Also I need to set 100% width
I tried:

$table = $section->addTable(array(
  'width' => 100
));
$table = $section->addTable(array(
  'width' => '100'
));
$table = $section->addTable(array(
  'width' => '100%'
));

But nothing seems to work. What should I write to make it work?

Body:
When you look on the documentation (https://www.phpdocx.com/api-documentation/word-content/add-table-Word-document-with-PHP) I believe you are using it wrong.

$docx->addTable($valuesTable, $paramsTable); your options parameter should come after table values.

Something like this?

require_once 'classes/CreateDocx.inc';

$docx = new CreateDocx();

$valuesTable = array(
    array(
        11,12,13,14
    ),
    array(
        21,22,23,24
    ),
    array(
        31,32,33,34
    ),
);

$paramsTable = array(
  'width' => 100, // not sure if width 100 is valid parameter though check the documentation
);

$docx = $section->addTable($valuesTable, $paramsTable);


问:
MongoDB query in PHP different collections, same entry, different types, result on a null
I'm actually working on a web server, I need to look for CardNumber in my client collection.

In order to do that, I get all the Bills where I can find my CardNumber

The problem is : in Bills, CardNumber are Int64, but in client, CardNumber are double. In PHP my query doesn't work, but when i'm doing it on mongo it works.

Here is my code

```<code>foreach ($this->bills as $bill)
    {
        $query = [
             //Already tried to cast, floatvar etc...
            'CARDNUM' => doublevar(($bill['CARDNUM']))
        ];
        $result = $collection->findOne($query);
        var_dump($result); //Always null
    }
</code>```

For exemple, my first $bill['CARDNUM'] gives me 0123456

If I do this db.getCollection('clientCollec').find({"CARDNUM" : 0123456}) in a mongoShell, I have a result.

Thanks for helping

答: Found my problem, the error was the name of clientCollec in my code ...

Body:
I'm actually working on a web server, I need to look for CardNumber in my client collection.

In order to do that, I get all the Bills where I can find my CardNumber

The problem is : in Bills, CardNumber are Int64, but in client, CardNumber are double. In PHP my query doesn't work, but when i'm doing it on mongo it works.

Here is my code

foreach ($this->bills as $bill)
    {
        $query = [
             //Already tried to cast, floatvar etc...
            'CARDNUM' => doublevar(($bill['CARDNUM']))
        ];
        $result = $collection->findOne($query);
        var_dump($result); //Always null
    }

For exemple, my first $bill['CARDNUM'] gives me 0123456

If I do this db.getCollection('clientCollec').find({"CARDNUM" : 0123456}) in a mongoShell, I have a result.

Thanks for helping


问:
Random number for dice (help)
```<code>import java.util.*;
import java.lang.*;

public class Main {

public static void main(String[] args) {

    Random dice = new Random();
    int a[]=new int [7];

    for(int i = 1 ; i <=100;i++){
        ++a[1+dice.nextInt(6)];
    }
    System.out.println("Sno\t Values");

    int no;
    for(int i=1;i<a.length;i++){

        System.out.println(i+"\t"+a[i]);
    }

}
}

Sno  Values
1   19
2   13
3   16
4   16
5   19
6   18
</code>```

Can any one please explain this line "++a[1+dice.nextInt(6)]"

i know this program provides random number generated from 1-6 on how many times within the given value

答:
nextInt() returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

So the value of 1+dice.nextInt(6) will fall between 1 to 6 (both inclusive) and increment the value of a[x] like a counter for x

Title: Random number for dice (help)

Body:
import java.util.*;
import java.lang.*;

public class Main {

public static void main(String[] args) {

    Random dice = new Random();
    int a[]=new int [7];

    for(int i = 1 ; i <=100;i++){
        ++a[1+dice.nextInt(6)];
    }
    System.out.println("Sno\t Values");

    int no;
    for(int i=1;i<a.length;i++){

        System.out.println(i+"\t"+a[i]);
    }

}
}

Sno  Values
1   19
2   13
3   16
4   16
5   19
6   18

Can any one please explain this line "++a[1+dice.nextInt(6)]"

i know this program provides random number generated from 1-6 on how many times within the given value


问:
Force to do flush to get new Primary key ID to store EmbeddedId
We are using JPA and we are using EmbeddedId in one of the Entity.

Tables are as bellow :

```<code>Role:
+-----------------------------+
| roleId | name | discription |
+-----------------------------+

Rights:
+-----------------------------+
| rightId | name | discription|
+-----------------------------+

rightrole
+--------------------------------------+
| roleId | rightId | some other column |
+--------------------------------------+
</code>```

Entity for role table is:

```<code>@Entity
@Table(name = "role")
public class Role {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private Long roleID;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "role", fetch = FetchType.LAZY)
    private List<RightRole> rightRoleList;

.......
}
</code>```

Entity for rightrole table is:

```<code>    @Entity
    @Table(name = "rightrole")
    public class RightRole extends BaseEntity<RightRolePK> {

        private static final long serialVersionUID = 1L;

        @EmbeddedId
        protected RightRolePK rightRolePK;

        @JoinColumn(name = "roleID", referencedColumnName = "roleID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Role role;

        @JoinColumn(name = "rightID", referencedColumnName = "rightID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Right right;

        ......
     }

    @Embeddable
    public class RightRolePK implements Serializable {
    private static final long serialVersionUID = 1L;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
      private long roleID;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
     private long rightID;

   .....

}
</code>```

My problem is whenever I want to create new role with rights then first I have to store(persist) role object and then I have to do flush to get newly generated id for role. then and then i can put it in rightrole entity's object.

Is there any way by that i can set rightrole list in role object and persist it in one go.

This flush casing us performance bottle neck because for bulk insert we have to persist single single object.

we are using Auto Generated primary key.

答:
Using a @ManyToMany annotation you can define your entity like this:

Role:

```<code> @Entity
    @Table(name = "role")
    public class Role {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @NotNull
        @Column(name = "ROLE_ID", nullable = false)
        private Long roleID;

        @JoinTable(name = "rightrole",
                joinColumns = {
                    @JoinColumn(name = "roleID", referencedColumnName = "ROLE_ID")},
                inverseJoinColumns = {
                    @JoinColumn(name = "rightID", referencedColumnName = "RIGHT_ID")})
        @ManyToMany
        private List<Right> rightList;

    }
</code>```

You have to write @ManyToMany(cascade = {CascadeType.PERSIST}) in inverseJoinColumns otherwise your parent data will get deleted if child get deleted.

Right:

```<code>@Entity
@Table(name = "right")
public class Right {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(name = "RIGHT_ID",nullable = false)
    private Long rightId;

}
</code>```

you can then simply:

```<code>    Role role = new  Role();
    List<Right> rightList = new ArrayList<>();
    Right right1 = new Right();
    Right right2 = new Right();
    rightList.add(right1);
    rightList.add(right2);
    role.setRightList(rightList);
</code>```

and persist

the @JoinTable annotation will take care of inserting in the rightrole table even without an entity (as long as that table have only the id columns of role and right) so you'll get something like this in db

Role :

```<code>id name     etc
1  roleName etc
</code>```

Right:

```<code>id name       etc
1  rightName1 etc
2  rightName2 etc
</code>```

rightrole:

```<code>roleId rightID
1      1
1      2
</code>```

Body:
We are using JPA and we are using EmbeddedId in one of the Entity.

Tables are as bellow :

Role:
+-----------------------------+
| roleId | name | discription |
+-----------------------------+

Rights:
+-----------------------------+
| rightId | name | discription|
+-----------------------------+

rightrole
+--------------------------------------+
| roleId | rightId | some other column |
+--------------------------------------+

Entity for role table is:

@Entity
@Table(name = "role")
public class Role {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private Long roleID;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "role", fetch = FetchType.LAZY)
    private List<RightRole> rightRoleList;

.......
}

Entity for rightrole table is:

    @Entity
    @Table(name = "rightrole")
    public class RightRole extends BaseEntity<RightRolePK> {

        private static final long serialVersionUID = 1L;

        @EmbeddedId
        protected RightRolePK rightRolePK;

        @JoinColumn(name = "roleID", referencedColumnName = "roleID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Role role;

        @JoinColumn(name = "rightID", referencedColumnName = "rightID", insertable = false, updatable = false)
        @ManyToOne(fetch = FetchType.LAZY)
        private Right right;

        ......
     }

    @Embeddable
    public class RightRolePK implements Serializable {
    private static final long serialVersionUID = 1L;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
      private long roleID;

      @Basic(optional = false)
      @NotNull
      @Column(nullable = false)
     private long rightID;

   .....

}

My problem is whenever I want to create new role with rights then first I have to store(persist) role object and then I have to do flush to get newly generated id for role. then and then i can put it in rightrole entity's object.

Is there any way by that i can set rightrole list in role object and persist it in one go.

This flush casing us performance bottle neck because for bulk insert we have to persist single single object.

we are using Auto Generated primary key.

Body:
Using a @ManyToMany annotation you can define your entity like this:

Role:

 @Entity
    @Table(name = "role")
    public class Role {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @NotNull
        @Column(name = "ROLE_ID", nullable = false)
        private Long roleID;

        @JoinTable(name = "rightrole",
                joinColumns = {
                    @JoinColumn(name = "roleID", referencedColumnName = "ROLE_ID")},
                inverseJoinColumns = {
                    @JoinColumn(name = "rightID", referencedColumnName = "RIGHT_ID")})
        @ManyToMany
        private List<Right> rightList;

    }

You have to write @ManyToMany(cascade = {CascadeType.PERSIST}) in inverseJoinColumns otherwise your parent data will get deleted if child get deleted.

Right:

@Entity
@Table(name = "right")
public class Right {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(name = "RIGHT_ID",nullable = false)
    private Long rightId;

}

you can then simply:

    Role role = new  Role();
    List<Right> rightList = new ArrayList<>();
    Right right1 = new Right();
    Right right2 = new Right();
    rightList.add(right1);
    rightList.add(right2);
    role.setRightList(rightList);

and persist

the @JoinTable annotation will take care of inserting in the rightrole table even without an entity (as long as that table have only the id columns of role and right) so you'll get something like this in db

Role :

id name     etc
1  roleName etc

Right:

id name       etc
1  rightName1 etc
2  rightName2 etc

rightrole:

roleId rightID
1      1
1      2


问:
How to update graphql endpoint (not using Graph.cool)
I spent some time working through the ReactQL starter kit and watched the intro video outlining how the kit is set up, but one area I am still confused on is where to put our graphql specific stuff if we don't use a Graph.cool endpoint.

Graph.cool seems great, but to get more experience with Graphql, I want to set up my own schema, queries, etc.

What is the best practice for handling our own graphql stuff? Do I place the:

```<code>app.get('/', {
graphiql: true
})
</code>```

or Koa equivalent in the config/project.js APOLLO variable? I am more familiar with Express than Koa, but could also see it going in the entry/server.js file.

答:
The GraphQL endpoint is set in config/project.js, under the APOLLO variable by default:

```<code>export const APOLLO = {
  uri: 'https://api.graph.cool/simple/v1/cinomw2r1018601o42x5z69uc',
};
</code>```

Change APOLLO.uri to point to another GraphQL server will update both the server and browser environments to use that new server.

If you want to create your own GraphQL server alongside the front-end web server that ReactQL starts by default, there's an example you can see here for wiring up your own schema and GraphQL endpoint:

https://github.com/reactql/examples/tree/master/graphql-server

(Usage instructions for example projects can be found here)

Body:
I spent some time working through the ReactQL starter kit and watched the intro video outlining how the kit is set up, but one area I am still confused on is where to put our graphql specific stuff if we don't use a Graph.cool endpoint.

Graph.cool seems great, but to get more experience with Graphql, I want to set up my own schema, queries, etc.

What is the best practice for handling our own graphql stuff? Do I place the:

app.get('/', {
graphiql: true
})

or Koa equivalent in the config/project.js APOLLO variable? I am more familiar with Express than Koa, but could also see it going in the entry/server.js file.

Body:
The GraphQL endpoint is set in config/project.js, under the APOLLO variable by default:

export const APOLLO = {
  uri: 'https://api.graph.cool/simple/v1/cinomw2r1018601o42x5z69uc',
};

Change APOLLO.uri to point to another GraphQL server will update both the server and browser environments to use that new server.

If you want to create your own GraphQL server alongside the front-end web server that ReactQL starts by default, there's an example you can see here for wiring up your own schema and GraphQL endpoint:

https://github.com/reactql/examples/tree/master/graphql-server

(Usage instructions for example projects can be found here)


问:
Looping over array: ReactJS Objects are not valid as a React child
```<code> render() {
    var NewsCards = this.state.news.map((b,i)=>{
        return(
            <div key={i} className="row">
                <div className="col-10">
                    <img src={b.image} className="img-fluid"/>
                </div>
            </div>
        )
    })
    return (
        <div className="container-fluid global-container-bottom-padding">
            {RenderIf(this.state.loading)(
            <div id="cssload-pgloading">
                <div className="cssload-loadingwrap">
                    <ul className="cssload-bokeh">
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                    </ul>
                </div>
            </div>
            )}
            {RenderIf(!this.state.loading)(
                { NewsCards }
            )}
        </div>
    );
}
</code>```

Not quite sure where I went wrong here.

EDIT:

this.state.news is an array of objects

```<code>[
    {
        "image":"imgurl",
        "link":"imglink"
    },
    {
        "image":"imgurl",
        "link":"imglink"
    }
]
</code>```

答:
The issue is here, as you create an object literal with NewsCard field using object property shorthand syntax by mistake:

```<code>{RenderIf(!this.state.loading)(
  { NewsCards }
)}
</code>```

Please change your code to:

```<code>!this.state.loading &&
<div>
  {NewsCards}
</div>
</code>```

or

```<code>{RenderIf(!this.state.loading)(
  <div>{NewsCards}</div>
)}
</code>```

as there is no support for fragments ready yet, at least before React 16.

Body:
 render() {
    var NewsCards = this.state.news.map((b,i)=>{
        return(

        )
    })
    return (

            {RenderIf(this.state.loading)(

            )}
            {RenderIf(!this.state.loading)(
                { NewsCards }
            )}

    );
}

Not quite sure where I went wrong here.

EDIT:

this.state.news is an array of objects

[
    {
        "image":"imgurl",
        "link":"imglink"
    },
    {
        "image":"imgurl",
        "link":"imglink"
    }
]

Body:
The issue is here, as you create an object literal with NewsCard field using object property shorthand syntax by mistake:

{RenderIf(!this.state.loading)(
  { NewsCards }
)}

Please change your code to:

!this.state.loading &&
<div>
  {NewsCards}
</div>

or

{RenderIf(!this.state.loading)(
  <div>{NewsCards}</div>
)}

as there is no support for fragments ready yet, at least before React 16.


问:
Why method call is giving error?
When I am writing this code I am getting error

```<code>public class MethodOverloading
{

void m(short i)
{
System.out.println("SHort");
}

public static void main(String[] args)
{

MethodOverloading ml=new MethodOverloading();
ml.m(10);
}

}
</code>```

I am getting error that m(short) is not applicable for m(int) but when I am
assigning int value to short then no error then if am not able to pass int
value as an argument to method that accepts short then how short variable is accepting int value as below?

```<code>short d=10;
System.out.println(d);
</code>```

答:
You have to cast the int to short, because 10 is considered like an int not a short :

```<code>ml.m((short)10);
</code>```

Title: Why method call is giving error?

Body:
When I am writing this code I am getting error

public class MethodOverloading
{

void m(short i)
{
System.out.println("SHort");
}

public static void main(String[] args)
{

MethodOverloading ml=new MethodOverloading();
ml.m(10);
}

}

I am getting error that m(short) is not applicable for m(int) but when I am
assigning int value to short then no error then if am not able to pass int
value as an argument to method that accepts short then how short variable is accepting int value as below?

short d=10;
System.out.println(d);

Body:
You have to cast the int to short, because 10 is considered like an int not a short :

ml.m((short)10);


问:
codeigniter : How to store product selection in the database
In my shopping cart. There are products that have 2 types of options that have been selected. Namely color and size. How to save to database?

my controller :

```<code>foreach ($this->cart->contents() as $item)
{
    if(empty($items['before']))
    {
        $harga_fix_diskon_atau_non_diskon = $this->cart->format_number($item['price']);
    }
    else
    {
        $harga_fix_diskon_atau_non_diskon = $this->cart->format_number($item['before']);
    }
    foreach ($this->cart->product_options($item['rowid']) as $option_name => $option_value)
    {
        if(empty($option_value))
        {
            $option_value = "";
        }
        else
        {
            $option_value;
        }
        $option = $option_value;
    }
    $data_order[] = array(
        'invoice'     => $invoice,
        'name_product' => $item['name'],
        'size'        => $item['option'],
        'color'       => $item['option'],
        'qty'         => $item['qty'],
        'price'       => $harga_fix_diskon_atau_non_diskon,
        'weight'      => $item['berat'],
    );
}
$this->db->insert_batch('order_product', $data_order);
</code>```

I have saved all the data except in the product selection section

The result of my database process is a matter of size and color :

```<code>----------------------------------------------------------------
| invoice | name_product | size | color | qty | price | weight |
----------------------------------------------------------------
| ST5623  | Nike         |  42  | 42    |  2  |   28  |  0,5   |
</code>```

*Should be in color columns containing colors.

If i use print_r (); And managed to show me what I wanted. Namely the color is color and size is size

```<code>foreach ($this->cart->product_options($item['rowid']) as $option_name => $option_value)
{
    if(empty($option_value))
    {
        $option_value = "";
    }
    else
    {
        $option_value;
    }
    $option = $option_value;
    print_r($option);
}
</code>```

please for help. thank you.

答:
because your setting same value for color and size </p>

```<code>'size' => $item['option'], 'color' => $item['option']
</code>```

<p>Or you need to check  $item for color parameter </p>

Body:
In my shopping cart. There are products that have 2 types of options that have been selected. Namely color and size. How to save to database?

my controller :

foreach ($this->cart->contents() as $item)
{
    if(empty($items['before']))
    {
        $harga_fix_diskon_atau_non_diskon = $this->cart->format_number($item['price']);
    }
    else
    {
        $harga_fix_diskon_atau_non_diskon = $this->cart->format_number($item['before']);
    }
    foreach ($this->cart->product_options($item['rowid']) as $option_name => $option_value)
    {
        if(empty($option_value))
        {
            $option_value = "";
        }
        else
        {
            $option_value;
        }
        $option = $option_value;
    }
    $data_order[] = array(
        'invoice'     => $invoice,
        'name_product' => $item['name'],
        'size'        => $item['option'],
        'color'       => $item['option'],
        'qty'         => $item['qty'],
        'price'       => $harga_fix_diskon_atau_non_diskon,
        'weight'      => $item['berat'],
    );
}
$this->db->insert_batch('order_product', $data_order);

I have saved all the data except in the product selection section

The result of my database process is a matter of size and color :

----------------------------------------------------------------
| invoice | name_product | size | color | qty | price | weight |
----------------------------------------------------------------
| ST5623  | Nike         |  42  | 42    |  2  |   28  |  0,5   |

*Should be in color columns containing colors.

If i use print_r (); And managed to show me what I wanted. Namely the color is color and size is size

foreach ($this->cart->product_options($item['rowid']) as $option_name => $option_value)
{
    if(empty($option_value))
    {
        $option_value = "";
    }
    else
    {
        $option_value;
    }
    $option = $option_value;
    print_r($option);
}

please for help. thank you.

Body:
because your setting same value for color and size

'size' => $item['option'], 'color' => $item['option']

Or you need to check  $item for color parameter


答:
```<code>m1.m((short) 10);
</code>```

<p>Cast the 10 (since there's no type associated with it Java assumes it's a 32-bit int instead of a 16-bit short) to a short. </p>

Title: Why method call is giving error?

Body:
m1.m((short) 10);

Cast the 10 (since there's no type associated with it Java assumes it's a 32-bit int instead of a 16-bit short) to a short.


问:
How do I test a file upload in rails?
I have a controller which is responsible for accepting JSON files and then processing the JSON files to do some user maintenance for our application. In user testing the file upload and processing works, but of course I would like to automate the process of testing the user maintenance in our testing. How can I upload a file to a controller in the functional testing framework?</p>

答:
if you are getting the file in your controller with the following

```<code>json_file = params[:json_file]
FileUtils.mv(json_file.tempfile, File.expand_path('.')+'/tmp/newfile.json')
</code>```

then try the following in your specs:

```<code>json_file = mock('JsonFile')
json_file.should_receive(:tempfile).and_return("files/bulk_bookmark.json")
post 'import', :json_file => json_file
response.should be_success
</code>```

This will make the fake method to 'tempfile' method, which will return the path to the loaded file.

Title: How do I test a file upload in rails?

Body:
if you are getting the file in your controller with the following

json_file = params[:json_file]
FileUtils.mv(json_file.tempfile, File.expand_path('.')+'/tmp/newfile.json')

then try the following in your specs:

json_file = mock('JsonFile')
json_file.should_receive(:tempfile).and_return("files/bulk_bookmark.json")
post 'import', :json_file => json_file
response.should be_success

This will make the fake method to 'tempfile' method, which will return the path to the loaded file.


问:
How to take index value of entire table
Currently I am displaying 5 rows per page. But if take index of the table in first page It is taking the index 0 to 6 for the first page. In second page again it is taking from 0 to 6. I want to know the selected index of the whole table with including (all pagination) table row values. How to take index of all the table rows

```<code>$scope.SampleTable[index].Name; //it is taking particular page index only
</code>```

I want Entire page index value using tr dir-paginate

答:
If you have a variable in your controller specifying the current page (e.g. $scope.currentPage), you could do something like this:

```<code>$scope.SampleTable[index + ($scope.currentPage * 5 - 5)].Name;
</code>```

Title: How to take index value of entire table

Body:
Currently I am displaying 5 rows per page. But if take index of the table in first page It is taking the index 0 to 6 for the first page. In second page again it is taking from 0 to 6. I want to know the selected index of the whole table with including (all pagination) table row values. How to take index of all the table rows

$scope.SampleTable[index].Name; //it is taking particular page index only

I want Entire page index value using tr dir-paginate

Body:
If you have a variable in your controller specifying the current page (e.g. $scope.currentPage), you could do something like this:

$scope.SampleTable[index + ($scope.currentPage * 5 - 5)].Name;


问:
Output Event Emitter triggers only on ngOnInit
I have parent and child component, from child need to trigger the parent component function.

Parent.component.ts

```<code>loadData(event) {
      console.log(event);
}
</code>```

Parent.component.html

```<code><app-project (uploaded)="loadData($event)" ></app-project>
</code>```

child.component.ts

```<code>@Output() uploaded:EventEmitter<any> = new EventEmitter();

ngOnInit() {
    this.uploaded.emit('complete'); // Worked
}

loadProject(){
    this.uploaded.emit('complete'); // Not triggering the parent function
}
</code>```

child.component.html

```<code><button type="button" (click)="loadProject(project)" label="Load Project"></button>
</code>```

Don't know what is the wrong in this, but workes from ngOnInit.

Calling the loadProject from child.component.html.

答:
change:

child.component.ts

```<code>@Output() uploaded = new EventEmitter<string>();

ngOnInit() {
    this.uploaded.emit('complete'); // Worked
}

loadProject(){
    this.uploaded.emit('complete'); // Not triggering the parent function
}
</code>```

child.component.html

```<code><button type="button" (click)="loadProject()" label="Load Project"></button>
</code>```

You were passing a string value to loadProject, but in child component there is no definition of loadproject that takes 1 parameter

Body:
I have parent and child component, from child need to trigger the parent component function.

Parent.component.ts

loadData(event) {
      console.log(event);
}

Parent.component.html

<app-project (uploaded)="loadData($event)" ></app-project>

child.component.ts

@Output() uploaded:EventEmitter<any> = new EventEmitter();

ngOnInit() {
    this.uploaded.emit('complete'); // Worked
}

loadProject(){
    this.uploaded.emit('complete'); // Not triggering the parent function
}

child.component.html

<button type="button" (click)="loadProject(project)" label="Load Project"></button>

Don't know what is the wrong in this, but workes from ngOnInit.

Calling the loadProject from child.component.html.

Body:
change:

child.component.ts

@Output() uploaded = new EventEmitter<string>();

ngOnInit() {
    this.uploaded.emit('complete'); // Worked
}

loadProject(){
    this.uploaded.emit('complete'); // Not triggering the parent function
}

child.component.html

<button type="button" (click)="loadProject()" label="Load Project"></button>

You were passing a string value to loadProject, but in child component there is no definition of loadproject that takes 1 parameter


问:
PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value
After typing cordova run android in terminal, I'm getting this error:

```<code>Waiting for emulator to start...
PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value [/Users/username/Library/Android/sdk]!
</code>```

This happens after exporting:

```<code>export ANDROID_SDK_ROOT='/Users/username/Library/Android/sdk'
</code>```

Before exporting I got:

```<code>Waiting for emulator to start...
PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
</code>```

Any ideas where I'm going wrong? I'm sure this is the sdk root so why am I getting broken avd system path?

答:
There are may be several different problems when you move your AVD or SDK to another directory, or replace an old SDK with a new one, or somehow get the SDK corrupted.

Below I'll describe all the possible problems I know, and will give you several ways to solve them.

Of course I assume that you have any AVD created, and it is located in C:\Users\<user_name>\.android\avd (Windows) or ~/.android/avd (Linux/MacOS).

If you moved .android to another place then set the ANDROID_SDK_HOME environment variable to the path of the parent dir containing your .android and make sure the AVD Manager successfully found your Virtual Device.

Also check paths in <user_home>/.android/avd/<avd_name>.ini

Incomplete/corrupted SDK stucture

```<code>PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value
</code>```

These 2 errors happen if the emulator cannot find the SDK, or the SDK is broken.

So, first of all I recommend to remove the ANDROID_SDK_ROOT variable at all. It's only needed when the emulator is located outside of the SDK directory. But in general, your emulator stays inside the SDK dir. And in this case it must detect the SDK location automatically. If it doesn't, then your SDK probably has wrong filetree. Please do the following:

Check that the SDK directory has at least these 4 directories: emulator, platforms, platform-tools, system-images. It is very important! These directories must be present. If some of them don't exist, then just create empty dirs.

Go to <user_home>/.android/avd/<avd_name> and open config.ini. Find the image.sysdir.1 property. It points at the directory, inside the SDK directory, that contains the actual system image. Make sure that this directory exists and contains files like build.prop, system.img, etc. If it doesn't, then you have to open the SDK Manager and download system images your AVD requires (see below).

If everything's set up properly, when these errors about ANDROID_SDK_ROOT must be gone. If they're not, then now you may try to set up ANDROID_SDK_ROOT variable.

Required packages and HAXM are not installed

The next problem you may face is that the emulator starts to launch, but hangs up or quits immediatelly. That probably means that you don't have all the required packages installed.

Another possible error is:

Could not automatically detect an ADB binary. Some emulator functionality will not work until a custom path to ADB is added in the extended settings page.

So, to successfully launch any AVD you must be sure that at least these packages are installed:

```<code>emulator (Android Emulator)
platform-tools (Android SDK Platform-Tools)
tools (Android SDK Tools)
</code>```

And as I mentioned earlier you must install system images your AVD is using, for example system-images;android-25;google_apis;x86

Note that the most recent versions on SDK don't have a standalone SDK Manager.exe. Instead of it you have either to use Android Studio, or tools\bin\sdkmanager.bat (Linux/MacOS probably have sh files).

To list all available packages use sdkmanager --list or sdkmanager --list --verbose

To install packages use sdkmanager <package1> <package2> ...

Also I recommend to install HAXM on your system manually.

Qcow2-files refer to incorrect/nonexistent base-images

The last problem I'll mention happens when you're trying to move AVD or SDK from one computer or directory to another. In this case you may get such error:

qemu-system-i386.exe: -drive if=none,overlap-check=none,cache=unsafe,index=0,id=system,file=C:\Users\<old_user_name>\.android\avd\<avd_name>.

avd\system.img.qcow2,read-only: Could not open backing file: Could not open '<old_sdk_dir>\system-images\android-22\google_apis\x86\system.img': Invalid argument

There are 2 ways to fix it:

If you don't care about the data the AVD contains, just delete all the qcow2 files from the AVD directory (e.g. from <user_home>/.android/avd/<avd_name>). In this case you will get a clean version of Android, like after a hard reset.

If the data on the emulator is important to you, then open all qcow2 files one by one using any HEX editor (I prefer HxD), find the path of a base img file, and change it to the correct one in the Overwrite mode (to preserve the file size). Then select the path and get its length in hex (e.g. 2F). 2F represents the ASCII slash /. Put it into position 13:

PS: Not sure, but there are probably some utilites like qemu-img allowing to set different base image. Well, to me it's easier to manually edit the binary.

Now you'll probably be able to successfully launch your Android Virtual Device. I hope so :)

Body:
After typing cordova run android in terminal, I'm getting this error:

Waiting for emulator to start...
PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value [/Users/username/Library/Android/sdk]!

This happens after exporting:

export ANDROID_SDK_ROOT='/Users/username/Library/Android/sdk'

Before exporting I got:

Waiting for emulator to start...
PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT

Any ideas where I'm going wrong? I'm sure this is the sdk root so why am I getting broken avd system path?

Body:
There are may be several different problems when you move your AVD or SDK to another directory, or replace an old SDK with a new one, or somehow get the SDK corrupted.

Below I'll describe all the possible problems I know, and will give you several ways to solve them.

Of course I assume that you have any AVD created, and it is located in C:\Users\<user_name>\.android\avd (Windows) or ~/.android/avd (Linux/MacOS).

If you moved .android to another place then set the ANDROID_SDK_HOME environment variable to the path of the parent dir containing your .android and make sure the AVD Manager successfully found your Virtual Device.

Also check paths in <user_home>/.android/avd/<avd_name>.ini

Incomplete/corrupted SDK stucture

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

These 2 errors happen if the emulator cannot find the SDK, or the SDK is broken.

So, first of all I recommend to remove the ANDROID_SDK_ROOT variable at all. It's only needed when the emulator is located outside of the SDK directory. But in general, your emulator stays inside the SDK dir. And in this case it must detect the SDK location automatically. If it doesn't, then your SDK probably has wrong filetree. Please do the following:

Check that the SDK directory has at least these 4 directories: emulator, platforms, platform-tools, system-images. It is very important! These directories must be present. If some of them don't exist, then just create empty dirs.

Go to <user_home>/.android/avd/<avd_name> and open config.ini. Find the image.sysdir.1 property. It points at the directory, inside the SDK directory, that contains the actual system image. Make sure that this directory exists and contains files like build.prop, system.img, etc. If it doesn't, then you have to open the SDK Manager and download system images your AVD requires (see below).

If everything's set up properly, when these errors about ANDROID_SDK_ROOT must be gone. If they're not, then now you may try to set up ANDROID_SDK_ROOT variable.

Required packages and HAXM are not installed

The next problem you may face is that the emulator starts to launch, but hangs up or quits immediatelly. That probably means that you don't have all the required packages installed.

Another possible error is:

Could not automatically detect an ADB binary. Some emulator functionality will not work until a custom path to ADB is added in the extended settings page.

So, to successfully launch any AVD you must be sure that at least these packages are installed:

emulator (Android Emulator)
platform-tools (Android SDK Platform-Tools)
tools (Android SDK Tools)

And as I mentioned earlier you must install system images your AVD is using, for example system-images;android-25;google_apis;x86

Note that the most recent versions on SDK don't have a standalone SDK Manager.exe. Instead of it you have either to use Android Studio, or tools\bin\sdkmanager.bat (Linux/MacOS probably have sh files).

To list all available packages use sdkmanager --list or sdkmanager --list --verbose

To install packages use sdkmanager <package1> <package2> ...

Also I recommend to install HAXM on your system manually.

Qcow2-files refer to incorrect/nonexistent base-images

The last problem I'll mention happens when you're trying to move AVD or SDK from one computer or directory to another. In this case you may get such error:

qemu-system-i386.exe: -drive if=none,overlap-check=none,cache=unsafe,index=0,id=system,file=C:\Users\<old_user_name>\.android\avd\<avd_name>.

avd\system.img.qcow2,read-only: Could not open backing file: Could not open '<old_sdk_dir>\system-images\android-22\google_apis\x86\system.img': Invalid argument

There are 2 ways to fix it:

If you don't care about the data the AVD contains, just delete all the qcow2 files from the AVD directory (e.g. from <user_home>/.android/avd/<avd_name>). In this case you will get a clean version of Android, like after a hard reset.

If the data on the emulator is important to you, then open all qcow2 files one by one using any HEX editor (I prefer HxD), find the path of a base img file, and change it to the correct one in the Overwrite mode (to preserve the file size). Then select the path and get its length in hex (e.g. 2F). 2F represents the ASCII slash /. Put it into position 13:

PS: Not sure, but there are probably some utilites like qemu-img allowing to set different base image. Well, to me it's easier to manually edit the binary.

Now you'll probably be able to successfully launch your Android Virtual Device. I hope so :)


答:
Narrowing conversion can occur in an assignment unlike literals being passed to a method. From the JLS

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

Title: Why method call is giving error?


问:
How can I correctly align text of varying size along the bottom of a div?
I'm primarily a back-end guy, so apologies if this is a silly question. If I've missed any information that I should provide, I'd be happy to oblige.

I have a small currency sign, and a larger number that I want to be aligned along the bottom of the div so that their bottom pixels are in line. Currently it looks like this.

Now (I believe) I have the div containing the elements in the right place.

But as you can see the text flows out of it.

The css for the div is as follows...

```<code>position: absolute;
left: 375px;
top: 15px;
width: 400px;
height: 70px;
</code>```

And for each the currency and number elements respectively.

```<code>position: absolute;
left: 0px;
bottom: 0px;
color: #e64611;

position: absolute;
left: 15px;
bottom: 0px;
color: #e64611;
font-size: 50px;
</code>```

答:
Avoid using position: absolute.

Use the position: relative to make the currency in the middle of the value:

```<code>.currency {
  font-size:12px;
  font-weight: bold;
  position: relative;
  top:-10px;
}

.value {
  font-size:41px;
  font-weight: bold;
}
</code>```

Maybe for you will be useful to check some front-end article about CSS positioning.

Here is the demo.

Body:
I'm primarily a back-end guy, so apologies if this is a silly question. If I've missed any information that I should provide, I'd be happy to oblige.

I have a small currency sign, and a larger number that I want to be aligned along the bottom of the div so that their bottom pixels are in line. Currently it looks like this.

Now (I believe) I have the div containing the elements in the right place.

But as you can see the text flows out of it.

The css for the div is as follows...

position: absolute;
left: 375px;
top: 15px;
width: 400px;
height: 70px;

And for each the currency and number elements respectively.

position: absolute;
left: 0px;
bottom: 0px;
color: #e64611;

position: absolute;
left: 15px;
bottom: 0px;
color: #e64611;
font-size: 50px;

Body:
Avoid using position: absolute.

Use the position: relative to make the currency in the middle of the value:

.currency {
  font-size:12px;
  font-weight: bold;
  position: relative;
  top:-10px;
}

.value {
  font-size:41px;
  font-weight: bold;
}

Maybe for you will be useful to check some front-end article about CSS positioning.

Here is the demo.


问:
Templated tooltip for DataGridCell depending on cell's content
I want to display tooltip of different view depending on content of DataGridCell. The following code works.

```<code><DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ToolTip>
                                <ToolTip.Content>
                                    <TextBlock Foreground="Blue" Text="{Binding}"></TextBlock>
                                </ToolTip.Content>
                            </ToolTip>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.Items>
        <system:String>AAA</system:String>
        <system:Int32>2</system:Int32>
    </DataGrid.Items>
</DataGrid>
</code>```

But when I try using templates I have no success (I want select template basing on type of view model).

```<code><DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ToolTip>
                                <ToolTip.ContentTemplate>
                                    <DataTemplate>
                                        <ContentControl Content="{Binding}">
                                            <ContentControl.Resources>
                                                <DataTemplate DataType="system:String">
                                                    <TextBlock Foreground="Blue" Text="{Binding}"></TextBlock>
                                                </DataTemplate>
                                                <DataTemplate DataType="system:Int32">
                                                    <TextBlock Foreground="Red" Text="{Binding}"></TextBlock>
                                                </DataTemplate>
                                            </ContentControl.Resources>
                                        </ContentControl>
                                    </DataTemplate>
                                </ToolTip.ContentTemplate>
                            </ToolTip>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.Items>
        <system:String>AAA</system:String>
        <system:Int32>2</system:Int32>
    </DataGrid.Items>
</DataGrid>
</code>```

How to fix it?

答:
Bind the Content property of the Tooltip itself to the DataContext and use explicit type specifications using {x:Type}:

```<code><DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ToolTip Content="{Binding}">
                                <ToolTip.ContentTemplate>
                                    <DataTemplate>
                                        <ContentControl Content="{Binding}">
                                            <ContentControl.Resources>
                                                <DataTemplate DataType="{x:Type system:String}">
                                                    <TextBlock Foreground="Blue" Text="{Binding}"></TextBlock>
                                                </DataTemplate>
                                                <DataTemplate DataType="{x:Type system:Int32}">
                                                    <TextBlock Foreground="Red" Text="{Binding}"></TextBlock>
                                                </DataTemplate>
                                            </ContentControl.Resources>
                                        </ContentControl>
                                    </DataTemplate>
                                </ToolTip.ContentTemplate>
                            </ToolTip>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.Items>
        <system:String>AAA</system:String>
        <system:Int32>2</system:Int32>
    </DataGrid.Items>
</DataGrid>
</code>```

Body:
I want to display tooltip of different view depending on content of DataGridCell. The following code works.

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding}">
            <DataGridTextColumn.CellStyle>

            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.Items>
        <system:String>AAA</system:String>
        <system:Int32>2</system:Int32>
    </DataGrid.Items>
</DataGrid>

But when I try using templates I have no success (I want select template basing on type of view model).

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding}">
            <DataGridTextColumn.CellStyle>

            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.Items>
        <system:String>AAA</system:String>
        <system:Int32>2</system:Int32>
    </DataGrid.Items>
</DataGrid>

How to fix it?

Body:
Bind the Content property of the Tooltip itself to the DataContext and use explicit type specifications using {x:Type}:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="1" Binding="{Binding}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ToolTip Content="{Binding}">
                                <ToolTip.ContentTemplate>
                                    <DataTemplate>
                                        <ContentControl Content="{Binding}">
                                            <ContentControl.Resources>
                                                <DataTemplate DataType="{x:Type system:String}">
                                                    <TextBlock Foreground="Blue" Text="{Binding}"></TextBlock>
                                                </DataTemplate>
                                                <DataTemplate DataType="{x:Type system:Int32}">
                                                    <TextBlock Foreground="Red" Text="{Binding}"></TextBlock>
                                                </DataTemplate>
                                            </ContentControl.Resources>
                                        </ContentControl>
                                    </DataTemplate>
                                </ToolTip.ContentTemplate>
                            </ToolTip>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <DataGrid.Items>
        <system:String>AAA</system:String>
        <system:Int32>2</system:Int32>
    </DataGrid.Items>
</DataGrid>


问:
bootstrap modal disappear immediately after showing
I'm using bootstrap's modal plugin in rails

The website says I can gain the function without write javascript.

I add the following line in my HTML(in slim):

```<code>div#makeDream.modal.hide.fade
    div.modal-header
        a.close data-dismiss='modal'
        h3 Hello World!
    div.modal-body
    div.modal-footer

a data-toggle='modal' data-target='#makeDream' Button
</code>```

However, after I clicking the Button. the modal shows up, but immediately disappears!

I found the css of #makeDream has

```<code>display:none
</code>```

I don't where it comes

Can someone tell me how to fix it?

答:
In my case, I had a button that was calling the modal...

```<code><asp:Button ID="btnSearch" runat="server" Width="100%" Text="Select
Action" class="btn btn-info btn-sm" data-backdrop="static"
data-toggle="modal" data-target="#myModalID"></asp:Button>
</code>```

I changed the button to an anchor tag and it works fine

```<code><a href="#" ID="btnShowModal" class="btn btn-info btn-sm"
data-backdrop="static" data-toggle="modal" style="width:100%;"
data-target="#myModalID">Select Action</a>
</code>```

This was after i checked that i was not loading duplicate bootstrap javascript files. Bootstrap.min.js or boostrap.js. Just one is enough.

Body:
I'm using bootstrap's modal plugin in rails

The website says I can gain the function without write javascript.

I add the following line in my HTML(in slim):

div#makeDream.modal.hide.fade
    div.modal-header
        a.close data-dismiss='modal'
        h3 Hello World!
    div.modal-body
    div.modal-footer

a data-toggle='modal' data-target='#makeDream' Button

However, after I clicking the Button. the modal shows up, but immediately disappears!

I found the css of #makeDream has

display:none

I don't where it comes

Can someone tell me how to fix it?

Body:
In my case, I had a button that was calling the modal...

<asp:Button ID="btnSearch" runat="server" Width="100%" Text="Select
Action" class="btn btn-info btn-sm" data-backdrop="static"
data-toggle="modal" data-target="#myModalID"></asp:Button>

I changed the button to an anchor tag and it works fine

<a href="#" ID="btnShowModal" class="btn btn-info btn-sm"
data-backdrop="static" data-toggle="modal" style="width:100%;"
data-target="#myModalID">Select Action</a>

This was after i checked that i was not loading duplicate bootstrap javascript files. Bootstrap.min.js or boostrap.js. Just one is enough.


问:
How to sum columns that have a field in common in Postgresql?
How to calculate total length for all rows that have a certain value?

Let's say there's the following table:

```<code> id | unit_id | length | column to be filled with total length
 1  |   1     | 10
 2  |   1     |  4
 3  |   1     |  5
 4  |   2     |  3
 5  |   3     |  3
 6  |   3     |  6
</code>```

In this case, how to update the table, making all the rows that have unit_id of 1 to have the sum of all the length of rows that have unit_id of 1 (10 + 4 + 5 = 19) then both rows that have a unit_id of 3 to have 9.

I've tried

```<code>update test.routes
set total_length = (select sum(length) from test.routes where unit_id = unit_id) where unit_id = unit_id
</code>```

But what it does is that it just updates the entire table with the same value, how to update the correct sum for each unit_id?

答:
This should do the work.

```<code>update
    routes as s
inner join (
    select unit_id, sum(length) as total_length from routes group by unit_id
) as g
set
    s.total_length = g.total_length
where
    s.unit_id = g.unit_id
</code>```

Here we are creating a temporary table which has total length for the unit_id. By using the join between 2 tables we can do this bit efficiently then using a subquery

Body:
How to calculate total length for all rows that have a certain value?

Let's say there's the following table:

 id | unit_id | length | column to be filled with total length
 1  |   1     | 10
 2  |   1     |  4
 3  |   1     |  5
 4  |   2     |  3
 5  |   3     |  3
 6  |   3     |  6

In this case, how to update the table, making all the rows that have unit_id of 1 to have the sum of all the length of rows that have unit_id of 1 (10 + 4 + 5 = 19) then both rows that have a unit_id of 3 to have 9.

I've tried

update test.routes
set total_length = (select sum(length) from test.routes where unit_id = unit_id) where unit_id = unit_id

But what it does is that it just updates the entire table with the same value, how to update the correct sum for each unit_id?

Body:
This should do the work.

update
    routes as s
inner join (
    select unit_id, sum(length) as total_length from routes group by unit_id
) as g
set
    s.total_length = g.total_length
where
    s.unit_id = g.unit_id

Here we are creating a temporary table which has total length for the unit_id. By using the join between 2 tables we can do this bit efficiently then using a subquery