问:
Reserved SQL keyword 'User' is not permitted as simple type name
When I gave the roo command

```<code>entity --class  ~.domain.User
</code>```

in the roo shell, I got

```<code>Reserved SQL keyword 'User' is not permitted as simple type name
</code>```

What I want to know is that, is there a way to gave alias name to the entity ? Because I do have a couple of entities which name are not permitted as above. Or is there a way to overcome this kind of problem ?

Any help will be greatly appreciated. Thank you very much.

答:
If you want to change the entity name, but keep the table name:

```<code>entity --class ~.domain.FooUser --table user
</code>```

I would think there is a way to quote all sql identifiers, but I don't know that much about Roo.

Body:
When I gave the roo command

entity --class  ~.domain.User

in the roo shell, I got

Reserved SQL keyword 'User' is not permitted as simple type name

What I want to know is that, is there a way to gave alias name to the entity ? Because I do have a couple of entities which name are not permitted as above. Or is there a way to overcome this kind of problem ?

Any help will be greatly appreciated. Thank you very much.

Body:
If you want to change the entity name, but keep the table name:

entity --class ~.domain.FooUser --table user

I would think there is a way to quote all sql identifiers, but I don't know that much about Roo.


来源: stackexchange

问:
How to query using left join to get the result
I am working on two tables on mysql in which I am trying to get all rows from left table along with the columns in the second table which are matching with first table.

business

```<code>id | business_name
-------------------
1   |abc
2   |def
3   |ghi
4   |jkl
5   |mno
</code>```

orders

```<code>business_id_fk  | order_status  | date
----------------------------------------
2               |  PCK         |  30-03-2017
3               |  DEL         |  30-03-2017
2               |  DEL         |  30-03-2017
2               |  PCK         |  30-03-2017
4               |  PCK         |  28-03-2017
3               |  PCK         |  29-03-2017
4               |  DEL         |  30-03-2017
</code>```

I want all rows from business table and count of each order status for every business on 30-03-2017 from orders table sort by total.
result set is:

```<code>id | business_name | total(order_status) | count(PCK) | count(DEL)
----------------------------------------------------
2  | def           | 3       | 2      |  1
3  | ghi           | 1       | 0      |  1
4  | jkl           | 1       | 0      |  1
1  | abc           | 0       | 0      |  0
5  | mno           | 0       | 0      |  0
</code>```

Please help me in query to getting the above result.

答:
You can use conditional aggregation on the join:

```<code>select b.id,
    b.business_name,
    count(o.order_status) as total_count,
    coalesce(sum(o.order_status = 'PCK'), 0) as count_PCK,
    coalesce(sum(o.order_status = 'DEL'), 0) as count_DEL
from business b
left join orders o on b.id = o.business_id_fk
    and o.date = '2017-03-30'
group by b.id,
    b.business_name;
</code>```

I have assumed the datatype of date column on orders table as date (or atleast formatted string in the format YYYY-MM-DD).

Demo

ContentLicense: CC BY-SA 3.0

Body:
I am working on two tables on mysql in which I am trying to get all rows from left table along with the columns in the second table which are matching with first table.

business

id | business_name
-------------------
1   |abc
2   |def
3   |ghi
4   |jkl
5   |mno

orders

business_id_fk  | order_status  | date
----------------------------------------
2               |  PCK         |  30-03-2017
3               |  DEL         |  30-03-2017
2               |  DEL         |  30-03-2017
2               |  PCK         |  30-03-2017
4               |  PCK         |  28-03-2017
3               |  PCK         |  29-03-2017
4               |  DEL         |  30-03-2017

I want all rows from business table and count of each order status for every business on 30-03-2017 from orders table sort by total.
result set is:

id | business_name | total(order_status) | count(PCK) | count(DEL)
----------------------------------------------------
2  | def           | 3       | 2      |  1
3  | ghi           | 1       | 0      |  1
4  | jkl           | 1       | 0      |  1
1  | abc           | 0       | 0      |  0
5  | mno           | 0       | 0      |  0

Please help me in query to getting the above result.

Body:
You can use conditional aggregation on the join:

select b.id,
    b.business_name,
    count(o.order_status) as total_count,
    coalesce(sum(o.order_status = 'PCK'), 0) as count_PCK,
    coalesce(sum(o.order_status = 'DEL'), 0) as count_DEL
from business b
left join orders o on b.id = o.business_id_fk
    and o.date = '2017-03-30'
group by b.id,
    b.business_name;

I have assumed the datatype of date column on orders table as date (or atleast formatted string in the format YYYY-MM-DD).

Demo


问:
How to Connect localhost (with invalid certificate) using Alamofire?
This my first project using swift. I am usin alamofire to connect the API. I have a local copy form the API I want to use for debugging - so I can set test data - because the remote API has already real data that I can't mess with.

The problem is I am getting the below error when I try to access https://localhost:8443/MyProject

Optional(Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “localhost” which could put your confidential information at risk." UserInfo=0x7fbeb8c61ff0 {NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorCodeKey=-9813, NSUnderlyingError=0x7fbeb8ea5c00 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1202.)", NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “localhost” which could put your confidential information at risk., NSErrorFailingURLKey=https://localhost:8443/myproject/api/loginUser.pdo, NSErrorFailingURLStringKey=https://localhost:8443/myproject/api/loginUser.pdo, _kCFStreamErrorDomainKey=3})

I have found many solution most of them for Objective-c as using setAllowsAnyHTTPSCertificate or using the delegate for Connection.
but I could not find an equevelent method for setAllowsAnyHTTPSCertificate in swift, and I not sure how to set the delegate to the connection while using alamofire.
any ideas what I need to do?

I know that setAllowsAnyHTTPSCertificate is private api and will cause the project to be rejected by Apple. I want to use it only while debugging then it will be removed before the publishing the project.

Thank you in advance.

答: Replacing with https to http of my base url. resolved the error.</p>


问:
VBA-excel double loop condition
I am currently working in excel vba, though my programming is simply terrible. I would like to perform the following functionality. I have 2 ranges of data:

One range (a1:a10) refers to the variable that need to be checked against the other range (b1:b250). The condition the variable is checking against should be that if the variable is smaller (<) than the values in the range (b1:b250), then it should spit out the variable, otherwise is should show "0".

Therefore a = 1 to 10 should check against all the values of b = 1 to 250 as if the loop should run 2500 times to ensure all the values in range (a1:a10) have checked against range (b1:b250). Please let me know if you can help or what other information is necessary.

答:
Thanks Ali SM for showing an excellent, but less known way!
Before Ali, I would have suggested one more Loop-Less approach:

```<code>Sub WithoutLoop()

Range("E1").FormulaR1C1 = "=""Vs Examiner ""&OFFSET(R2C2,COLUMN()-5,0)"
Range("E2").FormulaR1C1 = "=IF(OFFSET(R2C2,COLUMN()-5,0)<RC4,OFFSET(R2C2,COLUMN()-5,0),0)"
Range("E1").Copy
Range("E1", Range("E1").Offset(0, 9)).PasteSpecial xlPasteFormulas
Range("E2").Copy
Range("E2", Range("E2").Offset(2500, 9)).PasteSpecial xlPasteFormulas

End Sub
</code>```

Before Macro:

After Macro:

Title: VBA-excel double loop condition

Body:
Thanks Ali SM for showing an excellent, but less known way!
Before Ali, I would have suggested one more Loop-Less approach:

Sub WithoutLoop()

Range("E1").FormulaR1C1 = "=""Vs Examiner ""&OFFSET(R2C2,COLUMN()-5,0)"
Range("E2").FormulaR1C1 = "=IF(OFFSET(R2C2,COLUMN()-5,0)<RC4,OFFSET(R2C2,COLUMN()-5,0),0)"
Range("E1").Copy
Range("E1", Range("E1").Offset(0, 9)).PasteSpecial xlPasteFormulas
Range("E2").Copy
Range("E2", Range("E2").Offset(2500, 9)).PasteSpecial xlPasteFormulas

End Sub

Before Macro:

After Macro:


问:
Change background-image from array using setInterval, but only twice

Objective

I'm trying to change the background-image: url of a
 every four seconds based off images from an array using setInterval

There can be up to four images in the array

Where I'm getting stuck is that I need to loop over the array twice and then return to the first image in the array before stopping setInterval.

Where I'm at

Right now, the background-image only switches once before stopping. I should mention that I'm using Jinja with some JavaScript, but the two languages syntactically contain similarities.

scripts.js

```<code>    $(function() {

        // Array of images
        var carouselImages = [

            // Returns a list containing a progression of integers
            // Similar to iterating over an array
            {% for n in range(1, coursePhotos) %}
                "{{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg",
            {% endfor %}
        ];

        // The div of the background I want to change
        var carousel = $(".course__images");

        // Change the background image every four seconds
        var changeBackgroundImage = setInterval(function(){

            // Returns a list containing a progression of integers
            // Similar to iterating over an array
            {% for n in range(1, coursePhotos) %}
                carousel.css("background-image", "url({{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg");
            {% endfor %}
        }, 4000);
    });
</code>```

答:
Example

```<code>var images = [
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=one&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=two&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=three&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=four&w=100&h=100'
];

var img = document.querySelector('#image');
var index = 0;
var iterations = 0;

var updateImage = function() {
  /* reset index to zero if current index is greater than number of images.
   * increment iterations variable since it means we've done one whole loop.
   */
  if (index >= images.length) {
    index = 0;
    iterations++;
  }

  // set the background image
  img.style.backgroundImage = 'url(' + images[index] + ')';

  /* clear interval (stop timer) when we've reached
   * the number of iterations allowed.
   */
  if (iterations >= 2) {
    clearInterval(interval);
  } else {
    /* increment current index in order to get next image
     * when this function gets called again.
     */
    index++;
  }
}

// update first image
updateImage();

// initiate timer
var interval = setInterval(updateImage, 4000);
</code>```

JSFiddle Demo: https://jsfiddle.net/3wayry32/1/

Body:
Objective

I'm trying to change the background-image: url of a
 every four seconds based off images from an array using setInterval

There can be up to four images in the array

Where I'm getting stuck is that I need to loop over the array twice and then return to the first image in the array before stopping setInterval.

Where I'm at

Right now, the background-image only switches once before stopping. I should mention that I'm using Jinja with some JavaScript, but the two languages syntactically contain similarities.

scripts.js

    $(function() {

        // Array of images
        var carouselImages = [

            // Returns a list containing a progression of integers
            // Similar to iterating over an array
            {% for n in range(1, coursePhotos) %}
                "{{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg",
            {% endfor %}
        ];

        // The div of the background I want to change
        var carousel = $(".course__images");

        // Change the background image every four seconds
        var changeBackgroundImage = setInterval(function(){

            // Returns a list containing a progression of integers
            // Similar to iterating over an array
            {% for n in range(1, coursePhotos) %}
                carousel.css("background-image", "url({{ COPY.content.cdn_url }}/courses/{{course.slug}}/{{course.slug}}-{{n}}.jpg");
            {% endfor %}
        }, 4000);
    });

Body:
Example

var images = [
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=one&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=two&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=three&w=100&h=100',
  'https://placeholdit.imgix.net/~text?txtsize=33&txt=four&w=100&h=100'
];

var img = document.querySelector('#image');
var index = 0;
var iterations = 0;

var updateImage = function() {
  /* reset index to zero if current index is greater than number of images.
   * increment iterations variable since it means we've done one whole loop.
   */
  if (index >= images.length) {
    index = 0;
    iterations++;
  }

  // set the background image
  img.style.backgroundImage = 'url(' + images[index] + ')';

  /* clear interval (stop timer) when we've reached
   * the number of iterations allowed.
   */
  if (iterations >= 2) {
    clearInterval(interval);
  } else {
    /* increment current index in order to get next image
     * when this function gets called again.
     */
    index++;
  }
}

// update first image
updateImage();

// initiate timer
var interval = setInterval(updateImage, 4000);

JSFiddle Demo: https://jsfiddle.net/3wayry32/1/


问:
How can I make div not disappear when buttons are clicked
So I have a page that fades in when a button is pressed, and the page has 3 font-awesome icons on it. And when you click anywhere on the page it fades it fades the page out. When you click the font-awesome icons on the page it takes you to another page. But the problem is that the page fades out when you click the buttons. I want it to only fade out when you click anywhere except on the font-awesome icons.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  text-align: center;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    color: white;
    border-radius: 100px;
    font-size: 3.5em;
    padding: .5em;
    border: 5px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover {
    color: #f06262;
    cursor: pointer;
}

.fa-twitter:hover,
.fa-github:hover,
.fa-steam:hover {
    background-color: #1dd2e2;
    cursor: pointer;
}

.home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button class="home">Home</button>
    <button class="about">About</button>
    <button class="projects">Projects</button>
    <button id="fadeContent" class="contact">Contact</button>

```

答:
Check if the clicked element has the font awesome class.  If not, do the fade:

```<code>bodyContent.click(function(e) {
  if(!$(e.target).hasClass('fa')) {
    $(this).fadeOut(400);
  }
})
</code>```

Snippet:

$(function() {

  $('#fadeContent').click(function() {
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  text-align: center;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    color: white;
    border-radius: 100px;
    font-size: 3.5em;
    padding: .5em;
    border: 5px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover {
    color: #f06262;
    cursor: pointer;
}

.fa-twitter:hover,
.fa-github:hover,
.fa-steam:hover {
    background-color: #1dd2e2;
    cursor: pointer;
}

.home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button class="home">Home</button>
    <button class="about">About</button>
    <button class="projects">Projects</button>
    <button id="fadeContent" class="contact">Contact</button>

```

Body:
So I have a page that fades in when a button is pressed, and the page has 3 font-awesome icons on it. And when you click anywhere on the page it fades it fades the page out. When you click the font-awesome icons on the page it takes you to another page. But the problem is that the page fades out when you click the buttons. I want it to only fade out when you click anywhere except on the font-awesome icons.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  text-align: center;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    color: white;
    border-radius: 100px;
    font-size: 3.5em;
    padding: .5em;
    border: 5px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover {
    color: #f06262;
    cursor: pointer;
}

.fa-twitter:hover,
.fa-github:hover,
.fa-steam:hover {
    background-color: #1dd2e2;
    cursor: pointer;
}

.home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button class="home">Home</button>
    <button class="about">About</button>
    <button class="projects">Projects</button>
    <button id="fadeContent" class="contact">Contact</button>

Body:
Check if the clicked element has the font awesome class.  If not, do the fade:

bodyContent.click(function(e) {
  if(!$(e.target).hasClass('fa')) {
    $(this).fadeOut(400);
  }
})

Snippet:

$(function() {

  $('#fadeContent').click(function() {
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);

    bodyContent.click(function(e) {
      if(!$(e.target).hasClass('fa')) {
        $(this).fadeOut(400);
      }
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  text-align: center;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    color: white;
    border-radius: 100px;
    font-size: 3.5em;
    padding: .5em;
    border: 5px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover {
    color: #f06262;
    cursor: pointer;
}

.fa-twitter:hover,
.fa-github:hover,
.fa-steam:hover {
    background-color: #1dd2e2;
    cursor: pointer;
}

.home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <button class="home">Home</button>
    <button class="about">About</button>
    <button class="projects">Projects</button>
    <button id="fadeContent" class="contact">Contact</button>

      <div id="bodyContent">
           <i class="fa fa-times" aria-hidden="true"></i>
           <a href="https://twitter.com/LukielD" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i></a>
           <a href="https://github.com/LukieID" target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a>
           <a href="steamcommunity.com/id/LukieID" target="_blank"><i class="fa fa-steam" aria-hidden="true"></i></a>
      </div>

    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
    <script type="text/javascript" src="js/elegant.js"></script>

    <script type="text/javascript" src="js/transition.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="js/background.js"></script>
</body>
</html>


问:
JWPlayer CEA-608/708 captions styling
I am trying to dynamically set caption style like font Size, font color, background color and font family. Following is the code snippet;

```<code>jwplayer().setCaptions({"color":"#FF0000","fontSize": 14});
</code>```

This is working Chrome, but does not work on EDGE and FIREFOX. On IE11 closed caption are not displayed.

Is this a bug or is CC 608 support not uniform across different browsers?

Following are the versions:

JWPlayer: 7.9.3+commercial_v7-9-3.158

Microsoft Edge: 38.14393.0.0

Firefox: 52.0 (32-bit)

Chrome: 56.0.2924.87

IE: 11.953.14393.0

答: Apparently, when not using Flash, the CEA-608 styling depends on ::cue pseudo-element. see here github.com/jwplayer/jwplayer/issues/1813</p>

Title: JWPlayer CEA-608/708 captions styling

Body:
I am trying to dynamically set caption style like font Size, font color, background color and font family. Following is the code snippet;

jwplayer().setCaptions({"color":"#FF0000","fontSize": 14});

This is working Chrome, but does not work on EDGE and FIREFOX. On IE11 closed caption are not displayed.

Is this a bug or is CC 608 support not uniform across different browsers?

Following are the versions:

JWPlayer: 7.9.3+commercial_v7-9-3.158

Microsoft Edge: 38.14393.0.0

Firefox: 52.0 (32-bit)

Chrome: 56.0.2924.87

IE: 11.953.14393.0


问:
overload of template template function - explicit call
So, first consider the following where template parameters are known implicitly from the function arguments:

```<code>#include <iostream>
using namespace std;

class A {};
class B {};

template <class T1, class T2>
class C {
    T1 a;
    T2 b;
};

template <class T1>
class D {
    T1 a;
};

template <template<class, class> class TC, class TA, class TB>
void foo(TC<TA, TB> c) {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(TD<TA> d){
    std::cout << "T<T>" << std::endl;
};

int main() {
    C<A,B> c;
    D<A> d;

    foo(c);
    foo(d);
}
</code>```

And output is as you'd expect:

```<code>T<T,T>
T<T>
</code>```

However, what if I don't have an instance of class C and D so I need to explicitly call the correct overload?  How would this be done?  i.e., have a main() that consists of:

```<code>int main() {
    foo<C<A,B> >();
    foo<D<A> >();
}
</code>```

I've experimented with a few overloads of foo() as shown below:

```<code>template <template<class, class> class TC>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD>
void foo(){
    std::cout << "T<T>" << std::endl;
};

template <template<class, class> class TC, class TA, class TB>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(){
    std::cout << "T<T>" << std::endl;
};
</code>```

However, this (and all permutations I've been able to think of) simply results in a series of errors along the lines of the (abbreviated) output shown below

```<code>prog.cpp: In function 'int main()':
prog.cpp:44:18: error: no matching function for call to 'foo()'
     foo<C<A,B> >();
                  ^
prog.cpp:44:18: note: candidates are:
prog.cpp:19:6: note: template<template<class, class> class TC> void foo()
 void foo() {
      ^
prog.cpp:19:6: note:   template argument deduction/substitution failed:
prog.cpp:24:6: note: template<template<class> class TD> void foo()
 void foo(){
      ^
prog.cpp:24:6: note:   template argument deduction/substitution failed:
</code>```

Is what I'm looking to do even allowable?  If so, where am I messing up?

---- EDIT ----

So as apple apple pointed out if my main() is as follows:

```<code>int main() {
    foo<C, A, B>();
    foo<D, A>();
}
</code>```

I get the output as expected.

However, my real-world case winds up being more complex.  I'll expand a bit here.  The legacy code has (hundreds) of typedefs defined in headers elsewhere along the lines of:

```<code>typedef C<A, B> type_117;
typedef D<A>    type_252;
</code>```

The class I'm working on is templated and is instantiated with one of those typedefs as the templating argument.  So something along the lines of:

```<code>template <class Type>
class Test
{
public:
   Test();
   SomeClass mSC;
}
Test::Test()
  : mSC(foo<Type>())
{
};
</code>```

where Test was instantiated as

```<code>Test<type_117> aTest;
</code>```

So I've been trying to figure out how to write foo() for this context.  At the point I call foo() within my Test's initializer am I able to "decompose" it to produce the <C,A,B> form?  Or have I hit a roadblock and need to rework some of the existing framework?

答:
```<code>template<class T>struct tag_t{constexpr tag_t(){}};
template<class T>constexpr tag_t<T> tag{};
</code>```

these are type tags.  They can be passed to functions without an instance of the type.

Template functions will deduce on them.

```<code>template <template<class, class> class TC, class TA, class TB>
void foo(tag_t<TC<TA, TB>>) {
  std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(tag_t<TD<TA>>){
  std::cout << "T<T>" << std::endl;
};
</code>```

at call site do foo(tag<type_117>) and bob, as they say, is your uncle.

In C++98 (ick):

```<code>template<class T>struct tag_t{};
foo(tag_t<type_117>());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So, first consider the following where template parameters are known implicitly from the function arguments:

#include <iostream>
using namespace std;

class A {};
class B {};

template <class T1, class T2>
class C {
    T1 a;
    T2 b;
};

template <class T1>
class D {
    T1 a;
};

template <template<class, class> class TC, class TA, class TB>
void foo(TC<TA, TB> c) {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(TD<TA> d){
    std::cout << "T<T>" << std::endl;
};

int main() {
    C c;
    D d;

    foo(c);
    foo(d);
}

And output is as you'd expect:

T<T,T>
T<T>

However, what if I don't have an instance of class C and D so I need to explicitly call the correct overload?  How would this be done?  i.e., have a main() that consists of:

int main() {
    foo<C >();
    foo<D >();
}

I've experimented with a few overloads of foo() as shown below:

template <template<class, class> class TC>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD>
void foo(){
    std::cout << "T<T>" << std::endl;
};

template <template<class, class> class TC, class TA, class TB>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(){
    std::cout << "T<T>" << std::endl;
};

However, this (and all permutations I've been able to think of) simply results in a series of errors along the lines of the (abbreviated) output shown below

prog.cpp: In function 'int main()':
prog.cpp:44:18: error: no matching function for call to 'foo()'
     foo<C >();
                  ^
prog.cpp:44:18: note: candidates are:
prog.cpp:19:6: note: template<template<class, class> class TC> void foo()
 void foo() {
      ^
prog.cpp:19:6: note:   template argument deduction/substitution failed:
prog.cpp:24:6: note: template<template<class> class TD> void foo()
 void foo(){
      ^
prog.cpp:24:6: note:   template argument deduction/substitution failed:

Is what I'm looking to do even allowable?  If so, where am I messing up?

---- EDIT ----

So as apple apple pointed out if my main() is as follows:

int main() {
    foo<C, A, B>();
    foo<D, A>();
}

I get the output as expected.

However, my real-world case winds up being more complex.  I'll expand a bit here.  The legacy code has (hundreds) of typedefs defined in headers elsewhere along the lines of:

typedef C type_117;
typedef D    type_252;

The class I'm working on is templated and is instantiated with one of those typedefs as the templating argument.  So something along the lines of:

template <class Type>
class Test
{
public:
   Test();
   SomeClass mSC;
}
Test::Test()
  : mSC(foo<Type>())
{
};

where Test was instantiated as

Test<type_117> aTest;

So I've been trying to figure out how to write foo() for this context.  At the point I call foo() within my Test's initializer am I able to "decompose" it to produce the <C,A,B> form?  Or have I hit a roadblock and need to rework some of the existing framework?

Body:
template<class T>struct tag_t{constexpr tag_t(){}};
template<class T>constexpr tag_t<T> tag{};

these are type tags.  They can be passed to functions without an instance of the type.

Template functions will deduce on them.

template <template<class, class> class TC, class TA, class TB>
void foo(tag_t<TC<TA, TB>>) {
  std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(tag_t<TD<TA>>){
  std::cout << "T<T>" << std::endl;
};

at call site do foo(tag<type_117>) and bob, as they say, is your uncle.

In C++98 (ick):

template<class T>struct tag_t{};
foo(tag_t<type_117>());


问:
Ionic2 Native : Hide location bar in android
Plugin

```<code>ionic plugin add cordova-plugin-inappbrowser
</code>```

app.module.ts

```<code>const browser = this.iab.create('http://example.com','_blank','location = no,toolbar= no');
</code>```

edited the Android.manifest.xml

```<code>android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
</code>```

Edited the InAppBrowser.java

```<code>dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
</code>```

After all this I am still getting this Location bar.

Please guys help me out with this. Thank You!!

答:
The options string must not contain any blank space.So you have to write it as shown below without spaces.

```<code>'location=no,toolbar=no'
</code>```

Body:
Plugin

ionic plugin add cordova-plugin-inappbrowser

app.module.ts

const browser = this.iab.create('http://example.com','_blank','location = no,toolbar= no');

edited the Android.manifest.xml

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

Edited the InAppBrowser.java

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)

After all this I am still getting this Location bar.

Please guys help me out with this. Thank You!!

Body:
The options string must not contain any blank space.So you have to write it as shown below without spaces.

'location=no,toolbar=no'


问:
Search for lines that contain anything but alphabetic characters, dots and hyphens
I'm struggling to create a RegEx pattern to match lines that contain anything but a-zA-Z ,  . and -

So I don't want to match hello-world.txt , but I would like to match hello-world123.txt or hello-world(copy).txt

答:
If you don't want to match strings with just a-z. or -
it would be

^(?![a-zA-Z.-]+$).+$

For .+ you could substitute stuff you'd like to match (which could be anything)

like [a-zA-Z.()\d-]+


问:
.NET's GUID structure
http://msdn.microsoft.com/en-us/library/system.guid.aspx

How does it work? How does it guarantee unique ID? Does it only rely on probability or is there another trick? Can I always trust it to give unique id or what are cases where I should avoid guid?

答:
The .NET Guid.NewGuid() actually calls the function CoCreateGuid found in ole32.dll which is part of Windows "core".

The CoCreateGuid is calling the function UuidCreate which creates such thing, that is actually the "low level" of Guid.

From what I've read and understand (not official answer) it's generated using combination of MAC address of the machine and the current system time (amount of milliseconds that passed since 1/1/1970) and probably also random number but I'm not sure about this.

Avoid using GUID in the cases described under "Security Considerations" section in the link posted by Albin.

All your other questions has been answered in the other answers, no point to repeat it.:)

ContentLicense: CC BY-SA 2.5

Title: .NET's GUID structure


问:
Symfony 3 expected "Doctrine\Common\Collections\ArrayCollection" given ... when using OneToMany
I have a problem with this error:

```<code>Expected argument of type "AppBundle\Entity\BusVehiclesAmenities", "Doctrine\Common\Collections\ArrayCollection" given
</code>```

EDIT 3

After few comments I applied suggestions and error is gone now (remove ArrayCollection from bus vehicles amenities Entity, removed setting bus vehicles amenities entity from controller and removed ORM Join columns on all mapped entites)

Now I have this error:

```<code>The association AppBundle\Entity\BusVehiclesAmenities#bus refers to the inverse side field AppBundle\Entity\BusVehicles#busVehiclesAmenities which does not exist.
</code>```

Mapped entities

Bus vehicles:

```<code>/* @ORM\OneToMany(
     *     targetEntity="BusVehiclesAmenities",
     *     mappedBy="bus",
     *     fetch="EXTRA_LAZY",
     *     orphanRemoval=true,
     *     cascade={"persist"}

     * )
     *
     */

    private $busVehiclesAmenities;
</code>```

bus vehicles amenities entity:

```<code>private $bus;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Amenities", inversedBy="amenities")
     * @ORM\JoinColumn(name="amenities_id", referencedColumnName="id")
     *
     */
</code>```

I am using Collection of Forms to create OneToMany relationship. Problem is when I adding new data I got this error.

Does someone knows where is the problem?

CODE:
Bus Entity (Parent)

```<code>/**
     * @ORM\OneToMany(targetEntity="BusVehiclesAmenities", mappedBy="bus", cascade={"persist", "remove"}, fetch="EAGER", orphanRemoval=true)
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id", onDelete="CASCADE")
     *
     */

private $busVehiclesAmenities;

    public function __construct()
    {

        $this->busVehiclesAmenities = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         if ($this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
             return;
         }
        $this->busVehiclesAmenities->add($busVehiclesAmenities);
        $busVehiclesAmenities->addBus($this);

        return $this;
    }

    /**
     * Set busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function setBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         $this->busVehiclesAmenities = $busVehiclesAmenities;

        return $this;
    }

    /**
     * Remove busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     * @return BusVehicles
     */
    public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        if (!$this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
            return;
        }
        $this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
        $busVehiclesAmenities->removeBus($this);

        return $this;

    }
</code>```

Amenity Entity (Child)

```<code>/**
     *
     * @ORM\ManyToOne(targetEntity="BusVehicles", inversedBy="busVehiclesAmenities")
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id")
     *
     */
    private $bus;

    public function __construct()
    {
        $this->bus = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param BusVehicles $busVehicles
     */

    public function addBus(BusVehicles $busVehicles)
    {
        if ($this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->add($busVehicles);
        $busVehicles->addBusVehiclesAmenities($this);
    }

    /**
     * @param BusVehicles $busVehicles
     */
    public function removeBus(BusVehicles $busVehicles)
    {
        if (!$this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->removeElement($busVehicles);
        $busVehicles->removeBusVehiclesAmenities($this);
    }
</code>```

EDIT 1:

I removed ArrayCollection from BusVehiclesAmenitites Entity but I still got same error when I submit form.

EDIT 2:

Added forms

BusVehicles Form Type

```<code><?php

namespace AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class BusVehiclesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('licencePlate')
            ->add('chassisNumber')
            ->add('manufacturer')
            ->add('busVehiclesAmenities', CollectionType::class, array(
                'entry_type'   => BusVehiclesAmenitiesType::class,
                'prototype' => true,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\BusVehicles',
            'cascade_validation' => true,

        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'adminbundle_busvehicles';
    }

}
</code>```

BusVehiclesAmenities Form Type

```<code>    <?php

namespace AdminBundle\Form\Type;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use AppBundle\Entity\BusVehiclesAmenities;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BusVehiclesAmenitiesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('price', NumberType::class, array(

            ))
            ->add('amenities', EntityType::class, array(
                'class' =>'AppBundle:Amenities',
                'choice_label' => 'name',
            ))

        ;

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => BusVehiclesAmenities::class
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_busvehiclesamenities';
    }

}
</code>```

Controller.

```<code>/**
     * @Template
     */
    public function newAction(Request $request)
    {
        $bus = new BusVehicles();
        $busAmenities = new BusVehiclesAmenities();
        //   $this->getDoctrine()->getManager()->persist($busAmenities);
        $bus->setBusVehiclesAmenities($busAmenities);
        $form = $this->createForm(BusVehiclesType::class, $bus);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            /*$form->get('busVehiclesAmenities')->getData()->map(
                function ($amenities) use ($em, $bus) {

                    $bus->setBusVehiclesAmenities($amenities);
                    $em->persist($amenities);
                }
            );*/
            $em->persist($bus);

            $em->flush();

            // Adding flash message to our user

            $this->addFlash('success', 'admin.bus.created');

            //  return $this->redirectToRoute('bus_add');

        }
        return [
            'form' => $form->createView(),
        ];
    }
</code>```

答:
I have run into a similar problem to yours. What I did to fix the situation is remove the JoinColumn. It is actually redundant. It's one of those "magic" things about Symfony which can get annoying IMHO. Just make sure that your OneToMany annotation correctly points back to your ManyToOne. Here's an example-- this is in my User.php Entity:

```<code>/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\UserStats", mappedBy="user")
 */
private $userStats;
</code>```

And this is in the entity being joined (UserStats.php):

```<code>/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User",
 *     inversedBy="userStats")
 *
 */
private $user;
</code>```

As you can see, there is no JoinColumn, and everything works beautifully as a result. I hope this helps you. :)

Make sure that you use the proper path as I have above, i.e.

```<code>* (targetEntity="AppBundle\Entity\User", inversedBy="userStats")
</code>```

Body:
I have a problem with this error:

Expected argument of type "AppBundle\Entity\BusVehiclesAmenities", "Doctrine\Common\Collections\ArrayCollection" given

EDIT 3

After few comments I applied suggestions and error is gone now (remove ArrayCollection from bus vehicles amenities Entity, removed setting bus vehicles amenities entity from controller and removed ORM Join columns on all mapped entites)

Now I have this error:

The association AppBundle\Entity\BusVehiclesAmenities#bus refers to the inverse side field AppBundle\Entity\BusVehicles#busVehiclesAmenities which does not exist.

Mapped entities

Bus vehicles:

/* @ORM\OneToMany(
     *     targetEntity="BusVehiclesAmenities",
     *     mappedBy="bus",
     *     fetch="EXTRA_LAZY",
     *     orphanRemoval=true,
     *     cascade={"persist"}

     * )
     *
     */

    private $busVehiclesAmenities;

bus vehicles amenities entity:

private $bus;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Amenities", inversedBy="amenities")
     * @ORM\JoinColumn(name="amenities_id", referencedColumnName="id")
     *
     */

I am using Collection of Forms to create OneToMany relationship. Problem is when I adding new data I got this error.

Does someone knows where is the problem?

CODE:
Bus Entity (Parent)

/**
     * @ORM\OneToMany(targetEntity="BusVehiclesAmenities", mappedBy="bus", cascade={"persist", "remove"}, fetch="EAGER", orphanRemoval=true)
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id", onDelete="CASCADE")
     *
     */

private $busVehiclesAmenities;

    public function __construct()
    {

        $this->busVehiclesAmenities = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         if ($this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
             return;
         }
        $this->busVehiclesAmenities->add($busVehiclesAmenities);
        $busVehiclesAmenities->addBus($this);

        return $this;
    }

    /**
     * Set busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function setBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

         $this->busVehiclesAmenities = $busVehiclesAmenities;

        return $this;
    }

    /**
     * Remove busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     * @return BusVehicles
     */
    public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        if (!$this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
            return;
        }
        $this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
        $busVehiclesAmenities->removeBus($this);

        return $this;

    }

Amenity Entity (Child)

/**
     *
     * @ORM\ManyToOne(targetEntity="BusVehicles", inversedBy="busVehiclesAmenities")
     * @ORM\JoinColumn(name="bus_id", referencedColumnName="id")
     *
     */
    private $bus;

    public function __construct()
    {
        $this->bus = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param BusVehicles $busVehicles
     */

    public function addBus(BusVehicles $busVehicles)
    {
        if ($this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->add($busVehicles);
        $busVehicles->addBusVehiclesAmenities($this);
    }

    /**
     * @param BusVehicles $busVehicles
     */
    public function removeBus(BusVehicles $busVehicles)
    {
        if (!$this->bus->contains($busVehicles)) {
            return;
        }
        $this->bus->removeElement($busVehicles);
        $busVehicles->removeBusVehiclesAmenities($this);
    }

EDIT 1:

I removed ArrayCollection from BusVehiclesAmenitites Entity but I still got same error when I submit form.

EDIT 2:

Added forms

BusVehicles Form Type

<?php

namespace AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class BusVehiclesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('licencePlate')
            ->add('chassisNumber')
            ->add('manufacturer')
            ->add('busVehiclesAmenities', CollectionType::class, array(
                'entry_type'   => BusVehiclesAmenitiesType::class,
                'prototype' => true,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\BusVehicles',
            'cascade_validation' => true,

        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'adminbundle_busvehicles';
    }

}

BusVehiclesAmenities Form Type

    <?php

namespace AdminBundle\Form\Type;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use AppBundle\Entity\BusVehiclesAmenities;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BusVehiclesAmenitiesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('price', NumberType::class, array(

            ))
            ->add('amenities', EntityType::class, array(
                'class' =>'AppBundle:Amenities',
                'choice_label' => 'name',
            ))

        ;

    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => BusVehiclesAmenities::class
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_busvehiclesamenities';
    }

}

Controller.

/**
     * @Template
     */
    public function newAction(Request $request)
    {
        $bus = new BusVehicles();
        $busAmenities = new BusVehiclesAmenities();
        //   $this->getDoctrine()->getManager()->persist($busAmenities);
        $bus->setBusVehiclesAmenities($busAmenities);
        $form = $this->createForm(BusVehiclesType::class, $bus);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            /*$form->get('busVehiclesAmenities')->getData()->map(
                function ($amenities) use ($em, $bus) {

                    $bus->setBusVehiclesAmenities($amenities);
                    $em->persist($amenities);
                }
            );*/
            $em->persist($bus);

            $em->flush();

            // Adding flash message to our user

            $this->addFlash('success', 'admin.bus.created');

            //  return $this->redirectToRoute('bus_add');

        }
        return [
            'form' => $form->createView(),
        ];
    }

Body:
I have run into a similar problem to yours. What I did to fix the situation is remove the JoinColumn. It is actually redundant. It's one of those "magic" things about Symfony which can get annoying IMHO. Just make sure that your OneToMany annotation correctly points back to your ManyToOne. Here's an example-- this is in my User.php Entity:

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\UserStats", mappedBy="user")
 */
private $userStats;

And this is in the entity being joined (UserStats.php):

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User",
 *     inversedBy="userStats")
 *
 */
private $user;

As you can see, there is no JoinColumn, and everything works beautifully as a result. I hope this helps you. :)

Make sure that you use the proper path as I have above, i.e.

* (targetEntity="AppBundle\Entity\User", inversedBy="userStats")


问:
disabling file_browser_callback on insert/edit video on tinymce 4
I want to disable/hide browse button for source and other parameters in insert/edit video screen. At present I son't have back end implementation to provide the list of videos but I want this option available for insert/edit image. I am using file_browser_callback in tiny init but it looks to me that a same file_browser_callback is used to handle the browse for all the screen. Can someone suggest me a way to hide the browse for "insert/edit" video plugins but allow in "insert/edit image"?

Please check Fiddle

答:
TinyMCE has provided a way to do this by using file_picker_types. You will need to add this to the tinymce.init, maybe right above your "file_browser_callback:"

```<code>file_picker_types: 'image',
</code>```

https://www.tinymce.com/docs/configure/file-image-upload/#file_picker_types

Body:
TinyMCE has provided a way to do this by using file_picker_types. You will need to add this to the tinymce.init, maybe right above your "file_browser_callback:"

file_picker_types: 'image',

https://www.tinymce.com/docs/configure/file-image-upload/#file_picker_types


问:
How to find time is today or yesterday in android
I am developing an application for sending SMS. I am storing the current time and showing in the sent history page by retrieving the time from the database. In the sent history page I want to display the time of the message was sent. Here I want to check that the message has been sent today or yesterday or the the day before yesterday like that. If the message was sent yesterday means then I need to display "Yesterday 20:00" like that and even the message was sent yesterday before means "Monday 20:00". I don't know how it has to be done. Please help me if anybody knows.</p>

答:
As mentioned, DateUtils.isToday(d.getTime()) will work for determining if Date d is today. But some responses here don't actually answer how to determine if a date was yesterday. You can also do that easily with DateUtils:

```<code>public static boolean isYesterday(Date d) {
    return DateUtils.isToday(d.getTime() + DateUtils.DAY_IN_MILLIS);
}
</code>```

Following that, you could also determine if a date was tomorrow:

```<code>public static boolean isTomorrow(Date d) {
    return DateUtils.isToday(d.getTime() - DateUtils.DAY_IN_MILLIS);
}
</code>```

Body:
As mentioned, DateUtils.isToday(d.getTime()) will work for determining if Date d is today. But some responses here don't actually answer how to determine if a date was yesterday. You can also do that easily with DateUtils:

public static boolean isYesterday(Date d) {
    return DateUtils.isToday(d.getTime() + DateUtils.DAY_IN_MILLIS);
}

Following that, you could also determine if a date was tomorrow:

public static boolean isTomorrow(Date d) {
    return DateUtils.isToday(d.getTime() - DateUtils.DAY_IN_MILLIS);
}


问:
How to fix java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException when configuring EhCache for Hibernate 5.2.5
I am new to Hibernate and I started learning caching in Hibernate, I want to configure EhCache in my hibernate configuration file. I have added hibernate-ehcache-5.2.5.Final.jar to my build path and here is my hibernate.cfg.xml :

```<code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Enable the second level cache -->
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and recrete the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>

</session-factory>

</hibernate-configuration>
</code>```

Here is the main class from where I configure the session factory:

```<code>package hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
}
</code>```

After I run this code I receive the error message:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at org.hibernate.cache.internal.StrategyCreatorRegionFactoryImpl.create(StrategyCreatorRegionFactoryImpl.java:38)
at org.hibernate.cache.internal.StrategyCreatorRegionFactoryImpl.create(StrategyCreatorRegionFactoryImpl.java:23)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:198)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:161)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:67)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:28)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.<init>(MetadataBuilderImpl.java:663)
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:127)
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:654)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at hibernate.Main.main(Main.java:31)
Caused by: java.lang.ClassNotFoundException: net.sf.ehcache.CacheException
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 20 more
</code>```

Can you please help me to fix this or tell me what I did wrong? I am using Hibernate 5.2.5, MySQL DBMS and simple java project in Eclipse IDE. As I already stated I have added "hibernate-ehcache-5.2.5.Final.jar" to my build path and this jar contains org.hibernate.cache.ehcache.EhCacheRegionFactory class. I also tried to use some earlier versions of ehcache jar like "hibernate-ehcache-5.0.2.Final.jar" or "ehcache-3.2.0.jar" but I was getting the same error.

答:
Add to the classpath the ehcache.jar and hibernate-ehcache.jar archives that you find in:

```<code>hibernate-release-5.2.9.Final\lib\optional\ehcache
</code>```

Adding the lastest ehcache.jar from www.ehcache.org will not do the trick.

Body:
I am new to Hibernate and I started learning caching in Hibernate, I want to configure EhCache in my hibernate configuration file. I have added hibernate-ehcache-5.2.5.Final.jar to my build path and here is my hibernate.cfg.xml :

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

<session-factory>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <property name="connection.pool_size">1</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

    <property name="show_sql">true</property>

    <property name="hbm2ddl.auto">update</property>

</session-factory>

</hibernate-configuration>

Here is the main class from where I configure the session factory:

package hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
}

After I run this code I receive the error message:

Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at org.hibernate.cache.internal.StrategyCreatorRegionFactoryImpl.create(StrategyCreatorRegionFactoryImpl.java:38)
at org.hibernate.cache.internal.StrategyCreatorRegionFactoryImpl.create(StrategyCreatorRegionFactoryImpl.java:23)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:198)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:161)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:67)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:28)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.<init>(MetadataBuilderImpl.java:663)
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:127)
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:654)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at hibernate.Main.main(Main.java:31)
Caused by: java.lang.ClassNotFoundException: net.sf.ehcache.CacheException
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 20 more

Can you please help me to fix this or tell me what I did wrong? I am using Hibernate 5.2.5, MySQL DBMS and simple java project in Eclipse IDE. As I already stated I have added "hibernate-ehcache-5.2.5.Final.jar" to my build path and this jar contains org.hibernate.cache.ehcache.EhCacheRegionFactory class. I also tried to use some earlier versions of ehcache jar like "hibernate-ehcache-5.0.2.Final.jar" or "ehcache-3.2.0.jar" but I was getting the same error.

Body:
Add to the classpath the ehcache.jar and hibernate-ehcache.jar archives that you find in:

hibernate-release-5.2.9.Final\lib\optional\ehcache

Adding the lastest ehcache.jar from www.ehcache.org will not do the trick.


问:
J2ME, process a never-ending http connection line by line
I have to write a simple http connection reader in J2ME who has to process a chunked connection line by line.

I tried this:

```<code>  connection = (HttpConnection) Connector.open( url );
  inputStream = connection.openDataInputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int c ;
    while (true) {
        c = inputStream.read();
        if (c == -1)
            break;
        if (c == 10) { // new line \n

            handler( baos.toString() );
            baos = new ByteArrayOutputStream();
        }
        else
            baos.write(c);
    }
</code>```

but it seems to start the entire process only when the server close the connection.

How do i have to manage new incoming lines without have to buffer everything ?

Thank you!

答: It seems to be impossible using HttpConnection, but it works with StreamConnection</p>

Body:
I have to write a simple http connection reader in J2ME who has to process a chunked connection line by line.

I tried this:

  connection = (HttpConnection) Connector.open( url );
  inputStream = connection.openDataInputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int c ;
    while (true) {
        c = inputStream.read();
        if (c == -1)
            break;
        if (c == 10) { // new line \n

            handler( baos.toString() );
            baos = new ByteArrayOutputStream();
        }
        else
            baos.write(c);
    }

but it seems to start the entire process only when the server close the connection.

How do i have to manage new incoming lines without have to buffer everything ?

Thank you!


问:
has_many and belongs_to with join table
I have Users and Trucks. I want the ability to say @truck.drivers << @users and @user.truck = @truck.

The solution is simple until I want the relationship to be stored in a join table.

```<code># tables
:users
  :id

:truck_drivers
  :user_id
  :truck_id

:truck
  :id
</code>```

I've gotten it to where I can say @truck.drivers << @user and @user.trucks << @truck, but I would like to limit a user to occupy one truck at a time, for my sanity.

Is it possible? A has_many/belongs_to with a join table? Or should I try a different approach? I'm not using a third model for the join table. It's just a table. Here's what I have so far.

```<code>class User < ApplicationRecord
  has_and_belongs_to_many :trucks,
    join_table: :truck_drivers, # points to the table
    class_name: :Truck # looks for the truck model in the table
end

class Truck < ApplicationRecord
  belongs_to :company
  has_and_belongs_to_many :drivers,
    join_table: :truck_drivers,
    class_name: :User
end
</code>```

The reason I need a join table in the first place is because each User can have many Roles: Admin, Manager, Driver, Customer Service, etc. I thought it didn't make sense to add a truck_id to all the users if all the users are not going to be using trucks.

答:
It seems like you ought to be able to do something like:</p>

```<code>@user.trucks << @truck unless @user.trucks.any?
</code>```

Title: has_many and belongs_to with join table

Body:
I have Users and Trucks. I want the ability to say @truck.drivers << @users and @user.truck = @truck.

The solution is simple until I want the relationship to be stored in a join table.

# tables
:users
  :id

:truck_drivers
  :user_id
  :truck_id

:truck
  :id

I've gotten it to where I can say @truck.drivers << @user and @user.trucks << @truck, but I would like to limit a user to occupy one truck at a time, for my sanity.

Is it possible? A has_many/belongs_to with a join table? Or should I try a different approach? I'm not using a third model for the join table. It's just a table. Here's what I have so far.

class User < ApplicationRecord
  has_and_belongs_to_many :trucks,
    join_table: :truck_drivers, # points to the table
    class_name: :Truck # looks for the truck model in the table
end

class Truck < ApplicationRecord
  belongs_to :company
  has_and_belongs_to_many :drivers,
    join_table: :truck_drivers,
    class_name: :User
end

The reason I need a join table in the first place is because each User can have many Roles: Admin, Manager, Driver, Customer Service, etc. I thought it didn't make sense to add a truck_id to all the users if all the users are not going to be using trucks.

Body:
It seems like you ought to be able to do something like:

@user.trucks << @truck unless @user.trucks.any?


问:
reverse vowels in string in c
I'm a beginner programmer. I was trying out the problem of reversing vowels in a string.

Ex: input: zabedfigu, output: zubidfega

When I run the following code, I get a runtime error. I've tried to change the conditions within incrementing the pointer pc1 upto only upto the middle index etc., but that either gives me a runtime error or doesn't give me the required output. I'd like some help on what to do to make my code work as well as any new way of solving the problem. TIA.

```<code>#include<stdio.h>

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1!=pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              ++pc2;
              break;
            }
            else
              ++pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s", string);
    return 0;
}
</code>```

答:
The problem here is that you are incrementing both pointers the one in the 0 position, and the one in the end position. The first pointer should increment, and the second one should decrement, thus instead of doing this:

```<code>++pc2;
</code>```

You should do this

```<code>--pc2;
</code>```

Title: reverse vowels in string in c

Body:
I'm a beginner programmer. I was trying out the problem of reversing vowels in a string.

Ex: input: zabedfigu, output: zubidfega

When I run the following code, I get a runtime error. I've tried to change the conditions within incrementing the pointer pc1 upto only upto the middle index etc., but that either gives me a runtime error or doesn't give me the required output. I'd like some help on what to do to make my code work as well as any new way of solving the problem. TIA.

#include<stdio.h>

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1!=pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              ++pc2;
              break;
            }
            else
              ++pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s", string);
    return 0;
}

Body:
The problem here is that you are incrementing both pointers the one in the 0 position, and the one in the end position. The first pointer should increment, and the second one should decrement, thus instead of doing this:

++pc2;

You should do this

--pc2;


问:
compare colums of two table if table1.row > table2.row
TABLE1

```<code>mybb_users
(id gcoins)
 1    150
 2    10
</code>```

TABLE2

```<code>servercoins
(id prezzo)
 1    150
 2    70
</code>```

I should compare this table for control if users have enough "gcoins" for buy "prezzo". If "gcoins" > "prezzo" it's ok but "gcoins" < "prezzo" print an alert with "You don't have enough gocins for this"

答:
This is a general query that will print out the status:

```<code>SELECT u.id, u.gcoins, s.prezzo,
       CASE WHEN u.gcoins >= s.prezzo THEN 'OK' else 'Not Enough gcoins' END AS Status
  FROM mybb_users u
       INNER JOIN servercoins s ON u.id = s.id
</code>```

If you want a query that just returns the rows that need the alert, then remove the second line, and add a WHERE clause instead:

```<code>SELECT u.id, u.gcoins, s.prezzo
  FROM mybb_users u
       INNER JOIN servercoins s ON u.id = s.id
 WHERE u.gcoins < s.prezzo
</code>```

This gives you a list of those who need to be warned that they don't have enough gcoins.

Body:
TABLE1

mybb_users
(id gcoins)
 1    150
 2    10

TABLE2

servercoins
(id prezzo)
 1    150
 2    70

I should compare this table for control if users have enough "gcoins" for buy "prezzo". If "gcoins" > "prezzo" it's ok but "gcoins" < "prezzo" print an alert with "You don't have enough gocins for this"

Body:
This is a general query that will print out the status:

SELECT u.id, u.gcoins, s.prezzo,
       CASE WHEN u.gcoins >= s.prezzo THEN 'OK' else 'Not Enough gcoins' END AS Status
  FROM mybb_users u
       INNER JOIN servercoins s ON u.id = s.id

If you want a query that just returns the rows that need the alert, then remove the second line, and add a WHERE clause instead:

SELECT u.id, u.gcoins, s.prezzo
  FROM mybb_users u
       INNER JOIN servercoins s ON u.id = s.id
 WHERE u.gcoins < s.prezzo

This gives you a list of those who need to be warned that they don't have enough gcoins.


问:
How to deal with space input comparing word inverse C++
We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made.  Also we are counting sentences with using dots, and the user should end his input with @.

For example:

```<code>hi. how are you doing. @
</code>```

or

```<code>hi bro how are u.
im good. @
</code>```

The problem is my program is only working if the input doesn't contain any spaces.

```<code>hihowareyoudoing. thanksimfinebro @
</code>```

If the input is like that, it's working.
it works

```<code>hihowareyoudoing.
thanksimfinebro. @
</code>```

This 2 column also working

code:
(program shows correct inverse for testing)

```<code>#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
    int wrongCount = 0;
    if (reverseReal.length() != reverseUser.length()) {
        cout << "These strings are not comparable." << endl;
    }
    else {
        for (int i = 0; i < reverseReal.length(); i++) {
            if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
                wrongCount++;
            }
        }
        cout << "Number of mistakes: " << wrongCount << endl;
        if (wrongCount == 0){
            cout << "gj correct reverse" << endl;
        }
    }
}
string getReverse(string sentence) {

    string reverseResult = "";
    for (int i = sentence.length() - 1; i >= 0; i--) {
        reverseResult += sentence.substr(i, 1);
    }
    return reverseResult;
}
int findsnumber(string snumber)
{
    unsigned int sentences = 0, index = 0, length;
    string searchPattern = ".";
    length = snumber.length();
    while (index < length)
    {
        index = snumber.find(searchPattern, index);
        if (index != string::npos)
        {
            index += searchPattern.length();
            sentences++;
        }
    }
    return sentences;
}

// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
    while (sentence.find(".") != string::npos) {
        int dotFinder = 0;
        string sub = "";
        dotFinder = sentence.find(".");
        sub = sentence.substr(0, dotFinder);
        return sub;
    }
    return "";
}

int main() {

    string input = "";
    string result = "";
    string reverseReal = "";
    int i = 1;
    cout << "Welcome to my cancer c++ programme." << endl;
    cout << "Enter the paragraph with @ at the end to end it:" << endl;
    while (cin >> input && input != "@") {
        result += input + " ";
    }
    int sentnumber = findsnumber(result);
    cout << "Number of sentences in the given string " << sentnumber << endl;
    while (result.find(".") != string::npos) {
        string sub = "";
        string subReverse = "";
        string reverse = "";
        string reverseson = "";
        cout << i << "/" << sentnumber << endl;
        sub = getOneSentence(result);
        subReverse = getReverse(sub);
        cout << "reverse of the sub " << subReverse << endl;
        cout << "Sentence " << i << " : " << sub << endl;
        cout << "Enter the reverse of your sentence" << endl;
        while (cin >> reverse && reverse != "@"){
            reverseson += reverse + "";
        }
        Comparison(subReverse, reverseson);
        result = result.substr(result.find(".") + 2, result.length());
        i++;
    }
    cin.ignore();
    cin.get();
}
</code>```

答:
Edited Your Code!</p>

```<code>#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
    int wrongCount = 0;
    if (reverseReal.length() != reverseUser.length()) {
        cout << "These strings are not comparable." << endl;
    }
    else {
        for (int i = 0; i < reverseReal.length(); i++) {
            if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
                wrongCount++;
            }
        }
        cout << "Number of mistakes: " << wrongCount << endl;
        if (wrongCount == 0){
            cout << "gj correct reverse" << endl;
        }
    }
}

string getReverse(string sentence) {

    string reverseResult = "";
    for (int i = sentence.length() - 1; i >= 0; i--) {
        reverseResult += sentence.substr(i, 1);
    }
    return reverseResult;
}

int findsnumber(string snumber)
{
    unsigned int sentences = 0, index = 0, length;
    string searchPattern = ".";
    length = snumber.length();
    while (index < length)
    {
        index = snumber.find(searchPattern, index);
        if (index != string::npos)
        {
            index += searchPattern.length();
            sentences++;
        }
    }
    return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {

    while (sentence.find(".") != string::npos) {
        int dotFinder = 0;
        string sub = "";
        dotFinder = sentence.find(".");
        sub = sentence.substr(0, dotFinder);
        return sub;
    }
    return "";
}

int main() {

    //char input = '\0';
    string input = "";
    string result = "";
    string reverseReal = "";
    int i = 1;
    cout << "Welcome to my cancer c++ programme." << endl;
    cout << "Enter the paragraph with @ at the end to end it:" << endl;
    getline(cin, input,'@');
    result = input;
    int sentnumber = findsnumber(result);
    cin.clear();
    cout << "Number of sentences in the given string " << sentnumber << endl;

    while (result.find(".") != string::npos) {
        string sub = "";
        string subReverse = "";
        string reverse = "";
            string reverseson = "";
        cout << i << "/" << sentnumber << endl;
        sub = getOneSentence(result);
        subReverse = getReverse(sub);
        cout << "reverse of the sub " << subReverse << endl;
        cout << "Sentence " << i << " : " << sub << endl;
        cout << "Enter the reverse of your sentence" << endl;
        cin.clear();
        cin.ignore();
        getline(cin,reverse,'@');
        reverse.erase(reverse.end() - 1, reverse.end());
        reverseson = reverse;
        Comparison(subReverse, reverseson);
        result = result.substr(result.find(".") + 2, result.length());
        i++;
    }
    system("pause");
}
</code>```

Body:
We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made.  Also we are counting sentences with using dots, and the user should end his input with @.

For example:

hi. how are you doing. @

or

hi bro how are u.
im good. @

The problem is my program is only working if the input doesn't contain any spaces.

hihowareyoudoing. thanksimfinebro @

If the input is like that, it's working.
it works

hihowareyoudoing.
thanksimfinebro. @

This 2 column also working

code:
(program shows correct inverse for testing)

#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
    int wrongCount = 0;
    if (reverseReal.length() != reverseUser.length()) {
        cout << "These strings are not comparable." << endl;
    }
    else {
        for (int i = 0; i < reverseReal.length(); i++) {
            if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
                wrongCount++;
            }
        }
        cout << "Number of mistakes: " << wrongCount << endl;
        if (wrongCount == 0){
            cout << "gj correct reverse" << endl;
        }
    }
}
string getReverse(string sentence) {

    string reverseResult = "";
    for (int i = sentence.length() - 1; i >= 0; i--) {
        reverseResult += sentence.substr(i, 1);
    }
    return reverseResult;
}
int findsnumber(string snumber)
{
    unsigned int sentences = 0, index = 0, length;
    string searchPattern = ".";
    length = snumber.length();
    while (index < length)
    {
        index = snumber.find(searchPattern, index);
        if (index != string::npos)
        {
            index += searchPattern.length();
            sentences++;
        }
    }
    return sentences;
}

// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
    while (sentence.find(".") != string::npos) {
        int dotFinder = 0;
        string sub = "";
        dotFinder = sentence.find(".");
        sub = sentence.substr(0, dotFinder);
        return sub;
    }
    return "";
}

int main() {

    string input = "";
    string result = "";
    string reverseReal = "";
    int i = 1;
    cout << "Welcome to my cancer c++ programme." << endl;
    cout << "Enter the paragraph with @ at the end to end it:" << endl;
    while (cin >> input && input != "@") {
        result += input + " ";
    }
    int sentnumber = findsnumber(result);
    cout << "Number of sentences in the given string " << sentnumber << endl;
    while (result.find(".") != string::npos) {
        string sub = "";
        string subReverse = "";
        string reverse = "";
        string reverseson = "";
        cout << i << "/" << sentnumber << endl;
        sub = getOneSentence(result);
        subReverse = getReverse(sub);
        cout << "reverse of the sub " << subReverse << endl;
        cout << "Sentence " << i << " : " << sub << endl;
        cout << "Enter the reverse of your sentence" << endl;
        while (cin >> reverse && reverse != "@"){
            reverseson += reverse + "";
        }
        Comparison(subReverse, reverseson);
        result = result.substr(result.find(".") + 2, result.length());
        i++;
    }
    cin.ignore();
    cin.get();
}

Body:
Edited Your Code!

#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
    int wrongCount = 0;
    if (reverseReal.length() != reverseUser.length()) {
        cout << "These strings are not comparable." << endl;
    }
    else {
        for (int i = 0; i < reverseReal.length(); i++) {
            if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
                wrongCount++;
            }
        }
        cout << "Number of mistakes: " << wrongCount << endl;
        if (wrongCount == 0){
            cout << "gj correct reverse" << endl;
        }
    }
}

string getReverse(string sentence) {

    string reverseResult = "";
    for (int i = sentence.length() - 1; i >= 0; i--) {
        reverseResult += sentence.substr(i, 1);
    }
    return reverseResult;
}

int findsnumber(string snumber)
{
    unsigned int sentences = 0, index = 0, length;
    string searchPattern = ".";
    length = snumber.length();
    while (index < length)
    {
        index = snumber.find(searchPattern, index);
        if (index != string::npos)
        {
            index += searchPattern.length();
            sentences++;
        }
    }
    return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {

    while (sentence.find(".") != string::npos) {
        int dotFinder = 0;
        string sub = "";
        dotFinder = sentence.find(".");
        sub = sentence.substr(0, dotFinder);
        return sub;
    }
    return "";
}

int main() {

    //char input = '\0';
    string input = "";
    string result = "";
    string reverseReal = "";
    int i = 1;
    cout << "Welcome to my cancer c++ programme." << endl;
    cout << "Enter the paragraph with @ at the end to end it:" << endl;
    getline(cin, input,'@');
    result = input;
    int sentnumber = findsnumber(result);
    cin.clear();
    cout << "Number of sentences in the given string " << sentnumber << endl;

    while (result.find(".") != string::npos) {
        string sub = "";
        string subReverse = "";
        string reverse = "";
            string reverseson = "";
        cout << i << "/" << sentnumber << endl;
        sub = getOneSentence(result);
        subReverse = getReverse(sub);
        cout << "reverse of the sub " << subReverse << endl;
        cout << "Sentence " << i << " : " << sub << endl;
        cout << "Enter the reverse of your sentence" << endl;
        cin.clear();
        cin.ignore();
        getline(cin,reverse,'@');
        reverse.erase(reverse.end() - 1, reverse.end());
        reverseson = reverse;
        Comparison(subReverse, reverseson);
        result = result.substr(result.find(".") + 2, result.length());
        i++;
    }
    system("pause");
}


问:
JQuery select2 e.val undefined on change
My select2 on change event does not fire e.val.

code:

```<code>$(".clienteselect").select2({
        width: "200",
        placeholder: "<?php echo $dicescolhecli; ?>",
})
.on("change",function(e){
    console.log(e.val) ;
});
</code>```

HTML

```<code><select class="clienteselect">
    <option></option>
    <option value="1"> Manuel Silva </option>
    <option value="2"> Luis Antonio </option>
    <option value="3"> Jose Rodrigues </option>
</select>
</code>```

e.val always returns undefined. Did I miss something?

答:
e is a reference to the change event you subscribed to, you can use the target (html element) to get your select2 component and find the value :

```<code>$(".clienteselect").select2({
  width: "200",
  placeholder: "Select",
}).on("change",function(e){
  console.log($(e.target).select2("val"));
});
</code>```

hope this helps.

Body:
My select2 on change event does not fire e.val.

code:

$(".clienteselect").select2({
        width: "200",
        placeholder: "<?php echo $dicescolhecli; ?>",
})
.on("change",function(e){
    console.log(e.val) ;
});

HTML

<select class="clienteselect">
    <option></option>
    <option value="1"> Manuel Silva </option>
    <option value="2"> Luis Antonio </option>
    <option value="3"> Jose Rodrigues </option>
</select>

e.val always returns undefined. Did I miss something?

Body:
e is a reference to the change event you subscribed to, you can use the target (html element) to get your select2 component and find the value :

$(".clienteselect").select2({
  width: "200",
  placeholder: "Select",
}).on("change",function(e){
  console.log($(e.target).select2("val"));
});

hope this helps.