问:
Bootstrap: Font-Awesome does not work in subfolder?
I downloaded the Creative Bootstrap theme which has the following folder structure

```<code>css/
img/
js/
less/
vendor/
index.html
</code>```

I have now created a subfolder, copied the index.html in the folder and changed the links from the CSS and JS files by adding a ../. In particular the link for fontawesome on line 18 changed to

```<code><link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</code>```

To my surprise, the font-awesome links are not working anymore:

In addition, I noticed than when I remove the dots ../ and copy the vendor folder in subfolder then the font-awesome icons are working.

There is no 404 error in my network tab when I open index.html from root or form subfolder. Both times it looks like this (why is Font-Awesome never listed? I pressed F5 and the index.html file in the root folder actually displays teh Font-Awesome icons correctly):

Why are the Font-Awesome icons not displayed correctly when the vendor folder is outside the subfolder?

答: ../ is relative to the directory of the current page.  Start your href attribute with / to make it absolute.  Looks like it should just be href='/vendor/font-awesome/css/font-awesome.min.css' to me.  Using an absolute path will make it work with all pages without the need to account for the current directory.

Body:
I downloaded the Creative Bootstrap theme which has the following folder structure

css/
img/
js/
less/
vendor/
index.html

I have now created a subfolder, copied the index.html in the folder and changed the links from the CSS and JS files by adding a ../. In particular the link for fontawesome on line 18 changed to

<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

To my surprise, the font-awesome links are not working anymore:

In addition, I noticed than when I remove the dots ../ and copy the vendor folder in subfolder then the font-awesome icons are working.

There is no 404 error in my network tab when I open index.html from root or form subfolder. Both times it looks like this (why is Font-Awesome never listed? I pressed F5 and the index.html file in the root folder actually displays teh Font-Awesome icons correctly):

Why are the Font-Awesome icons not displayed correctly when the vendor folder is outside the subfolder?


来源: stackexchange

问:
Constraining time with LINQ
I'm having difficulty constraining time in a LINQ statement. I am still pretty new with LINQ. The SQL I want to emulate is something like this:

```<code>SELECT ID, Token, StartTime
FROM Tokens
WHERE Token = '050'
AND StartTime > DATEADD(MI, -30, CURRENT_TIMESTAMP)
</code>```

This SQL statement gets only rows where the time in the StartTime column is less than 30 minutes from the current time. How would I do this with LINQ? So far my best guess is

```<code>DateTime cutoff = DateTime.Now - new TimeSpan(0, 30, 0);
IEnumerable<Tokens> token = dataContext.Tokens.Where(row => row.Token == "050" &&
                                                            row.StartTime > cutoff);
</code>```

But that doesn't seem to be working. Any advise?

答:
```<code>row.Token == '5'
</code>```

This jumps out at me. Watch out for using sql's string literal syntax in C#, as it indicates a char - not a string.

ContentLicense: CC BY-SA 2.5

Title: Constraining time with LINQ

Body:
I'm having difficulty constraining time in a LINQ statement. I am still pretty new with LINQ. The SQL I want to emulate is something like this:

SELECT ID, Token, StartTime
FROM Tokens
WHERE Token = '050'
AND StartTime > DATEADD(MI, -30, CURRENT_TIMESTAMP)

This SQL statement gets only rows where the time in the StartTime column is less than 30 minutes from the current time. How would I do this with LINQ? So far my best guess is

DateTime cutoff = DateTime.Now - new TimeSpan(0, 30, 0);
IEnumerable<Tokens> token = dataContext.Tokens.Where(row => row.Token == "050" &&
                                                            row.StartTime > cutoff);

But that doesn't seem to be working. Any advise?

Body:
row.Token == '5'

This jumps out at me. Watch out for using sql's string literal syntax in C#, as it indicates a char - not a string.


问:
Trouble with adding multiple values into array
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

```<code>function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}
</code>```

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.

答:
There are multiple points here:

the function multiply() is not returning the return from list.forEach(). Add the return keyword before list.forEach(function (element){

forEach returns undefined.

Return value

undefined

  1

To return the result from each iteration, use map() or manually add each return value to the array.

See the changes in the snippet below.

To learn more about map() and similar functions, try these exercises.

function doThis() {
  var multiplier = 3
  var list = [23, 54, 23, 25, 65]
  var products = multiply(list, multiplier)
  console.log('products: ', products)
}

function multiply(list, multiplier) {
  return list.map(
    function(element) {
      var multi = [element * multiplier]
      return multi
    }
  );
}
document.getElementById('doThis').addEventListener('click', doThis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="doThis">doThis()</button></code>```

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Return_value

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.

Body:
There are multiple points here:

the function multiply() is not returning the return from list.forEach(). Add the return keyword before list.forEach(function (element){

forEach returns undefined.

Return value

undefined

  1

To return the result from each iteration, use map() or manually add each return value to the array.

See the changes in the snippet below.

To learn more about map() and similar functions, try these exercises.

function doThis() {
  var multiplier = 3
  var list = [23, 54, 23, 25, 65]
  var products = multiply(list, multiplier)
  console.log('products: ', products)
}

function multiply(list, multiplier) {
  return list.map(
    function(element) {
      var multi = [element * multiplier]
      return multi
    }
  );
}
document.getElementById('doThis').addEventListener('click', doThis);

<button id="doThis">doThis()</button>

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Return_value


问:
Celery does not release memory
It looks like celery does not release memory after task finished. Every time a task finishes, there would be 5m-10m memory leak. So with thousands of tasks, soon it will use up all memory.

```<code>BROKER_URL = 'amqp://user@localhost:5672/vhost'
# CELERY_RESULT_BACKEND = 'amqp://user@localhost:5672/vhost'

CELERY_IMPORTS = (
    'tasks.tasks',
)

CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# CELERY_ACKS_LATE = True
CELERY_TASK_RESULT_EXPIRES = 3600
# maximum time for a task to execute
CELERYD_TASK_TIME_LIMIT = 600
CELERY_DEFAULT_ROUTING_KEY = "default"
CELERY_DEFAULT_QUEUE = 'default'
CELERY_DEFAULT_EXCHANGE = "default"
CELERY_DEFAULT_EXCHANGE_TYPE = "direct"
# CELERYD_MAX_TASKS_PER_CHILD = 50
CELERY_DISABLE_RATE_LIMITS = True
CELERYD_CONCURRENCY = 2
</code>```

Might be same with issue, but it does not has an answer:
RabbitMQ/Celery/Django Memory Leak?

I am not using django, and my packages are:

```<code>Chameleon==2.11
Fabric==1.6.0
Mako==0.8.0
MarkupSafe==0.15
MySQL-python==1.2.4
Paste==1.7.5.1
PasteDeploy==1.5.0
SQLAlchemy==0.8.1
WebOb==1.2.3
altgraph==0.10.2
amqp==1.0.11
anyjson==0.3.3
argparse==1.2.1
billiard==2.7.3.28
biplist==0.5
celery==3.0.19
chaussette==0.9
distribute==0.6.34
flower==0.5.1
gevent==0.13.8
greenlet==0.4.1
kombu==2.5.10
macholib==1.5.1
objgraph==1.7.2
paramiko==1.10.1
pycrypto==2.6
pyes==0.20.0
pyramid==1.4.1
python-dateutil==2.1
redis==2.7.6
repoze.lru==0.6
requests==1.2.3
six==1.3.0
tornado==3.1
translationstring==1.1
urllib3==1.6
venusian==1.0a8
wsgiref==0.1.2
zope.deprecation==4.0.2
zope.interface==4.0.5
</code>```

I just added a test task like, test_string is a big string, and it still has memory leak:

```<code>@celery.task(ignore_result=True)
def process_crash_xml(test_string, client_ip, request_timestamp):
    logger.info("%s %s" % (client_ip, request_timestamp))
    test = [test_string] * 5
</code>```

答: set worker_max_tasks_per_child in your settings</p>

Title: Celery does not release memory

Body:
It looks like celery does not release memory after task finished. Every time a task finishes, there would be 5m-10m memory leak. So with thousands of tasks, soon it will use up all memory.

BROKER_URL = 'amqp://user@localhost:5672/vhost'
# CELERY_RESULT_BACKEND = 'amqp://user@localhost:5672/vhost'

CELERY_IMPORTS = (
    'tasks.tasks',
)

CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# CELERY_ACKS_LATE = True
CELERY_TASK_RESULT_EXPIRES = 3600
# maximum time for a task to execute
CELERYD_TASK_TIME_LIMIT = 600
CELERY_DEFAULT_ROUTING_KEY = "default"
CELERY_DEFAULT_QUEUE = 'default'
CELERY_DEFAULT_EXCHANGE = "default"
CELERY_DEFAULT_EXCHANGE_TYPE = "direct"
# CELERYD_MAX_TASKS_PER_CHILD = 50
CELERY_DISABLE_RATE_LIMITS = True
CELERYD_CONCURRENCY = 2

Might be same with issue, but it does not has an answer:
RabbitMQ/Celery/Django Memory Leak?

I am not using django, and my packages are:

Chameleon==2.11
Fabric==1.6.0
Mako==0.8.0
MarkupSafe==0.15
MySQL-python==1.2.4
Paste==1.7.5.1
PasteDeploy==1.5.0
SQLAlchemy==0.8.1
WebOb==1.2.3
altgraph==0.10.2
amqp==1.0.11
anyjson==0.3.3
argparse==1.2.1
billiard==2.7.3.28
biplist==0.5
celery==3.0.19
chaussette==0.9
distribute==0.6.34
flower==0.5.1
gevent==0.13.8
greenlet==0.4.1
kombu==2.5.10
macholib==1.5.1
objgraph==1.7.2
paramiko==1.10.1
pycrypto==2.6
pyes==0.20.0
pyramid==1.4.1
python-dateutil==2.1
redis==2.7.6
repoze.lru==0.6
requests==1.2.3
six==1.3.0
tornado==3.1
translationstring==1.1
urllib3==1.6
venusian==1.0a8
wsgiref==0.1.2
zope.deprecation==4.0.2
zope.interface==4.0.5

I just added a test task like, test_string is a big string, and it still has memory leak:

@celery.task(ignore_result=True)
def process_crash_xml(test_string, client_ip, request_timestamp):
    logger.info("%s %s" % (client_ip, request_timestamp))
    test = [test_string] * 5


问:
SQL Query to transpose rows into columns - revisited
I have a .net web application that uses SQL Server 2008. The data table I am trying to display in a grid contains columns that are actually rows of another table. Right now, I am doing this in the BLL, reading data into data table; getting the data from another table and making it into columns of first data table and then going through each row of data in that data table to populate the new columns. Very time consuming and slow.

I believe this can be done through a query in SQL 2012 and above using "Transpose" or something similar but not sure if it is possible in 2008. I researched and tried using "pivot" but I am not good at SQL and couldn't get it to work.

This is a simplified example of DB tables and what I need to display:

```<code>Facility Table:
FacilityID
12345
67890
99999

PartnerInfo table:
PartnerID    Partner
1            Partner1
2            Partner2
3            Partner3

FacilityPartner table:
FacilityID    PartnerID    Active
12345         1              1
12345         3              0
67890         2              1
67890         3              1
</code>```

Need a query to return something like:

```<code>FacilityID    Partner1    Partner2    Partner3
12345         true        false       true
67890         false       true        true
99999         false       false       false
</code>```

I posted this question here and got a response that seemed to work (query below). However, when I the list of facilities, the query seems to exclude all those that have no partners (e.g. facility id 99999 does not get displayed). I tried playing with the query and changing inner joins to left joins but that didn't help.

```<code>declare  @facility table (facilityId int)
declare  @PartnerInfo  table (partnerid int, partnerN varchar(1000))
declare  @FacilityPartner table (facilityId int,partnerid int)

insert into @facility values (12345)
insert into @facility values (67890)

insert into @PartnerInfo values (1, 'partner1')
insert into @PartnerInfo values (2, 'partner2')
insert into @PartnerInfo values (3, 'partner3')

insert into @FacilityPartner values(12345, 1)
insert into @FacilityPartner values(12345, 3)
insert into @FacilityPartner values(67890, 2)
insert into @FacilityPartner values(67890, 3)

select f.facilityId as facid, p.PartnerN as partn, 100 as val
FROM @facility f
Inner join @FacilityPartner fp on f.facilityId = fp.facilityId
INNER JOIN @PartnerInfo p on p.partnerid = fp.partnerid

select facid, Partner1 , partner2,partner3 FROM

(select f.facilityId as facid, p.PartnerN as partn, 100 as val
FROM @facility f
Inner join @FacilityPartner fp on f.facilityId = fp.facilityId
INNER JOIN @PartnerInfo p on p.partnerid = fp.partnerid) x
PIVOT(
avg(val)
for partn in ([partner1], [partner2],[partner3])
) as pvt
</code>```

答:
Changing inner join to left outer join would work perfectly.

Updated based on OP's comment:

```<code>select facid, isnull(Partner1, 0) p1 , isnull(partner2, 0) p2, isnull(partner3, 0) p3
FROM
(select f.facilityId as facid, p.PartnerN as partn, cast(fp.active as int) as val
FROM @facility f
left outer join @FacilityPartner fp on f.facilityId = fp.facilityId
left outer JOIN @PartnerInfo p on p.partnerid = fp.partnerid) x
PIVOT(
avg(val)
for partn in ([partner1], [partner2],[partner3])
) as pvt
</code>```

Result:

```<code>facid   p1  p2  p3
------------------
12345   1   0   0
67890   0   1   1
99999   0   0   0
</code>```

Body:
I have a .net web application that uses SQL Server 2008. The data table I am trying to display in a grid contains columns that are actually rows of another table. Right now, I am doing this in the BLL, reading data into data table; getting the data from another table and making it into columns of first data table and then going through each row of data in that data table to populate the new columns. Very time consuming and slow.

I believe this can be done through a query in SQL 2012 and above using "Transpose" or something similar but not sure if it is possible in 2008. I researched and tried using "pivot" but I am not good at SQL and couldn't get it to work.

This is a simplified example of DB tables and what I need to display:

Facility Table:
FacilityID
12345
67890
99999

PartnerInfo table:
PartnerID    Partner
1            Partner1
2            Partner2
3            Partner3

FacilityPartner table:
FacilityID    PartnerID    Active
12345         1              1
12345         3              0
67890         2              1
67890         3              1

Need a query to return something like:

FacilityID    Partner1    Partner2    Partner3
12345         true        false       true
67890         false       true        true
99999         false       false       false

I posted this question here and got a response that seemed to work (query below). However, when I the list of facilities, the query seems to exclude all those that have no partners (e.g. facility id 99999 does not get displayed). I tried playing with the query and changing inner joins to left joins but that didn't help.

declare  @facility table (facilityId int)
declare  @PartnerInfo  table (partnerid int, partnerN varchar(1000))
declare  @FacilityPartner table (facilityId int,partnerid int)

insert into @facility values (12345)
insert into @facility values (67890)

insert into @PartnerInfo values (1, 'partner1')
insert into @PartnerInfo values (2, 'partner2')
insert into @PartnerInfo values (3, 'partner3')

insert into @FacilityPartner values(12345, 1)
insert into @FacilityPartner values(12345, 3)
insert into @FacilityPartner values(67890, 2)
insert into @FacilityPartner values(67890, 3)

select f.facilityId as facid, p.PartnerN as partn, 100 as val
FROM @facility f
Inner join @FacilityPartner fp on f.facilityId = fp.facilityId
INNER JOIN @PartnerInfo p on p.partnerid = fp.partnerid

select facid, Partner1 , partner2,partner3 FROM

(select f.facilityId as facid, p.PartnerN as partn, 100 as val
FROM @facility f
Inner join @FacilityPartner fp on f.facilityId = fp.facilityId
INNER JOIN @PartnerInfo p on p.partnerid = fp.partnerid) x
PIVOT(
avg(val)
for partn in ([partner1], [partner2],[partner3])
) as pvt

Body:
Changing inner join to left outer join would work perfectly.

Updated based on OP's comment:

select facid, isnull(Partner1, 0) p1 , isnull(partner2, 0) p2, isnull(partner3, 0) p3
FROM
(select f.facilityId as facid, p.PartnerN as partn, cast(fp.active as int) as val
FROM @facility f
left outer join @FacilityPartner fp on f.facilityId = fp.facilityId
left outer JOIN @PartnerInfo p on p.partnerid = fp.partnerid) x
PIVOT(
avg(val)
for partn in ([partner1], [partner2],[partner3])
) as pvt

Result:

facid   p1  p2  p3
------------------
12345   1   0   0
67890   0   1   1
99999   0   0   0


问:
Run specific code when overloading C++ operators
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator):

```<code>... operator<(A a) { return *this; }
... operator<(B b) { return *this; }
... operator<(C c) { return *this; }
</code>```

A, B, C classes are not related in any way(if that, is of any matter).

Now In my program I only have the 2 following cases:

```<code>A a = new A();
B b = new B();
C c = new C();

(First Case): new Foo() < a < b;
</code>```

or

```<code>(Second Case): new Foo() < a < b < c;
</code>```

Whenever I have the first case (which ends with b), I want to execute a function run() when I have read(I know) the b instance. So the idea is that I would have the following code in the Foo class:

```<code>... operator<(B b)
{
    run();
}
</code>```

Now when I have the code of the first case, run() is being executed.

The problem is that when I have code like in the second case(which ends in c).
I want to execute the run() function again but NOT until I know what c is.
So If I have the previous piece of code run() will be called when doing < b
which is not what I want as I don't know c yet.
If I add run() in operator<(C c) I will call run() twice.

In a few words what I want to accomplish is when having the first case call run() at operator<(B b) and when I have the second case ONLY call run at operator<(C c).

Any ideas on how this can be solved(if it can)?

答:
You have to create a syntax tree before, and than evaluate it. So you are creating a DSL, domain specific language.

read this
http://codeidol.com/cpp/cpp-template-metaprogramming/Domain-Specific-Embedded-Languages/-10.5.-Blitz-and-Expression-Templates/

or you can use the boost::proto

Body:
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator):

... operator<(A a) { return *this; }
... operator<(B b) { return *this; }
... operator<(C c) { return *this; }

A, B, C classes are not related in any way(if that, is of any matter).

Now In my program I only have the 2 following cases:

A a = new A();
B b = new B();
C c = new C();

(First Case): new Foo() < a < b;

or

(Second Case): new Foo() < a < b < c;

Whenever I have the first case (which ends with b), I want to execute a function run() when I have read(I know) the b instance. So the idea is that I would have the following code in the Foo class:

... operator<(B b)
{
    run();
}

Now when I have the code of the first case, run() is being executed.

The problem is that when I have code like in the second case(which ends in c).
I want to execute the run() function again but NOT until I know what c is.
So If I have the previous piece of code run() will be called when doing < b
which is not what I want as I don't know c yet.
If I add run() in operator<(C c) I will call run() twice.

In a few words what I want to accomplish is when having the first case call run() at operator<(B b) and when I have the second case ONLY call run at operator<(C c).

Any ideas on how this can be solved(if it can)?


答:
Using return in a forEach function on an array will not change the values of the original array.

You need to specify where you want to set a value. I suggest using the second parameter in the forEach anonymous function, being the index of the element.

Then you can easily do list[index] = "my new value";

Also, putting the value of the multiplying action between brackets (you did var multi = [element * multiplier];) creates a single-element array for each value.

Here's how I did it to keep a one dimension array:

function doThis() {
    var multiplier = 3
    var list = [23, 54, 23, 25, 65]
    var products = multiply(list, multiplier)
    console.log(products)
}

function multiply(list, multiplier) {
    list.forEach(function(element, index) {
        list[index] = element * multiplier
    });

    return list;
}

doThis();```

Title: Trouble with adding multiple values into array


问:
How to check if a button has this image

I want to check if myButton has a named image.

I try this but it doesn't work

```<code>if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }
</code>```

and this too doesn't work

```<code>if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }
</code>```

答:
Here is what I came up with in Swift 3.0.

```<code>if let myButtonImage = myButton.image(for: .normal),
    let buttonAppuyerImage = UIImage(named: "ButtonAppuyer.png"),
    UIImagePNGRepresentation(myButtonImage) == UIImagePNGRepresentation(buttonAppuyerImage)
{
    print("YES")
} else {
    print("NO")
}
</code>```

This could be cleaned up a lot.

```<code>extension UIButton {
    func hasImage(named imageName: String, for state: UIControlState) -> Bool {
        guard let buttonImage = image(for: state), let namedImage = UIImage(named: imageName) else {
            return false
        }

        return UIImagePNGRepresentation(buttonImage) == UIImagePNGRepresentation(namedImage)
    }
}
</code>```

Then use it

```<code>if myButton.hasImage(named: "ButtonAppuyer.png", for: .normal) {
    print("YES")
} else {
    print("NO")
}
</code>```

Title: How to check if a button has this image

Body:
I want to check if myButton has a named image.

I try this but it doesn't work

if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }

and this too doesn't work

if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }

Body:
Here is what I came up with in Swift 3.0.

if let myButtonImage = myButton.image(for: .normal),
    let buttonAppuyerImage = UIImage(named: "ButtonAppuyer.png"),
    UIImagePNGRepresentation(myButtonImage) == UIImagePNGRepresentation(buttonAppuyerImage)
{
    print("YES")
} else {
    print("NO")
}

This could be cleaned up a lot.

extension UIButton {
    func hasImage(named imageName: String, for state: UIControlState) -> Bool {
        guard let buttonImage = image(for: state), let namedImage = UIImage(named: imageName) else {
            return false
        }

        return UIImagePNGRepresentation(buttonImage) == UIImagePNGRepresentation(namedImage)
    }
}

Then use it

if myButton.hasImage(named: "ButtonAppuyer.png", for: .normal) {
    print("YES")
} else {
    print("NO")
}


问:
How to limit class animations to clicked elements and their content
I know this question has been asked and answered, but here is a slightly more complicated situation. I have a list of cards, all set to animate once clicked. Of course the animation is created by using the toggleClass() command and the initial problem was that if i Clicked one card, all of them animated. This was easily fixed by using the $(this) statement. However, I then decided to add content to the cards, that would display only once the card is clicked. I thought this would be affected by the $(this) statement too, but it is not and now when I click a card, that card animates but the content of other cards is displayed too.

$(".card").click(function() {
  $(this).toggleClass("transform-active");
  $(".disappear").toggleClass("appear");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* CARDS SECTION */

.cards {
  display: block;
  position: absolute;
  width: 100%;
  top: 60px;
  list-style: none;
  text-decoration: none;
  z-index: -1;
}

.cards li {
  display: block;
  position: relative;
  width: 100%;
  padding-bottom: 10px;
}

.card {
  position: relative;
  background-color: #ffffff;
  height: 150px;
  width: 100%;
  left: -5%;
  border-radius: 8px;
  box-shadow: 2px 2px 2px #686868;
  cursor: pointer;
}

/* CARDS CONTENT SECTION */

#containText {
  position: absolute;
  width: 76%;
  color: #58a7dd;
  top: -2px;
  left: 90px;
  text-align: justify;
}

#containText p {
  position: absolute;
  top: 30px;
}

.face {
  position: relative;
  height: 70px;
  width: 70px;
  top: 10px;
  left: 10px;
  border: solid #58a7dd;
  background-color: white;
  border-radius: 50%;
  color: #58a7dd;
}

.face h2 {
  position: relative;
  left: 3px;
  top: 20px;
  transform: rotate(90deg);
}

.extra {
  position: relative;
  width: 90%;
  top: 7px;
  margin: auto;
  color: #2f4f4f;
}

.disappear {
  position: relative;
  width: 90%;
  height: 40%;
  top: 5px;
  margin: auto;
  color: #2f4f4f;
  opacity: 0;
}

.appear {
  animation: appear 1.2s ease;
  animation-fill-mode: forwards;
}

@keyframes appear {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.transform {
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -o-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

.transform-active {
  background-color: #ffffff;
  height: 300px;
  width: 100%;
  box-shadow: 6px 6px 6px #888888;
}</code>```

: )

HI! I am a card.

Click me to trigger the animation.

Here is some extra info about the items on this card, such as stuff, things and blah.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

TWO

THREE

FOUR

FIVE

SIX

```

CodePen with working example: https://codepen.io/BGGrieco/pen/PjOevR

答:
Try changing your JS to the following:

```<code>$(".card").click(function()
{
  $(this).toggleClass("transform-active");
  $(".disappear", this).toggleClass("appear");
});
</code>```

Your problem was that you were toggling the 'appear' class of ALL elements with the class 'disappear', which covers the content of all the cards, including those that are not active.

Adding , this to the select statement of jQuery will limit the context of 'disappear' to the scope of this. (See http://api.jquery.com/jquery/#jQuery1)

Here is the modified CodePen: https://codepen.io/williamli/pen/LLBPOv

$(".card").click(function()
{
  $(this).toggleClass("transform-active");
  $(".disappear", this).toggleClass("appear");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body
{
  position: relative;
  background-color: #f9f9f9;
  font-family: "arial";
  margin: 0;
  padding: 0;
}

.header p
{
  text-align: center;
  font-weight: lighter;
  font-size: 20px;
  line-height: 12px;
  color: white;
}

/* APP BARS SECTION */
.header
{
  position: fixed;
  top: 0%;
  width: 100%;
  height: 50px;
  background-color: #d36363;
  box-shadow: 0px 6px 6px #888888;
  z-index: +1;
}

.footer
{
  position: fixed;
  bottom: 0%;
  width: 100%;
  height: 50px;
  background-color: #d36363;
  box-shadow: 0px -6px 6px #888888;
}

/* CARDS SECTION */
.cards
{
  display: block;
  position: absolute;
  width: 100%;
  top: 60px;
  list-style: none;
  text-decoration: none;
  z-index: -1;
}

.cards li
{
  display: block;
  position: relative;
  width: 100%;
  padding-bottom: 10px;
}

.card
{
  position: relative;
  background-color: #ffffff;
  height: 150px;
  width: 100%;
  left: -5%;
  border-radius: 8px;
  box-shadow: 2px 2px 2px #686868;
  cursor: pointer;
}

/* CARDS CONTENT SECTION */
#containText
{
  position: absolute;
  width: 76%;
  color: #58a7dd;
  top: -2px;
  left: 90px;
  text-align: justify;
}

#containText p
{
  position: absolute;
  top: 30px;
}

.face
{
  position: relative;
  height: 70px;
  width: 70px;
  top: 10px;
  left: 10px;
  border: solid #58a7dd;
  background-color: white;
  border-radius: 50%;
  color: #58a7dd;
}

.face h2
{
  position: relative;
  left: 3px;
  top: 20px;
  transform: rotate(90deg);
}

.extra
{
  position: relative;
  width: 90%;
  top: 7px;
  margin: auto;
  color: #2f4f4f;
}

.disappear
{
  position: relative;
  width: 90%;
  height: 40%;
  top: 5px;
  margin: auto;
  color: #2f4f4f;
  opacity: 0;
}

.appear
{
  animation: appear 1.2s ease;
  animation-fill-mode: forwards;
}

@keyframes appear
{
  0%
  {
    opacity: 0;
  }
  100%
  {
    opacity: 1;
  }
}

.transform
{
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -o-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

.transform-active
{
  background-color: #ffffff;
  height: 300px;
  width: 100%;
  box-shadow: 6px 6px 6px #888888;
}</code>```

    <meta charset="UTF-8">
    <link rel="stylesheet" href="styling.css" type="text/css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Current Page

: )

HI! I am a card.

Click me to trigger the animation.

Here is some extra info about the items on this card, such as stuff,                    things and blah.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim                    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea                commodo consequat.

TWO

Here is some extra info about the items on this card, such as stuff,                    things and blah.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim                    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea                commodo consequat.

THREE

FOUR

FIVE

SIX

  ```

Body:
I know this question has been asked and answered, but here is a slightly more complicated situation. I have a list of cards, all set to animate once clicked. Of course the animation is created by using the toggleClass() command and the initial problem was that if i Clicked one card, all of them animated. This was easily fixed by using the $(this) statement. However, I then decided to add content to the cards, that would display only once the card is clicked. I thought this would be affected by the $(this) statement too, but it is not and now when I click a card, that card animates but the content of other cards is displayed too.

$(".card").click(function() {
  $(this).toggleClass("transform-active");
  $(".disappear").toggleClass("appear");
});

/* CARDS SECTION */

.cards {
  display: block;
  position: absolute;
  width: 100%;
  top: 60px;
  list-style: none;
  text-decoration: none;
  z-index: -1;
}

.cards li {
  display: block;
  position: relative;
  width: 100%;
  padding-bottom: 10px;
}

.card {
  position: relative;
  background-color: #ffffff;
  height: 150px;
  width: 100%;
  left: -5%;
  border-radius: 8px;
  box-shadow: 2px 2px 2px #686868;
  cursor: pointer;
}

/* CARDS CONTENT SECTION */

#containText {
  position: absolute;
  width: 76%;
  color: #58a7dd;
  top: -2px;
  left: 90px;
  text-align: justify;
}

#containText p {
  position: absolute;
  top: 30px;
}

.face {
  position: relative;
  height: 70px;
  width: 70px;
  top: 10px;
  left: 10px;
  border: solid #58a7dd;
  background-color: white;
  border-radius: 50%;
  color: #58a7dd;
}

.face h2 {
  position: relative;
  left: 3px;
  top: 20px;
  transform: rotate(90deg);
}

.extra {
  position: relative;
  width: 90%;
  top: 7px;
  margin: auto;
  color: #2f4f4f;
}

.disappear {
  position: relative;
  width: 90%;
  height: 40%;
  top: 5px;
  margin: auto;
  color: #2f4f4f;
  opacity: 0;
}

.appear {
  animation: appear 1.2s ease;
  animation-fill-mode: forwards;
}

@keyframes appear {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.transform {
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -o-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

.transform-active {
  background-color: #ffffff;
  height: 300px;
  width: 100%;
  box-shadow: 6px 6px 6px #888888;
}

: )

HI! I am a card.

Click me to trigger the animation.

Here is some extra info about the items on this card, such as stuff, things and blah.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

TWO

THREE

FOUR

FIVE

SIX

CodePen with working example: https://codepen.io/BGGrieco/pen/PjOevR

Body:
Try changing your JS to the following:

$(".card").click(function()
{
  $(this).toggleClass("transform-active");
  $(".disappear", this).toggleClass("appear");
});

Your problem was that you were toggling the 'appear' class of ALL elements with the class 'disappear', which covers the content of all the cards, including those that are not active.

Adding , this to the select statement of jQuery will limit the context of 'disappear' to the scope of this. (See http://api.jquery.com/jquery/#jQuery1)

Here is the modified CodePen: https://codepen.io/williamli/pen/LLBPOv

$(".card").click(function()
{
  $(this).toggleClass("transform-active");
  $(".disappear", this).toggleClass("appear");
});

body
{
  position: relative;
  background-color: #f9f9f9;
  font-family: "arial";
  margin: 0;
  padding: 0;
}

.header p
{
  text-align: center;
  font-weight: lighter;
  font-size: 20px;
  line-height: 12px;
  color: white;
}

/* APP BARS SECTION */
.header
{
  position: fixed;
  top: 0%;
  width: 100%;
  height: 50px;
  background-color: #d36363;
  box-shadow: 0px 6px 6px #888888;
  z-index: +1;
}

.footer
{
  position: fixed;
  bottom: 0%;
  width: 100%;
  height: 50px;
  background-color: #d36363;
  box-shadow: 0px -6px 6px #888888;
}

/* CARDS SECTION */
.cards
{
  display: block;
  position: absolute;
  width: 100%;
  top: 60px;
  list-style: none;
  text-decoration: none;
  z-index: -1;
}

.cards li
{
  display: block;
  position: relative;
  width: 100%;
  padding-bottom: 10px;
}

.card
{
  position: relative;
  background-color: #ffffff;
  height: 150px;
  width: 100%;
  left: -5%;
  border-radius: 8px;
  box-shadow: 2px 2px 2px #686868;
  cursor: pointer;
}

/* CARDS CONTENT SECTION */
#containText
{
  position: absolute;
  width: 76%;
  color: #58a7dd;
  top: -2px;
  left: 90px;
  text-align: justify;
}

#containText p
{
  position: absolute;
  top: 30px;
}

.face
{
  position: relative;
  height: 70px;
  width: 70px;
  top: 10px;
  left: 10px;
  border: solid #58a7dd;
  background-color: white;
  border-radius: 50%;
  color: #58a7dd;
}

.face h2
{
  position: relative;
  left: 3px;
  top: 20px;
  transform: rotate(90deg);
}

.extra
{
  position: relative;
  width: 90%;
  top: 7px;
  margin: auto;
  color: #2f4f4f;
}

.disappear
{
  position: relative;
  width: 90%;
  height: 40%;
  top: 5px;
  margin: auto;
  color: #2f4f4f;
  opacity: 0;
}

.appear
{
  animation: appear 1.2s ease;
  animation-fill-mode: forwards;
}

@keyframes appear
{
  0%
  {
    opacity: 0;
  }
  100%
  {
    opacity: 1;
  }
}

.transform
{
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -o-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

.transform-active
{
  background-color: #ffffff;
  height: 300px;
  width: 100%;
  box-shadow: 6px 6px 6px #888888;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="styling.css" type="text/css">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <!--HEADER-->
    <div class="header">
      <div id="info">
        <p>Current Page</p>
      </div>
    </div>

    <!--CARDS-->
    <ul id="cardList" class="cards">
      <li><div class="card transform">
        <div class="face"><h2>: )</h2></div>
          <div id="containText">
            <h3>HI! I am a card.</h3><br>
            <p>Click me to trigger the animation.</p>
          </div>
          <div class="extra">
            <p>Here is some extra info about the items on this card, such as stuff,                    things and blah.</p>
          </div>
          <div class="disappear">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim                    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea                commodo consequat.</p>
          </div>
          </div>
      </li>
      <li><div class="card transform">TWO
        <div class="extra">
            <p>Here is some extra info about the items on this card, such as stuff,                    things and blah.</p>
          </div>
          <div class="disappear">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim                    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea                commodo consequat.</p>
          </div>
        </div></li>
      <li><div class="card transform">THREE</div></li>
      <li><div class="card transform">FOUR</div></li>
      <li><div class="card transform">FIVE</div></li>
      <li><div class="card transform">SIX</div></li>
    </ul>

    <!--FOOTER-->
    <div class="footer"></div>
  </body>


问:
How to select, trim, and store as range a word that contains the insertion point in an open Word document using the Office Add-in JavaScript API
I apologize if the answer to this basic question is obvious. I have looked everywhere and not been able to find an answer.

Say the insertion point is currently between two letters of a word in an open Word Document.  How would I assign the word (without trailing space) to a range variable using the Word Add-in JavaScript API?

For context, I am trying to make it so that the user can single click any word in the document, which would put the insertion point inside the word, and then click a UI control that executes a particular Find & Replace on that word everywhere in the document.

答:
You need to use the getTextRanges() method of the range to solve this. The semantic of this method is that takes the delimiters specified on the first parameter, then we go from the current insertion point both fwd and bwd until we find any of the specified delimiters and return the resulting range. Not that end of paragraph is an implicit delimiter, so this cannot go beyond a paragraph. What this means is that if the user is selecting the last word of the paragraph, that range will include a ".", so you want to make sure you validate the last characters, same is true for any other punctuation characters. Second parameter is to trim or not spaces (in my example set to true).

Here is an example of how to use it using the space (" ") as delimiter.

    Word.run(function (context) {
        var myWordRange = context.document.getSelection().getTextRanges([" "], true).getFirst();
        context.load(myWordRange);
        return context.sync()
            .then(function () {
                console.log(myWordRange.text);
             })
    })```

Have fun..
juan.

Body:
You need to use the getTextRanges() method of the range to solve this. The semantic of this method is that takes the delimiters specified on the first parameter, then we go from the current insertion point both fwd and bwd until we find any of the specified delimiters and return the resulting range. Not that end of paragraph is an implicit delimiter, so this cannot go beyond a paragraph. What this means is that if the user is selecting the last word of the paragraph, that range will include a ".", so you want to make sure you validate the last characters, same is true for any other punctuation characters. Second parameter is to trim or not spaces (in my example set to true).

Here is an example of how to use it using the space (" ") as delimiter.

    Word.run(function (context) {
        var myWordRange = context.document.getSelection().getTextRanges([" "], true).getFirst();
        context.load(myWordRange);
        return context.sync()
            .then(function () {
                console.log(myWordRange.text);
             })
    })

Have fun..
juan.


问:
Wamp Server not starting in Windows 10 64-bit
I was writing some PHP code for my web application recently. I was trying to test sending an e-mail from a contact form on a local server (by using a variety of methods, including SendMail). None of them worked (though it may be code-related but I don't know yet). I basically restarted Apache/MySQL several times throughout testing. At one point when I was changing the configurations for SendMail, I was unable to re-start Apache & MySQL after stopping them. The icon remained red. Every time I try to start Apache, nothing would happen and the icon still remains red. I tried doing it manually from Services but it's giving me an error. It has always worked in the past, so I am not sure what's happening now or whether or not changing some of the SMTP configurations on php.ini or sendmail.ini and installing these mail server tools messed something up?

Anyone have any suggestions on how to fix/troubleshoot this? I am pretty new to server-side development. I appreciate the help!

答:
It could be a hundred different things, do what welshGaz said and check your logs.  If you're still stuck after that, you have the following options:

Uninstall/Reinstall WAMP

Try an alternative to WAMP such as XAMPP

Spin up a virtual environment using virtual box and ubuntu

Spin up a server on Amazon Web Services, Heroku, etc.

These are options are of the last-resort variety, but if you're in a pinch and don't have time to troubleshoot, one of these options might be a faster way to get back up and running.


问:
Return Content with alert in Controller
I'm trying to somewhat replicate what I saw in this question, particularly in this answer, but not quite the same.
My intent is, if the zip has no files (it can happen because the folder could be empty) I want to return an alert just so the user is warned that is not possible to obtain the file at the time.
But I'm missing on the redirection point, I don't want the alert to redirect the user to a blank page refering the Action, I want it to stay in the page, also due to some filters.
Is this possible? I couldn't find anything that would stop the redirection from happening.

Here is my the Action Controller code:

```<code>public ActionResult DownloadZip(List<int> things)
    {
        // Create zip with files

        if (!zip.Any())
        {
            return Content(@"<script language='javascript' type='text/javascript'>
                     alert('Message');
                     </script>
                  ");
        }

        // Return zip
    }
</code>```

Here is the call from the view:

```<code>$("#btnExportToZip").on("click", function (e) {

    var grid = $("#gridThings").data("kendoGrid");
    var items = grid.dataSource.data();
    var lstIds = [];
    $.each(items, function (index, elem) {
        if (elem.Checked) {
            lstIds.push(elem.Id);
        }
    });

    if (lstIds.length > 0) {
        var params = lstIds.join("&listAmostras=")
        var url = '/Search/DownloadZip?listAmostras=' + params;

        window.location.href = url;
    }
});
</code>```

答:
If you do a redirect as you're doing here, it's too late to take it back once you've determined the zip file is empty. Your best bet here is probably to do an AJAX file download. Bear in mind, though, that this will require that the browser supports the HTML5 File API, so IE 9 and under are out.

```<code>$.ajax({
    url: url,
    async: false,
    xhrFields: {
        responseType: 'blob'
    },
    success: function (data) {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(data);
        a.href = url;
        a.download = 'myfile.pdf';
        a.click();
        window.URL.revokeObjectURL(url);
    }
});
</code>```

Essentially what this does is request the zip file via AJAX. Once the file data has been received, an anchor link is added to the DOM (not visible) and dynamically "clicked" to approximate the behavior of user click a link to a static file. In other words, a download prompt will pop as soon as the AJAX request completes successfully. However, this code only removes the need to redirect. You still need to conditionally pop the download only if the zip file has something in. There's two ways you can accomplish that.

In the success callback of the AJAX, you would wrap the code there in a conditional that checks that data.size > 0. However, that might not actually work. I've never looked at an empty zip file, but it's entirely possible that there's file headers in the binary that would cause the blob to actually have a size greater than zero, even though it's "empty".

The better approach is to return an error response in your zip action when the zip file is empty. Off the top of my head, I'm not sure what the most appropriate error response code would be, but anything in 400-500 range will work for triggering the appropriate AJAX callback. Then, you just need to add and error handler to this AJAX. In that handler, you could then notify the user however you like that there's no download because the zip would be empty.

Title: Return Content with alert in Controller

Body:
I'm trying to somewhat replicate what I saw in this question, particularly in this answer, but not quite the same.
My intent is, if the zip has no files (it can happen because the folder could be empty) I want to return an alert just so the user is warned that is not possible to obtain the file at the time.
But I'm missing on the redirection point, I don't want the alert to redirect the user to a blank page refering the Action, I want it to stay in the page, also due to some filters.
Is this possible? I couldn't find anything that would stop the redirection from happening.

Here is my the Action Controller code:

public ActionResult DownloadZip(List<int> things)
    {
        // Create zip with files

        if (!zip.Any())
        {
            return Content(@"
                  ");
        }

        // Return zip
    }

Here is the call from the view:

$("#btnExportToZip").on("click", function (e) {

    var grid = $("#gridThings").data("kendoGrid");
    var items = grid.dataSource.data();
    var lstIds = [];
    $.each(items, function (index, elem) {
        if (elem.Checked) {
            lstIds.push(elem.Id);
        }
    });

    if (lstIds.length > 0) {
        var params = lstIds.join("&listAmostras=")
        var url = '/Search/DownloadZip?listAmostras=' + params;

        window.location.href = url;
    }
});

Body:
If you do a redirect as you're doing here, it's too late to take it back once you've determined the zip file is empty. Your best bet here is probably to do an AJAX file download. Bear in mind, though, that this will require that the browser supports the HTML5 File API, so IE 9 and under are out.

$.ajax({
    url: url,
    async: false,
    xhrFields: {
        responseType: 'blob'
    },
    success: function (data) {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(data);
        a.href = url;
        a.download = 'myfile.pdf';
        a.click();
        window.URL.revokeObjectURL(url);
    }
});

Essentially what this does is request the zip file via AJAX. Once the file data has been received, an anchor link is added to the DOM (not visible) and dynamically "clicked" to approximate the behavior of user click a link to a static file. In other words, a download prompt will pop as soon as the AJAX request completes successfully. However, this code only removes the need to redirect. You still need to conditionally pop the download only if the zip file has something in. There's two ways you can accomplish that.

In the success callback of the AJAX, you would wrap the code there in a conditional that checks that data.size > 0. However, that might not actually work. I've never looked at an empty zip file, but it's entirely possible that there's file headers in the binary that would cause the blob to actually have a size greater than zero, even though it's "empty".

The better approach is to return an error response in your zip action when the zip file is empty. Off the top of my head, I'm not sure what the most appropriate error response code would be, but anything in 400-500 range will work for triggering the appropriate AJAX callback. Then, you just need to add and error handler to this AJAX. In that handler, you could then notify the user however you like that there's no download because the zip would be empty.


问:
insert in url paratmeters using javascript
i have a url something like:

```<code>http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=abc123
</code>```

or

```<code>http://somewhere.com/dir/?parameter1=123123&parameter2=abcabc&parameter3=abc123
</code>```

and some variables including:

```<code>var alpha = aaa;
var num = 111;
var alphanum= aaa123;
</code>```

i want to add these variables by by one into url every url parameters using javascript (or jQuery) , so that i have:

```<code>http://somewhere.com/dir/parameter1=aaa&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=111&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=aaa123&parameter2=abcabc&parameter3=abc123
</code>```

and for next parameter:

```<code>http://somewhere.com/dir/parameter1=123123&parameter2=aaa&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=111&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=aaa123&parameter3=abc123
</code>```

and the last one

```<code>http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=111
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa123
</code>```

how can i do it ?
thanks.

答:
Here you go:

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button to encode a URI.</p>

<button onclick="clickHandler()">Try it</button>

<p id="demo"></p>
<script>
function clickHandler() {
     var url = "http://somewhere.com/dir/?";
     var alpha = "aaa";
     var num = 111;
     var alphanum= "aaa123";
     var params = {
       alpha,
       num,
       alphanum
     }
     var amp = '';
     for (var key in params) {
       if (!params.hasOwnProperty(key)) continue;
       var value = params[key];
         url += amp;
         url += encodeURI(key);
         url += '='
         url += encodeURI(value);
         amp = '&';
    }
    document.getElementById("demo").innerHTML = url;
}
</script>
</body>
</html>
</code>```

To see it working click here.

Body:
i have a url something like:

http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=abc123

or

http://somewhere.com/dir/?parameter1=123123&parameter2=abcabc&parameter3=abc123

and some variables including:

var alpha = aaa;
var num = 111;
var alphanum= aaa123;

i want to add these variables by by one into url every url parameters using javascript (or jQuery) , so that i have:

http://somewhere.com/dir/parameter1=aaa&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=111&parameter2=abcabc&parameter3=abc123
http://somewhere.com/dir/parameter1=aaa123&parameter2=abcabc&parameter3=abc123

and for next parameter:

http://somewhere.com/dir/parameter1=123123&parameter2=aaa&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=111&parameter3=abc123
http://somewhere.com/dir/parameter1=123123&parameter2=aaa123&parameter3=abc123

and the last one

http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=111
http://somewhere.com/dir/parameter1=123123&parameter2=abcabc&parameter3=aaa123

how can i do it ?
thanks.

Body:
Here you go:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to encode a URI.</p>

<button onclick="clickHandler()">Try it</button>

<p id="demo"></p>
<script>
function clickHandler() {
     var url = "http://somewhere.com/dir/?";
     var alpha = "aaa";
     var num = 111;
     var alphanum= "aaa123";
     var params = {
       alpha,
       num,
       alphanum
     }
     var amp = '';
     for (var key in params) {
       if (!params.hasOwnProperty(key)) continue;
       var value = params[key];
         url += amp;
         url += encodeURI(key);
         url += '='
         url += encodeURI(value);
         amp = '&';
    }
    document.getElementById("demo").innerHTML = url;
}
</script>
</body>
</html>

To see it working click here.


问:
What return ostream::write?
Cplusplus say "The ostream object (* this)" but I do not understand. Return ostream object's pointer? I have try print this value with cout function but I print always 0. And how can this value be useful?</p>

答:
```<code>this
</code>```

is a pointer to the current object invoked.

```<code>*this
</code>```

dereferences the pointer.

This is often used for "chaining".
For instance:

```<code>cout<<1<<2<<3<<4<<5;
</code>```

operator<< is invoked in cout:
    cout<<1
will print 1 and return cout, then we'll have:

```<code>cout<<2<<3<<4<<5;
</code>```

and so on.

Title: What return ostream::write?

Body:
this

is a pointer to the current object invoked.

*this

dereferences the pointer.

This is often used for "chaining".
For instance:

cout<<1<<2<<3<<4<<5;

operator<< is invoked in cout:
    cout<<1
will print 1 and return cout, then we'll have:

cout<<2<<3<<4<<5;

and so on.


问:
HTML string to formatted text in Swift
Hello I have a string that I want to write to a text document in Swift. Because the text document has line breaks, however, the string seems to be in HTML format.
Here is what I want to do:</p>

```<code>    //Covert str1 to str2
    var str1 = "1<div>2</div><div>3</div><div>4</div>"
    var str2 = "1
                2
                3
                4" //Text document will have text that looks like this (With line breaks)
</code>```

答:
Swift 3.0: You can pop this directly into Xcode's playground to check it out.</p>

```<code>let htmlString = "1<div>2</div><div>3</div><div>4</div>"
func getHtmlFormat(fromString htmlString: String) -> NSAttributedString? {
    guard let htmlData = htmlString.data(using: String.Encoding.unicode) else
    {
        print("Could not get htmlData")
        return nil
    }
    do {
        return try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let error {
        print(error)
        return nil
    }
}

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
textView.attributedText = getHtmlFormat(fromString: htmlString)
</code>```

Title: HTML string to formatted text in Swift

Body:
Hello I have a string that I want to write to a text document in Swift. Because the text document has line breaks, however, the string seems to be in HTML format.
Here is what I want to do:

    //Covert str1 to str2
    var str1 = "1
2

3

4
"
    var str2 = "1
                2
                3
                4" //Text document will have text that looks like this (With line breaks)

Body:
Swift 3.0: You can pop this directly into Xcode's playground to check it out.

let htmlString = "1<div>2</div><div>3</div><div>4</div>"
func getHtmlFormat(fromString htmlString: String) -> NSAttributedString? {
    guard let htmlData = htmlString.data(using: String.Encoding.unicode) else
    {
        print("Could not get htmlData")
        return nil
    }
    do {
        return try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let error {
        print(error)
        return nil
    }
}

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
textView.attributedText = getHtmlFormat(fromString: htmlString)


问:
invalid operands of types 'const char [26]' and 'LPSTR '
My code is

```<code>string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );
</code>```

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

答:
If you consider the second parameter of MessageBox in this line of code:

```<code>MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

You can see a string literal, i.e. "The selected folder is : ", which is a NUL-terminated C-style raw char array (the const char [26] part in your error message); and you are trying to "concatenate" it using the operator + with lp, which you defined as LPSTR (i.e. char*) in your code.

Such operation is not defined, hence the error message.

It's clear that your intent is to concatenate two strings, and print the resulting string calling the MessageBox API.

To do so, consider using a C++ string class. If you are at the Win32 API boundary, I think ATL/MFC CString is very convenient. Or, you can use a standard string class like std::string.

std::string (and CString as well...) conveniently defines proper overloads of operator+(), which make it possible to concatenate strings with a simple syntax, e.g.:

```<code>string str = "C:\\Users\\mardare\\Downloads\\config";
string message = "The selected folder is : " + str;
</code>```

At this point, if you want to pass your message std::string instance to the MessageBox API (which is a C-interface API), you can call the std::string::c_str() method:

```<code>MessageBox( NULL, message.c_str(), /* ... other params ... */ );
</code>```

Note that this code will compile in ANSI/MBCS builds (which is an obsolete build setting; Unicode build has been the default since VS2005, more than 10 years ago).

In your case, the actual Win32 API that gets called is MessageBoxA (note the A suffix).

Your code will fail to compile in VS solutions that use Unicode builds; in those cases, you may want to use the explicit MessageBoxA() call.

EDIT Not directly related to your error message, but might be interesting for you to know: If you are using a recent Visual C++ compiler, you may want to replace NULL with nullptr in your C++ code, and you can use raw string literals to simplify the way you write your paths, like this:

```<code>// Was: string str = "C:\\Users\\mardare\\Downloads\\config";
string str = R"(C:\Users\mardare\Downloads\config)";
</code>```

Body:
My code is

string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

Body:
If you consider the second parameter of MessageBox in this line of code:

MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can see a string literal, i.e. "The selected folder is : ", which is a NUL-terminated C-style raw char array (the const char [26] part in your error message); and you are trying to "concatenate" it using the operator + with lp, which you defined as LPSTR (i.e. char*) in your code.

Such operation is not defined, hence the error message.

It's clear that your intent is to concatenate two strings, and print the resulting string calling the MessageBox API.

To do so, consider using a C++ string class. If you are at the Win32 API boundary, I think ATL/MFC CString is very convenient. Or, you can use a standard string class like std::string.

std::string (and CString as well...) conveniently defines proper overloads of operator+(), which make it possible to concatenate strings with a simple syntax, e.g.:

string str = "C:\\Users\\mardare\\Downloads\\config";
string message = "The selected folder is : " + str;

At this point, if you want to pass your message std::string instance to the MessageBox API (which is a C-interface API), you can call the std::string::c_str() method:

MessageBox( NULL, message.c_str(), /* ... other params ... */ );

Note that this code will compile in ANSI/MBCS builds (which is an obsolete build setting; Unicode build has been the default since VS2005, more than 10 years ago).

In your case, the actual Win32 API that gets called is MessageBoxA (note the A suffix).

Your code will fail to compile in VS solutions that use Unicode builds; in those cases, you may want to use the explicit MessageBoxA() call.

EDIT Not directly related to your error message, but might be interesting for you to know: If you are using a recent Visual C++ compiler, you may want to replace NULL with nullptr in your C++ code, and you can use raw string literals to simplify the way you write your paths, like this:

// Was: string str = "C:\\Users\\mardare\\Downloads\\config";
string str = R"(C:\Users\mardare\Downloads\config)";


问:
Using wildcards in HAVING
Im trying to get a list of all the countries that have atleast 2 customers with yahoo email.

So far I came up with this:

```<code>SELECT Country
FROM Customer
GROUP BY Country
HAVING COUNT(Email LIKE '%yahoo%')>= 2
</code>```

This doesnt work though. Probably because I cant use LIKE in HAVING clause. I tried to use it in where clause, but I cant use aggregate functions there. Do you know how to make this work? Assume standard sql. Thx

答:
use conditional aggregation

```<code>SELECT Country
FROM Customer
GROUP BY Country
HAVING SUM(case when Email like '%yahoo%' then 1 else 0 end )>= 2
</code>```

Or just put the limit in your where clause...  This way the limit is imposed before the count possibly having a performance boost; since it only has to evaluate the emails that are like '%yahoo%' instead or all emails when counting; but since the where clause has to do the evaluation 1st anyway.  I'm not sure which would be faster w/o testing.

```<code>SELECT Country
FROM Customer
WHERE email like '%yahoo%'
GROUP BY Country
HAVING count(Email)>= 2
</code>```

though like %val% is unable to use any index so; maybe not. but if it was like %yahoo.com' you'd see one. (if index is on email)

Title: Using wildcards in HAVING

Body:
Im trying to get a list of all the countries that have atleast 2 customers with yahoo email.

So far I came up with this:

SELECT Country
FROM Customer
GROUP BY Country
HAVING COUNT(Email LIKE '%yahoo%')>= 2

This doesnt work though. Probably because I cant use LIKE in HAVING clause. I tried to use it in where clause, but I cant use aggregate functions there. Do you know how to make this work? Assume standard sql. Thx

Body:
use conditional aggregation

SELECT Country
FROM Customer
GROUP BY Country
HAVING SUM(case when Email like '%yahoo%' then 1 else 0 end )>= 2

Or just put the limit in your where clause...  This way the limit is imposed before the count possibly having a performance boost; since it only has to evaluate the emails that are like '%yahoo%' instead or all emails when counting; but since the where clause has to do the evaluation 1st anyway.  I'm not sure which would be faster w/o testing.

SELECT Country
FROM Customer
WHERE email like '%yahoo%'
GROUP BY Country
HAVING count(Email)>= 2

though like %val% is unable to use any index so; maybe not. but if it was like %yahoo.com' you'd see one. (if index is on email)


问:
How to use local fonts using font-face mixin in vaadin?
I want to use Roboto Condensed font as local, not from web.

Like

```<code>@include font-face('Roboto Condensed', '../../../../../../styles/systemfont/*', 300, 300i, 400, 400i, 700&'subset=cyrillic, cyrillic-ext, latin-ext');
</code>```

But this seems not to work

And I try to avoid to use

```<code>@StyleSheet("https://fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700&subset=cyrillic,cyrillic-ext,latin-ext")
</code>```

in my UI class

答:
This has worked for me. I am packaging my font in Jar like Vaadin is doing with their Valo theme and then I include that as a dependency through pom.xml.

Place font files (ttf etc.) in your theme folder. You can add more urls to @font-face section if there are different types of fonts.

Folder structure looks like this

VAADIN/themes/my-style/styles.scss

VAADIN/themes/my-style/my-style.scss

VAADIN/themes/my-style/fonts/RobotoCondensed-Regular.ttf

...

styles.scss

```<code>@import "my-style.scss";
.my-valo {
    @include my-style;
}
</code>```

my-style.scss

```<code>@import "my other files ..."
@mixin my-valo {
    ...
}

@mixin MyRobotoFont($weight, $style, $fontWeight: 400, $fontStyle: normal) {
    @font-face {
        font-family: "Roboto Condensed";
        src: url('fonts/RobotoCondensed-#{$weight}#{$style}.ttf' format('truetype');
        font-weight: $fontWeight;
        font-style: $fontStyle;
    }
}

@include MyRobotoFont($weight: Regular, $style: "");
@include MyRobotoFont($weight: Bold, $style: "");
@include MyRobotoFont($weight: Bold, $style: Italic);
@include MyRobotoFont($weight: "", $style: Italic);
@include MyRobotoFont($weight: Light, $style: "");
@include MyRobotoFont($weight: Light, $style: Italic);
</code>```

Somewhere in your scss files

```<code>font-family: MyRobotoFont
font-weight: 400;
font-style: italic;
</code>```

Or in _variables.scss

```<code>$v-font-family: MyRobotoFont, arial, sans-serif
</code>```

Body:
I want to use Roboto Condensed font as local, not from web.

Like

@include font-face('Roboto Condensed', '../../../../../../styles/systemfont/*', 300, 300i, 400, 400i, 700&'subset=cyrillic, cyrillic-ext, latin-ext');

But this seems not to work

And I try to avoid to use

@StyleSheet("https://fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700&subset=cyrillic,cyrillic-ext,latin-ext")

in my UI class

Body:
This has worked for me. I am packaging my font in Jar like Vaadin is doing with their Valo theme and then I include that as a dependency through pom.xml.

Place font files (ttf etc.) in your theme folder. You can add more urls to @font-face section if there are different types of fonts.

Folder structure looks like this

VAADIN/themes/my-style/styles.scss

VAADIN/themes/my-style/my-style.scss

VAADIN/themes/my-style/fonts/RobotoCondensed-Regular.ttf

...

styles.scss

@import "my-style.scss";
.my-valo {
    @include my-style;
}

my-style.scss

@import "my other files ..."
@mixin my-valo {
    ...
}

@mixin MyRobotoFont($weight, $style, $fontWeight: 400, $fontStyle: normal) {
    @font-face {
        font-family: "Roboto Condensed";
        src: url('fonts/RobotoCondensed-#{$weight}#{$style}.ttf' format('truetype');
        font-weight: $fontWeight;
        font-style: $fontStyle;
    }
}

@include MyRobotoFont($weight: Regular, $style: "");
@include MyRobotoFont($weight: Bold, $style: "");
@include MyRobotoFont($weight: Bold, $style: Italic);
@include MyRobotoFont($weight: "", $style: Italic);
@include MyRobotoFont($weight: Light, $style: "");
@include MyRobotoFont($weight: Light, $style: Italic);

Somewhere in your scss files

font-family: MyRobotoFont
font-weight: 400;
font-style: italic;

Or in _variables.scss

$v-font-family: MyRobotoFont, arial, sans-serif


问:
NoMethodError: undefined method `assert_emails' in controller test
According to the Rails documentation, the method assert_emails allows to transform the syntax :

```<code>assert_difference ->{ ActionMailer::Base.deliveries.size }, +1 do
  post :method_that_should_send_email
end
</code>```

to

```<code>assert_emails 1 do
  post :method_that_should_send_email
end
</code>```

which I find much better, because I don't have to copy paste the long syntax every time.

However I get the following error in my controllers tests when using the above code:

NoMethodError: undefined method `assert_emails'

I assume this is because the method is only available in mailers tests.

Is there a way to make it available to controllers tests too? Is there a good reason why this is not available by default? Is there a better way to test that calling a specific route results in sending a email?

Thanks.

答:
I've just had the same problem when trying to use assert_emails in a regular test (not an ActionMailer::TestCase).

The helpers started working when I included ActionMailer::TestHelper to my test class.

```<code>class FooTest < ActiveSupport::TestCase
  include ActionMailer::TestHelper

  test '...' do
    assert_no_emails do
      # ...
    end
  end
end
</code>```

I believe that should work in your controller tests as well.

Body:
According to the Rails documentation, the method assert_emails allows to transform the syntax :

assert_difference ->{ ActionMailer::Base.deliveries.size }, +1 do
  post :method_that_should_send_email
end

to

assert_emails 1 do
  post :method_that_should_send_email
end

which I find much better, because I don't have to copy paste the long syntax every time.

However I get the following error in my controllers tests when using the above code:

NoMethodError: undefined method `assert_emails'

I assume this is because the method is only available in mailers tests.

Is there a way to make it available to controllers tests too? Is there a good reason why this is not available by default? Is there a better way to test that calling a specific route results in sending a email?

Thanks.

Body:
I've just had the same problem when trying to use assert_emails in a regular test (not an ActionMailer::TestCase).

The helpers started working when I included ActionMailer::TestHelper to my test class.

class FooTest < ActiveSupport::TestCase
  include ActionMailer::TestHelper

  test '...' do
    assert_no_emails do
      # ...
    end
  end
end

I believe that should work in your controller tests as well.


问:
Firebase Database rules - Give unauthenticated user access to ONLY read specific path
Say my Firebase Database rules look like this:

```<code>"rules": {
".read": "auth != null",
".write": "auth != null"
  }
</code>```

In my app I need to check if a username is already taken, and thus I need to do so before authenticating the user. I am aware that I could do something like this:

```<code>"rules": {
".write": "auth != null",
"Users": {
  ".read": true
}
}
</code>```

However, if I have understood how the rules work correctly, this will make only the "Users" path readable and by default every other path will be set to ".read": false. My question is therefore how I would make every path readable by an authenticated user, and make an unauthenticated user only able to read data from the path "Users" and nothing else.

答:
Certainly you can make it so one path in the database is readable for unauthenticated users, but I wouldn't recommend it. It's not ideal to allow anyone to read the usernames of all of your users.

One other option is you can create a user first and then have them choose a username once authenticated, but then you'd have to figure out how you wanted to handle users who are authenticated but then exit the app before choosing a username.

A better option is to use Cloud Functions for Firebase with an HTTP trigger, and pass the desired username as part of the request. The request would include a query of the desired username and the response would return whether the username is available or not. It could look something like this:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username)once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    })
}
</code>```

If you're new to Cloud Functions for Firebase, then check out these resources:

Getting Started with Cloud Functions for Firebase - YouTube

Cloud Functions for Firebase Documentation

Cloud Functions Samples

Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - YouTube

Body:
Say my Firebase Database rules look like this:

"rules": {
".read": "auth != null",
".write": "auth != null"
  }

In my app I need to check if a username is already taken, and thus I need to do so before authenticating the user. I am aware that I could do something like this:

"rules": {
".write": "auth != null",
"Users": {
  ".read": true
}
}

However, if I have understood how the rules work correctly, this will make only the "Users" path readable and by default every other path will be set to ".read": false. My question is therefore how I would make every path readable by an authenticated user, and make an unauthenticated user only able to read data from the path "Users" and nothing else.

Body:
Certainly you can make it so one path in the database is readable for unauthenticated users, but I wouldn't recommend it. It's not ideal to allow anyone to read the usernames of all of your users.

One other option is you can create a user first and then have them choose a username once authenticated, but then you'd have to figure out how you wanted to handle users who are authenticated but then exit the app before choosing a username.

A better option is to use Cloud Functions for Firebase with an HTTP trigger, and pass the desired username as part of the request. The request would include a query of the desired username and the response would return whether the username is available or not. It could look something like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username)once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    })
}

If you're new to Cloud Functions for Firebase, then check out these resources:

Getting Started with Cloud Functions for Firebase - YouTube

Cloud Functions for Firebase Documentation

Cloud Functions Samples

Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - YouTube


问:
Laravel Database Query returns collection of objects - how do I get the values to display?
I guess there is a simple solution to my problem, I'm just a beginner :D

On one of my controllers I have a fairly complex DB request (see below) that returns a collection of objects and not an array (and I think I cannot perform the request with Eloquent?). Now I don't know how I get these values to actually display inside my blade page? Do I have to somehow convert it to an array to do that?

Thank you very much!

Part of TagsController.php:

```<code>$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->get();
</code>```

return $tags:

```<code>[
    {
        "name": "javascript"
    },
    {
        "name": "jquery"
    },
    {
        "name": "php"
    }
]
</code>```

答:
use json_encode() first to get the json from your result data, and then use json_decode() to convert the json data into array. so your final result will be a multidimensional array.

```<code>$tags=json_decode(json_encode($tags,true),true);
</code>```

Then you can print the data in your blade as

```<code>@foreach ($tags as $tag)
    <div>{{ $tag['name'] }}</div>
@endforeach
</code>```

Body:
I guess there is a simple solution to my problem, I'm just a beginner :D

On one of my controllers I have a fairly complex DB request (see below) that returns a collection of objects and not an array (and I think I cannot perform the request with Eloquent?). Now I don't know how I get these values to actually display inside my blade page? Do I have to somehow convert it to an array to do that?

Thank you very much!

Part of TagsController.php:

$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->get();

return $tags:

[
    {
        "name": "javascript"
    },
    {
        "name": "jquery"
    },
    {
        "name": "php"
    }
]

Body:
use json_encode() first to get the json from your result data, and then use json_decode() to convert the json data into array. so your final result will be a multidimensional array.

$tags=json_decode(json_encode($tags,true),true);

Then you can print the data in your blade as

@foreach ($tags as $tag)
    <div>{{ $tag['name'] }}</div>
@endforeach


问:
Allow only letters, numbers, and hyphen in input?
I want to accept only letters, numbers, and hyphen (dash) in the input. in php, i do this:

```<code>if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
    echo "Only letters, numbers, and hyphens are allowed.";
}
</code>```

how can I achieve this same thing in vanilla javascript? if its not possible in pure javascript, how can i do it in jquery? thanks

答:
Adapted from Sylvain's answer here: jQuery only allow numbers,letters and hyphens.

Note: jQuery is pretty much a wrapper for vanilla js to make a lot of common statements like Document.querySelectorAll() shorter, it's generally safe to assume that jQuery can be directly converted to vanilla js (I can't think of any examples off the top of my head where the jQuery functionality differs).

What you could do is select all the inputs in a form (or whichever you would like), then test their values against a regex (Sylvain used a regex that selects the inverse of the desired characters so that it would be true if there is an invalid character) and if it has any forbidden character prevent the form from submitting and do some other things asking the user to address the issue.

document.getElementById("formWhitelistedChars").addEventListener("submit", function(e) {
    // Get all inputs in the form we specifically are looking at, this selector can be
    // changed if this is supposed to be applied to specific inputs
    var inputs = document.querySelectorAll('#formWhitelistedChars input');
    var forbiddenChars = /[^a-z\d\-]/ig;

    // check all the inputs we selected
    for(var input of inputs) {
        // Just in case the selector decides to do something weird
        if(!input) continue;

        // Check that there aren't any forbidden chars
        if(forbiddenChars.test(input.value)) {
            // This line is just to do something on a failure for Stackoverflow
            // I suggest removing this and doing something different in application
            console.log('input ' + input.name + ' has forbidden chars.');

            // Do stuff here

            // Prevent submit even propagation (don't submit)
            e.preventDefault();
            return false;
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="formWhitelistedChars">
  <input name="1" />
  <input name="2" />
  <button type="submit">Submit</button>
</form></code>```

EDIT: Replaced 0-9 with \d as @ibrahimmahrir mentioned in the comments

EDIT2: Changed input listeners to form submit

Body:
I want to accept only letters, numbers, and hyphen (dash) in the input. in php, i do this:

if(!preg_match("/^[A-Za-z0-9-]+$/", $input)) {
    echo "Only letters, numbers, and hyphens are allowed.";
}

how can I achieve this same thing in vanilla javascript? if its not possible in pure javascript, how can i do it in jquery? thanks

Body:
Adapted from Sylvain's answer here: jQuery only allow numbers,letters and hyphens.

Note: jQuery is pretty much a wrapper for vanilla js to make a lot of common statements like Document.querySelectorAll() shorter, it's generally safe to assume that jQuery can be directly converted to vanilla js (I can't think of any examples off the top of my head where the jQuery functionality differs).

What you could do is select all the inputs in a form (or whichever you would like), then test their values against a regex (Sylvain used a regex that selects the inverse of the desired characters so that it would be true if there is an invalid character) and if it has any forbidden character prevent the form from submitting and do some other things asking the user to address the issue.

document.getElementById("formWhitelistedChars").addEventListener("submit", function(e) {
    // Get all inputs in the form we specifically are looking at, this selector can be
    // changed if this is supposed to be applied to specific inputs
    var inputs = document.querySelectorAll('#formWhitelistedChars input');
    var forbiddenChars = /[^a-z\d\-]/ig;

    // check all the inputs we selected
    for(var input of inputs) {
        // Just in case the selector decides to do something weird
        if(!input) continue;

        // Check that there aren't any forbidden chars
        if(forbiddenChars.test(input.value)) {
            // This line is just to do something on a failure for Stackoverflow
            // I suggest removing this and doing something different in application
            console.log('input ' + input.name + ' has forbidden chars.');

            // Do stuff here

            // Prevent submit even propagation (don't submit)
            e.preventDefault();
            return false;
        }
    }
});

<form id="formWhitelistedChars">
  <input name="1" />
  <input name="2" />
  <button type="submit">Submit</button>
</form>

EDIT: Replaced 0-9 with \d as @ibrahimmahrir mentioned in the comments

EDIT2: Changed input listeners to form submit


问:
Ruby (Rails) DRY - Function pattern
I'm using ruby on rails for a project and noticed I'm using some pattern on my functions that goes like this:

```<code>begin
    ActiveRecord::Base.transaction do
        #some database manipulation
    end
    return true
rescue
    return false
end
</code>```

So I would like to DRY my code, in a way that only that #some database manipulation is gonna change. Any ideas of how I could do that? Thanks in advance!

答:
You could create a method like this:

```<code>def with_transaction
  ActiveRecord::Base.transaction do
    yield
  end
  return true
rescue
  return false
end
</code>```

And then use it like:

```<code>with_transaction do
  # some db manipulation
end
</code>```

But generally I would advise against silencing errors like that.

Title: Ruby (Rails) DRY - Function pattern

Body:
I'm using ruby on rails for a project and noticed I'm using some pattern on my functions that goes like this:

begin
    ActiveRecord::Base.transaction do
        #some database manipulation
    end
    return true
rescue
    return false
end

So I would like to DRY my code, in a way that only that #some database manipulation is gonna change. Any ideas of how I could do that? Thanks in advance!

Body:
You could create a method like this:

def with_transaction
  ActiveRecord::Base.transaction do
    yield
  end
  return true
rescue
  return false
end

And then use it like:

with_transaction do
  # some db manipulation
end

But generally I would advise against silencing errors like that.


问:
How many number of ordering node can take a transaction in Hyper-ledger Fabric?
When we talk about ordering service in a hyper-ledger fabric architecture,
how many ordering nodes can take up a transaction? </p>

答:
Hyperledger Fabric v1.0 comes with 2 implementations of ordering service types:

Solo Orderer - mainly for development and testing, that comes with only a single node.

Kafka Orderer - a set of ordering service nodes that communicate with one another via sending and receiving messages through a cluster of Apache Kafka brokers.

In each of these - a transaction is sent to exactly one ordering service nodes, and it signed by exactly one ordering service node.


问:
tkinter - Scrollbar will not show
I am having a developing a GUI in Python and there is no scrollbar that shows when I run it. It get an empty bar with arrows, but there is no scrollbar inside and the scrollbar does not work at all. </p>

```<code>#Scroll Functions
    def ScrollAll(event):
        self.topcanvas.config(scrollregion = self.topcanvas.bbox("all"))
    def on_mousewheel(event):
        self.topcanvas.yview('scroll',0, 'units')

    #topframe
    topframe = Frame(master, background = '#D9F7FE', width = 2100, height = 1700)
    topframe.place(x = 0, y = 0)

    #Top canvas
    self.topcanvas = Canvas(topframe, scrollregion = (0, 0, 1000, 1000))
    self.topcanvas.pack(side = TOP, fill = BOTH, expand = TRUE)
    self.topcanvas.config(width = 2100, height =1700, background = '#D9F7FE')

    #scroll
    self.vbar = ttk.Scrollbar(master, orient = 'vertical', command = self.topcanvas.yview)
    #self.hbar = ttk.Scrollbar(master, orient = 'horizontal', command = self.topcanvas.xview)
    #self.topcanvas.config(xscrollcommand = self.hbar.set)
    self.topcanvas.config(yscrollcommand = self.vbar.set)

    #self.hbar.pack(side = "bottom", fill = "x")
    self.vbar.pack(side = "right", fill = "y")
    self.topcanvas.pack(side="left")
    self.topcanvas.bind_all("<MouseWheel>", on_mousewheel)

    #frame
    frame = Frame(self.topcanvas)
    frame.config(width = 2100, height = 1700,background = '#D9F7FE')
    self.topcanvas.create_window((0,0), window = frame, anchor = 'nw')
    frame.bind("<Configure>", ScrollAll)
</code>```

答: My scroll region needed to be larger than the actual frame it was in. I increased my scroll region and my scroll bars worked.</p>

Title: tkinter - Scrollbar will not show

Body:
I am having a developing a GUI in Python and there is no scrollbar that shows when I run it. It get an empty bar with arrows, but there is no scrollbar inside and the scrollbar does not work at all.

#Scroll Functions
    def ScrollAll(event):
        self.topcanvas.config(scrollregion = self.topcanvas.bbox("all"))
    def on_mousewheel(event):
        self.topcanvas.yview('scroll',0, 'units')

    #topframe
    topframe = Frame(master, background = '#D9F7FE', width = 2100, height = 1700)
    topframe.place(x = 0, y = 0)

    #Top canvas
    self.topcanvas = Canvas(topframe, scrollregion = (0, 0, 1000, 1000))
    self.topcanvas.pack(side = TOP, fill = BOTH, expand = TRUE)
    self.topcanvas.config(width = 2100, height =1700, background = '#D9F7FE')

    #scroll
    self.vbar = ttk.Scrollbar(master, orient = 'vertical', command = self.topcanvas.yview)
    #self.hbar = ttk.Scrollbar(master, orient = 'horizontal', command = self.topcanvas.xview)
    #self.topcanvas.config(xscrollcommand = self.hbar.set)
    self.topcanvas.config(yscrollcommand = self.vbar.set)

    #self.hbar.pack(side = "bottom", fill = "x")
    self.vbar.pack(side = "right", fill = "y")
    self.topcanvas.pack(side="left")
    self.topcanvas.bind_all("<MouseWheel>", on_mousewheel)

    #frame
    frame = Frame(self.topcanvas)
    frame.config(width = 2100, height = 1700,background = '#D9F7FE')
    self.topcanvas.create_window((0,0), window = frame, anchor = 'nw')
    frame.bind("<Configure>", ScrollAll)


问:
How to paste multiple lines in Vim?
QUESTION:

I am deleting/copying every other line with :g/^/+d
However, when I try pasting all of those lines only the last line gets pasted. How do I paste every single line that I deleted/copied?

RESOLVED:

Thanks everyone! With your help I was able to finish my video (I work on a Youtube channel called Vim Girl where I make guided Vim Golf challenges.) Here's the link if you're interested: https://youtu.be/S9o5bHUAbP0

答:
Selecting all the lines you want to copy using the mouse, press ^shiftc using the text getting copied.

Now pasting, get at the position that you want to paste to, then press ESC:set paste insert and then ^shiftv

If you want to cut/paste then use dd and p to paste. You can also use d4d in place of dd to cut/paste 4 lines.

Title: How to paste multiple lines in Vim?


问:
Can't import dependency installed with Cocoapods
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:

答:
Why not simply use the Swift pods?-

```<code>pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'
</code>```

and then import as normal, like-

```<code>import FBSDKLoginKit
import FacebookLogin
</code>```

Once done, do a clean and build (command/⌘ + Shift + K) and Build (command/⌘ + B). Make sure you are using the .xcworkspace file to open the project.

More info on Swift FBSDK here.

Once you use the Swift pods, you should see these Frameworks in your project.

If you still continue to see the error then "Clean the build folder" using command + shift + alt + K.

Body:
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:

Body:
Why not simply use the Swift pods?-

pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'

and then import as normal, like-

import FBSDKLoginKit
import FacebookLogin

Once done, do a clean and build (command/⌘ + Shift + K) and Build (command/⌘ + B). Make sure you are using the .xcworkspace file to open the project.

More info on Swift FBSDK here.

Once you use the Swift pods, you should see these Frameworks in your project.

If you still continue to see the error then "Clean the build folder" using command + shift + alt + K.