问:
canActivate Dependant on Parent Route Resolve
I have routes setup like so:

```<code>export const APP_ROUTES: Routes = [
    {
        path: '',
        resolve: {
            user: CurrentUserResolver
        },
        children: [
            {
                path: ':sectionKey',
                canActivate: [SectionAccessGuard],
                children: [
                    {
                        path: 'dashboard',
                        component: DashboardComponent
                    }
                ]
            }
        ]
    }
]
</code>```

Where the parent route will retrieve the user via a HTTP call, and I'd like my sub-route :sectionKey to only be activated if the current user has access to it.  The issue is, it appears my canActivate SectionAccessGuard is called prior to the snapshot being fully populated:

```<code>@Injectable()
export default class SectionAccessGuard implements CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log(route.data);
        console.log(route);
        return true;
    }
}
</code>```

In the console, the first entry will have nothing; however, the 2nd entry will eventually have the user field populated.

I know the canActivate method can return an Observable<boolean> as well, but I don't see any hooks on how to wait until the resolve completes.

What am I missing here?  I feel like this should be pretty straight forward.  I'm currently using angular v4.0.0-rc.2

答:
I'm struggling with this too and I'd like to see more documentation surrounding this from the Angular team. It seems canActivate does not wait to start running until after the parent is finished, but resolve does.

You can change your can activate code into another resolve, because a child resolve does wait for a parent resolve. If it is changed to resolve you will have access to the user through route.parent.data.user and you can then make a call to router.navigate to leave the section if the user isn't authorized.

Another approach is to set up a service that can be injected into both the resolve guard and the canActivate guard. You'd have to set up an observable from the resolve guard and subscribe to it in the canActivate guard.

Body:
I have routes setup like so:

export const APP_ROUTES: Routes = [
    {
        path: '',
        resolve: {
            user: CurrentUserResolver
        },
        children: [
            {
                path: ':sectionKey',
                canActivate: [SectionAccessGuard],
                children: [
                    {
                        path: 'dashboard',
                        component: DashboardComponent
                    }
                ]
            }
        ]
    }
]

Where the parent route will retrieve the user via a HTTP call, and I'd like my sub-route :sectionKey to only be activated if the current user has access to it.  The issue is, it appears my canActivate SectionAccessGuard is called prior to the snapshot being fully populated:

@Injectable()
export default class SectionAccessGuard implements CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log(route.data);
        console.log(route);
        return true;
    }
}

In the console, the first entry will have nothing; however, the 2nd entry will eventually have the user field populated.

I know the canActivate method can return an Observable<boolean> as well, but I don't see any hooks on how to wait until the resolve completes.

What am I missing here?  I feel like this should be pretty straight forward.  I'm currently using angular v4.0.0-rc.2


来源: stackexchange

问:
Getting javascript variables with Python
I want to scrap data inside a js script on a distant web page using Python. I woud like to only get the numbers of "ownerId" and "id". I want to do it on multiple pages so the numbers will be different each time, how can I do that ?

```<code>var _zf_aab = new zfl_Guestbook('_aab', { ownerId: 12443183, id: 891273218, type: 2 }, _zf_aabb, _zf_aaba, 17, false, '4Yhbn6glH6xXTW3UWh4GceL1mCDcXyiASFBtk_8j-mA=');
</code>```

Thank you

答:
You can use something like this:</p>

```<code>import re
your_string = "var _zf_aab = new zfl_Guestbook('_aab', { ownerId: 12443183, id: 891273218, type: 2 }, _zf_aabb, _zf_aaba, 17, false, '4Yhbn6glH6xXTW3UWh4GceL1mCDcXyiASFBtk_8j-mA=');"
owner_id = re.search(r'ownerId: ([1-9]+)?,', your_string).group(1)
id = re.search(r'id: ([1-9]+)?,', your_string).group(1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to scrap data inside a js script on a distant web page using Python. I woud like to only get the numbers of "ownerId" and "id". I want to do it on multiple pages so the numbers will be different each time, how can I do that ?

var _zf_aab = new zfl_Guestbook('_aab', { ownerId: 12443183, id: 891273218, type: 2 }, _zf_aabb, _zf_aaba, 17, false, '4Yhbn6glH6xXTW3UWh4GceL1mCDcXyiASFBtk_8j-mA=');

Thank you

Body:
You can use something like this:

import re
your_string = "var _zf_aab = new zfl_Guestbook('_aab', { ownerId: 12443183, id: 891273218, type: 2 }, _zf_aabb, _zf_aaba, 17, false, '4Yhbn6glH6xXTW3UWh4GceL1mCDcXyiASFBtk_8j-mA=');"
owner_id = re.search(r'ownerId: ([1-9]+)?,', your_string).group(1)
id = re.search(r'id: ([1-9]+)?,', your_string).group(1)


问:
Akka Stream connect to multiple sinks
I have implemented a custom component in akka stream which takes elements as input, groups and merges them based on a key and sends them out through one of a dozen outlets. You can think of this component as a kind of GroupBy component which does not partition the flow into subflows, but actual flows. In addition to partitioning incoming elements, it merges them into one element, i.e. there is some buffering happening inside the component such that 1 element in does not necessarily mean 1 element out through an outlet.

Below is a simplified implementation of said component.

```<code>class CustomGroupBy[A,B](k: Int, f: A => Int) extends GraphStage[FlowShape[B, B]] {

  val in = Inlet[A]("CustomGroupBy.in")
  val outs = (0 until k).map(i => Outlet[B](s"CustomGroupBy.$i.out"))

  override val shape = new AmorphousShape(scala.collection.immutable.Seq(in), outs)

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

I now what to connect each outlet of that component to a different Sink and combine the materialized value of all these sinks.

I have tried a few things with the graph DSL, but have not quite managed to get it working. Would anyone be so kind as to provide me with a snippet to do that or point me in the right direction?

Thanks in advance!

答:
You probably want the akka.stream.scaladsl.Partition[T](outputPorts: Int, partitioner: T ⇒ Int) stage.

EDIT:

To connect all the ports, and keep the materialized values, you have to give your stages as parameters to the GraphDSL.create method.

This allows you to define a combiner for the materialized values, and add the stages to your GraphDSLBuilder, as parameters to the last argument. Note that this overloaded create method does not take a varargs parameter, so it may not be possible to have 14 different stages treated that way.

Assuming some names for your stages, here is how I would implement it, in the case of 3 outputs:

```<code>val runnable = RunnableGraph.fromGraph(
  GraphDSL.create(
    source, customGroupBy, sink1, sink2, sink3)(combiner) {  //the combiner is the function to combine the materialized values
      implicit b => //this is the builder, needed as implicit to make the connections
      (src, cgb, s1, s2, s3) => //here are the stages added to the builder
      import GraphDSL.Implicits._

      src.out ~> cgb.in
      List(s1, s2, s3).map(_.in).zip(cgb.outlets).foreach{
        case (in, out) => in ~> out
      }

      ClosedShape
    }
  )
)
</code>```

Remember that if you don't need one of the stages' materialized value, you can just add it inside the DSL by doing val cgb = b.add(customGroupBy)

Title: Akka Stream connect to multiple sinks

Body:
I have implemented a custom component in akka stream which takes elements as input, groups and merges them based on a key and sends them out through one of a dozen outlets. You can think of this component as a kind of GroupBy component which does not partition the flow into subflows, but actual flows. In addition to partitioning incoming elements, it merges them into one element, i.e. there is some buffering happening inside the component such that 1 element in does not necessarily mean 1 element out through an outlet.

Below is a simplified implementation of said component.

class CustomGroupBy[A,B](k: Int, f: A => Int) extends GraphStage[FlowShape[B, B]] {

  val in = Inlet[A]("CustomGroupBy.in")
  val outs = (0 until k).map(i => Outlet[B](s"CustomGroupBy.$i.out"))

  override val shape = new AmorphousShape(scala.collection.immutable.Seq(in), outs)

  /* ... */
}

I now what to connect each outlet of that component to a different Sink and combine the materialized value of all these sinks.

I have tried a few things with the graph DSL, but have not quite managed to get it working. Would anyone be so kind as to provide me with a snippet to do that or point me in the right direction?

Thanks in advance!

Body:
You probably want the akka.stream.scaladsl.Partition[T](outputPorts: Int, partitioner: T ⇒ Int) stage.

EDIT:

To connect all the ports, and keep the materialized values, you have to give your stages as parameters to the GraphDSL.create method.

This allows you to define a combiner for the materialized values, and add the stages to your GraphDSLBuilder, as parameters to the last argument. Note that this overloaded create method does not take a varargs parameter, so it may not be possible to have 14 different stages treated that way.

Assuming some names for your stages, here is how I would implement it, in the case of 3 outputs:

val runnable = RunnableGraph.fromGraph(
  GraphDSL.create(
    source, customGroupBy, sink1, sink2, sink3)(combiner) {  //the combiner is the function to combine the materialized values
      implicit b => //this is the builder, needed as implicit to make the connections
      (src, cgb, s1, s2, s3) => //here are the stages added to the builder
      import GraphDSL.Implicits._

      src.out ~> cgb.in
      List(s1, s2, s3).map(_.in).zip(cgb.outlets).foreach{
        case (in, out) => in ~> out
      }

      ClosedShape
    }
  )
)

Remember that if you don't need one of the stages' materialized value, you can just add it inside the DSL by doing val cgb = b.add(customGroupBy)


问:
check if progressbar animation is done android
I need to check when the progressbar animation is done.

Then i need to do something.

I already have this:

```<code>private ObjectAnimator progressAnimator;

mProgressBar = (ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setMax(1000);
progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 1000, 0);
progressAnimator.setDuration(10000);
progressAnimator.start();
</code>```

How to check if this animation is done??

答:
Use addListener() method:</p>

```<code>     progressAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }
            @Override
            public void onAnimationEnd(Animator animation) {
               //here animation finished
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
</code>```

Body:
I need to check when the progressbar animation is done.

Then i need to do something.

I already have this:

private ObjectAnimator progressAnimator;

mProgressBar = (ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setMax(1000);
progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 1000, 0);
progressAnimator.setDuration(10000);
progressAnimator.start();

How to check if this animation is done??

Body:
Use addListener() method:

     progressAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }
            @Override
            public void onAnimationEnd(Animator animation) {
               //here animation finished
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });


问:
How does Python's bitwise complement operator (~ tilde) work?
Why is it that ~2 is equal to -3?  How does ~ operator work?

答:
Javascript tilde (~) coerces a given value to the one's complement--all bits are inverted.
That's all tilde does. It's not sign opinionated. It neither adds nor subtracts any quantity.

```<code>0 -> 1
1 -> 0
...in every bit position [0...integer nbr of bits - 1]
</code>```

On standard desktop processors using high-level languages like JavaScript,  BASE10 signed arithmetic is the most common, but keep in mind, it's not the only kind. Bits at the CPU level are subject to interpretation based on a number of factors. At the 'code' level, in this case JavaScript, they are interpreted as a 32-bit signed integer by definition (let's leave floats out of this). Think of it as quantum, those 32-bits represent many possible values all at once. It depends entirely on the converting lens you view them through.

```<code>JavaScript Tilde operation (1's complement)

BASE2 lens
~0001 -> 1110  - end result of ~ bitwise operation

BASE10 Signed lens (typical JS implementation)
~1  -> -2

BASE10 Unsigned lens
~1  -> 14
</code>```

All of the above are true at the same time.

ContentLicense: CC BY-SA 4.0

Body:
Javascript tilde (~) coerces a given value to the one's complement--all bits are inverted.
That's all tilde does. It's not sign opinionated. It neither adds nor subtracts any quantity.

0 -> 1
1 -> 0
...in every bit position [0...integer nbr of bits - 1]

On standard desktop processors using high-level languages like JavaScript,  BASE10 signed arithmetic is the most common, but keep in mind, it's not the only kind. Bits at the CPU level are subject to interpretation based on a number of factors. At the 'code' level, in this case JavaScript, they are interpreted as a 32-bit signed integer by definition (let's leave floats out of this). Think of it as quantum, those 32-bits represent many possible values all at once. It depends entirely on the converting lens you view them through.

JavaScript Tilde operation (1's complement)

BASE2 lens
~0001 -> 1110  - end result of ~ bitwise operation

BASE10 Signed lens (typical JS implementation)
~1  -> -2

BASE10 Unsigned lens
~1  -> 14

All of the above are true at the same time.


问:
Is it possible to implement comparator in single class?
Generally I saw- To implement comparator in java collections we need 2 classes , one class call the sort function and 2nd class implement comparator.. I want to know Is there any way to implement whole comparator concept in a single class??</p>

答:
Yes, you can use comparator without creating that second class. if you want to use comparator  in one class, you have 3 options.  You can 1. create an inner class.  2. create an anonymous class, and 3. (Which is the best way to do it) use a lambda.  Using lambdas are the best way to create readable code.

So in your code, this should work:

```<code>al.sort((o1, o2) -> o1.name.compareTo(o2.name));
</code>```

It's that easy.  This is new in Java 8, and I'm very glad they added this.  Your question touches on one of the downfalls of OOP.  Sometimes, you don't WANT to pass objects, only behavior, which is what lambdas accomplish.

Body:
Yes, you can use comparator without creating that second class. if you want to use comparator  in one class, you have 3 options.  You can 1. create an inner class.  2. create an anonymous class, and 3. (Which is the best way to do it) use a lambda.  Using lambdas are the best way to create readable code.

So in your code, this should work:

al.sort((o1, o2) -> o1.name.compareTo(o2.name));

It's that easy.  This is new in Java 8, and I'm very glad they added this.  Your question touches on one of the downfalls of OOP.  Sometimes, you don't WANT to pass objects, only behavior, which is what lambdas accomplish.


问:
jQuery ID Return is undefined although HTML ID is defined
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

```<code><div class="mainContent">
<div class="articleContent">
     <h1>header1</h1>
     <p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>

<div class="mainContent">
<div class="articleContent">
     <h1>header2</h1>
     <p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
</code>```

And then the JS/jQuery

```<code>function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}
</code>```

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

答:
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.

With querySelector you get the element and then with parentElement you can retrieve the parent of that element.

```<code>function readMore(el) {
  var articleFooterId = el.id;
  var articlePara = document.querySelector(".articleContent #"+articleFooterId);
  var articleContent = articlePara.parentElement;

  console.log('articleFooter', articleFooterId);
  console.log('articlePara', articlePara);
  console.log('articleContent', articleContent);
}
</code>```

In your html you can return the 'this' object back to the function by doing readMore(this).

```<code><div class="mainContent">
  <div class="articleContent">
       <h1>header1</h1>
       <p class="articlePara" id="one">para1</p>
  </div>
  <div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>

<div class="mainContent">
  <div class="articleContent">
       <h1>header2</h1>
       <p class="articlePara" id="two">para2</p>
  </div>
  <div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>
</code>```

jsfiddle

Body:
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.

header1

para1

header2

para2

And then the JS/jQuery

function readMore() {
var subID = event.target.id;

var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");

alert(newTarget.id);
}

At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.

jsfiddle: https://jsfiddle.net/dr0f2nu3/

To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.

Body:
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.

With querySelector you get the element and then with parentElement you can retrieve the parent of that element.

function readMore(el) {
  var articleFooterId = el.id;
  var articlePara = document.querySelector(".articleContent #"+articleFooterId);
  var articleContent = articlePara.parentElement;

  console.log('articleFooter', articleFooterId);
  console.log('articlePara', articlePara);
  console.log('articleContent', articleContent);
}

In your html you can return the 'this' object back to the function by doing readMore(this).

<div class="mainContent">
  <div class="articleContent">
       <h1>header1</h1>
       <p class="articlePara" id="one">para1</p>
  </div>
  <div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>

<div class="mainContent">
  <div class="articleContent">
       <h1>header2</h1>
       <p class="articlePara" id="two">para2</p>
  </div>
  <div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>

jsfiddle


问:
Apple AppStore Reject
Does Apple reject iPhone/iPad Apps because of using Third Prty APIs.. </p>

答:
No, Apple never rejects application because of third party APIs. If you use any PRIVATE API of apple, it invariably gets rejected.

Google maps, google analytics, google weather, UAStoreFront, Authorize.net etc. are third parties which provide their own APIs for specfic functionality's and lots and lots of applications are there on the app-store which use these APIs

ContentLicense: CC BY-SA 2.5

Title: Apple AppStore Reject


问:
Order of operands in C
Say you have x = exp1 + exp2 in c. It might be evaluated by first evaluating exp1 then exp2 and adding the results however it may evaluate exp2 first.

How do you find out which side is evaluated first? I would like to make x = 1/2 depending on which one was evaluated first.

Any ideas?

答:
How do you find out which side is evaluated first?

Generally this is not specified by the standard. C11 6.5/3:

Except as specified later, side effects and value computations of
  subexpressions are unsequenced. 86)

...

86) In an expression that is evaluated more than once
  during the execution of a program, unsequenced and indeterminately
  sequenced evaluations of its subexpressions need not be performed
  consistently in different evaluations.

"Specified later" refers to a few special cases where the order of evaluation is specified, namely for the following operators: || && ?: ,, which are all guaranteed to be evaluated left-to-right.

As we can see from the cited note, we can't even know if the same program will treat the same expression consistently. This is called unspecified behavior, which means that compiler will behave in one of several well-defined ways but we can never know or assume which way. You should always write your programs so that the order of evaluation does not matter.

If you wish to fool around with code that prints which order the compiler decided to evaluate a particular expression (this time), you could do:

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

int func(void)
{
  static int x=0;
  return x++;
}

int main (void)
{
  printf("%d", func() << func());
}
</code>```

This will either give 0<<1 == 0 (left-to-right) or 1<<0 == 1 (right-to-left). But such code has no practical purpose.

Title: Order of operands in C

Body:
How do you find out which side is evaluated first?

Generally this is not specified by the standard. C11 6.5/3:

Except as specified later, side effects and value computations of
  subexpressions are unsequenced. 86)

...

86) In an expression that is evaluated more than once
  during the execution of a program, unsequenced and indeterminately
  sequenced evaluations of its subexpressions need not be performed
  consistently in different evaluations.

"Specified later" refers to a few special cases where the order of evaluation is specified, namely for the following operators: || && ?: ,, which are all guaranteed to be evaluated left-to-right.

As we can see from the cited note, we can't even know if the same program will treat the same expression consistently. This is called unspecified behavior, which means that compiler will behave in one of several well-defined ways but we can never know or assume which way. You should always write your programs so that the order of evaluation does not matter.

If you wish to fool around with code that prints which order the compiler decided to evaluate a particular expression (this time), you could do:

#include <stdio.h>

int func(void)
{
  static int x=0;
  return x++;
}

int main (void)
{
  printf("%d", func() << func());
}

This will either give 0<<1 == 0 (left-to-right) or 1<<0 == 1 (right-to-left). But such code has no practical purpose.


问:
Resetting a shared pointer captured in a lambda function
(I'm very unsure about the phrasing of the question title. I'm hoping it's not misleading because I really don't know how to summarize this. But I'll try to explain my problem as well as I can.)

In a project, there is something like this (written from memory and simplified):

```<code>Class A {
private:
    boost::weak_ptr<SomeClassB> b;
public:
    static boost::shared_ptr<SomeClassB> StopSomeProcesses () {
        boost::shared_ptr<SomeClassB> temp (new SomeClassB());
        b = temp;
        return temp;
    }
}
</code>```

Now in another project, I need to do something similar to the following:

```<code>boost::shared_ptr<SomeClassB> obj;
void someFunction () {
    obj = A::StopSomeProcesses();

    auto callback = [](){
        //some other stuff here
        obj.reset();
    };
    NamespaceFromYetAnotherProject::DoSomething(callback);
}
</code>```

What this basically does is while b holds a valid object from A::StopSomeProcesses, as the name implies, some processes will be stopped. In this case, the processes are stopped while DoSomething is executed. At the end, DoSomething will call callback where obj is reset and the stopped processes can now finally continue.

I've done this and it works. However, as much as possible, I'd like to avoid using global variables. I tried doing the following:

```<code>void someFunction () {
    boost::shared_ptr<SomeClassB> obj;
    obj = A::StopSomeProcesses();

    auto callback = [&obj](){
        //some other stuff here
        obj.reset();
    };
    NamespaceFromYetAnotherProject::DoSomething(callback);
}
</code>```

The above code works. But I'm not sure if I was already in "undefined behavior" territory and just got lucky. Doesn't obj's scope end already? Or does the fact that the lambda was passed as an argument help extend its "life"? If this is safe to do, is that safety lost if callback is run on another thread?

I also tried doing this:

```<code>void someFunction () {
    boost::shared_ptr<SomeClassB> obj;
    obj = A::StopSomeProcesses();

    auto callback = [obj](){
        //some other stuff here
        boost::shared_ptr<SomeClassB> tempObj (new SomeClassB(*obj));
        tempObj.reset();
    };
    NamespaceFromYetAnotherProject::DoSomething(callback);
}
</code>```

But this was something I tried randomly. I wrote it while completely focused on just deleting the object held by the shared pointer. It worked, but I'm not even sure if it's just roundabout or even valid.

Are these attempts going anywhere? Or am I completely going the wrong way? Or should I just stick to using a global variable? Would appreciate any help on how to go about this problem. Thanks!

答: You are using a shared_ptr and StopSomeProcesses will internally allocate the memory it points to. Pointers are passed by value so the lifetime of obj is irelevant. Every function call makes a new copy of it as does the binding in the lambda. What matters is what the pointer points too and that was allocated with new and lives on.</p>

Body:
(I'm very unsure about the phrasing of the question title. I'm hoping it's not misleading because I really don't know how to summarize this. But I'll try to explain my problem as well as I can.)

In a project, there is something like this (written from memory and simplified):

Class A {
private:
    boost::weak_ptr<SomeClassB> b;
public:
    static boost::shared_ptr<SomeClassB> StopSomeProcesses () {
        boost::shared_ptr<SomeClassB> temp (new SomeClassB());
        b = temp;
        return temp;
    }
}

Now in another project, I need to do something similar to the following:

boost::shared_ptr<SomeClassB> obj;
void someFunction () {
    obj = A::StopSomeProcesses();

    auto callback = [](){
        //some other stuff here
        obj.reset();
    };
    NamespaceFromYetAnotherProject::DoSomething(callback);
}

What this basically does is while b holds a valid object from A::StopSomeProcesses, as the name implies, some processes will be stopped. In this case, the processes are stopped while DoSomething is executed. At the end, DoSomething will call callback where obj is reset and the stopped processes can now finally continue.

I've done this and it works. However, as much as possible, I'd like to avoid using global variables. I tried doing the following:

void someFunction () {
    boost::shared_ptr<SomeClassB> obj;
    obj = A::StopSomeProcesses();

    auto callback = [&obj](){
        //some other stuff here
        obj.reset();
    };
    NamespaceFromYetAnotherProject::DoSomething(callback);
}

The above code works. But I'm not sure if I was already in "undefined behavior" territory and just got lucky. Doesn't obj's scope end already? Or does the fact that the lambda was passed as an argument help extend its "life"? If this is safe to do, is that safety lost if callback is run on another thread?

I also tried doing this:

void someFunction () {
    boost::shared_ptr<SomeClassB> obj;
    obj = A::StopSomeProcesses();

    auto callback = [obj](){
        //some other stuff here
        boost::shared_ptr<SomeClassB> tempObj (new SomeClassB(*obj));
        tempObj.reset();
    };
    NamespaceFromYetAnotherProject::DoSomething(callback);
}

But this was something I tried randomly. I wrote it while completely focused on just deleting the object held by the shared pointer. It worked, but I'm not even sure if it's just roundabout or even valid.

Are these attempts going anywhere? Or am I completely going the wrong way? Or should I just stick to using a global variable? Would appreciate any help on how to go about this problem. Thanks!


问:
How to listen to when elements with a certain are show() or hide() in jquery?
I have a number of elements on the a page which are hidden by default. Depending on a user behaviour, one might be shown (using jquery's show()). Similar, one might be hidden (using jquery's hide()).

All these elements have the same css class. Is there a way to create a listener for elements with a specific class to see if any of them have changed between hide/show?

Thanks!

答:
You can use :visible or :hidden. More info here https://api.jquery.com/visible-selector/ and here https://api.jquery.com/hidden-selector/

var $foo = $('.foo');

$foo.first().hide();

$('.foo').each(function() {
  console.log($(this).is(":visible"));
  console.log($(this).is(":hidden"));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">foo</div>
<div class="foo">foo</div></code>```

Body:
You can use :visible or :hidden. More info here https://api.jquery.com/visible-selector/ and here https://api.jquery.com/hidden-selector/

var $foo = $('.foo');

$foo.first().hide();

$('.foo').each(function() {
  console.log($(this).is(":visible"));
  console.log($(this).is(":hidden"));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">foo</div>
<div class="foo">foo</div>


问:
Apple Pay works on simulator but not on device
I am able to display Apple Pay view controller on simulator but not on device.

Entitlement added and certificate installed.

```<code>class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {

var paymentRequest: PKPaymentRequest!

override func viewDidLoad() {
    super.viewDidLoad()

}

func rydes(shipping: Double) -> [PKPaymentSummaryItem] {

    let ryde = PKPaymentSummaryItem(label: "Your Fare", amount: 1.00)
    let discount = PKPaymentSummaryItem(label: "Discount", amount: -0.00)
    let shipping = PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "\(shipping)"))
    let subTotal = ryde.amount.adding(discount.amount)
    let total = PKPaymentSummaryItem(label: "rydes", amount: subTotal)

    return [ryde, discount, shipping, total]

} // rydes() func

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect shippingMethod: PKShippingMethod, completion: @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) {

        completion(PKPaymentAuthorizationStatus.success, rydes(shipping: Double(shippingMethod.amount)))

    } // paymentAuthorizationViewController( didSelectShippingMethod )

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {

        completion(PKPaymentAuthorizationStatus.success)

    } // paymentAuthorizationViewController( didAuthorizePayment )

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {

        controller.dismiss(animated: true, completion: nil)

    } // paymentAuthorizationViewControllerDidFinish()

@IBAction func applePayPressed(_ sender: Any) {

    print("enable apple pay")

    // send user to Apple Pay to make payment

    let paymentNetworks = [PKPaymentNetwork.visa, .masterCard, .interac, .discover, .amex]
    let merchantId = "merchant.com.xxx"

    if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) {

        paymentRequest = PKPaymentRequest()
        paymentRequest.currencyCode = "CAD"
        paymentRequest.countryCode = "CA"
        paymentRequest.merchantIdentifier = merchantId
        paymentRequest.supportedNetworks = paymentNetworks
        paymentRequest.merchantCapabilities = .capability3DS
        paymentRequest.requiredShippingAddressFields = [.all]
        paymentRequest.paymentSummaryItems = self.rydes(shipping: 0.00)

        // . . .  shipping - not really needed

        let samedayShipping = PKShippingMethod(label: "Same Day", amount: 12.99)
        samedayShipping.detail = "Guaranteed same day delivery."
        samedayShipping.identifier = "sameday"

        let twodayShipping = PKShippingMethod(label: "Two Day", amount: 4.99)
        twodayShipping.detail = "Guaranteed within two days."
        twodayShipping.identifier = "twoday"

        let freeShipping = PKShippingMethod(label: "Same Day", amount: 0.00)
        freeShipping.detail = "Guaranteed same day."
        freeShipping.identifier = "freeShipping"

        paymentRequest.shippingMethods = [samedayShipping, twodayShipping, freeShipping]

        // . . .  shipping - not really needed

        let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
        applePayVC.delegate = self
        self.present(applePayVC, animated: true, completion: nil)

    }  else {

        print("Tell the user they need to set up Apple Pay!")
    }

} // applePayPressed func ACTION

}
</code>```

The above code just returns this line - Tell the user they need to set up Apple Pay!

I am using a iPhone 6s as the device and Apple Pay and Wallet are enabled with a valid debit card and credit card.  I am from Canada, so I am in a valid region.

Edited Code

```<code>class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {

var paymentRequest: PKPaymentRequest! // apple pay

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

func rydes() -> [PKPaymentSummaryItem] {

    let ryde = PKPaymentSummaryItem(label: "Your Fare", amount: 1.00)
    let subTotal = ryde.amount
    let total = PKPaymentSummaryItem(label: "rydes", amount: subTotal)

    return [ryde, total]

} // rydes() func

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {

        completion(PKPaymentAuthorizationStatus.success)

    } // paymentAuthorizationViewController( didAuthorizePayment )

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {

        controller.dismiss(animated: true, completion: nil)

    } // paymentAuthorizationViewControllerDidFinish()

@IBAction func applePayPressed(_ sender: Any) {

    print("enable apple pay")

    // send user to Apple Pay to make payment

    let paymentNetworks = [PKPaymentNetwork.visa, .masterCard, .interac, .discover, .amex]
    let merchantID = "merchant.com.xxx"

    if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) {
        paymentRequest = PKPaymentRequest()
        paymentRequest.currencyCode = "CAD"
        paymentRequest.countryCode = "CA"
        paymentRequest.merchantIdentifier = merchantID
        paymentRequest.supportedNetworks = paymentNetworks
        paymentRequest.merchantCapabilities = .capability3DS
        paymentRequest.requiredShippingAddressFields = [.all]
        paymentRequest.paymentSummaryItems = self.rydes()

        let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
        applePayVC.delegate = self
        self.present(applePayVC, animated: true, completion: nil)

    }  else {

        print("Tell the user they need to set up Apple Pay!")
    }

} // applePayPressed func ACTION

}
</code>```

答:
Same issue I face during enable of Apple Pay to my application. Make sure you have entered all the valid shipping, service and total payment value inside PKPaymentSummaryItem.

Also total payment value should be greater that 0.0 to show the payment gate way view. If any of the value is 0.0 then don't add as SummaryItem.

Code for Valid PKPaymentSummaryItem:

```<code>{
// 12.75 subtotal
NSDecimalNumber *subtotalAmount = [NSDecimalNumber decimalNumberWithMantissa:1275
 exponent:-2 isNegative:NO];
self.subtotal = [PKPaymentSummaryItem summaryItemWithLabel:@"Subtotal" amount:subtotalAmount];

// 2.00 discount
NSDecimalNumber *discountAmount = [NSDecimalNumber decimalNumberWithMantissa:200 exponent:-2 isNegative:YES];
self.discount = [PKPaymentSummaryItem summaryItemWithLabel:@"Discount" amount:discountAmount];

// 12.75 - 2.00 = 10.75 grand total
NSDecimalNumber *totalAmount = [NSDecimalNumber zero];
totalAmount = [totalAmount decimalNumberByAdding:subtotalAmount];
totalAmount = [totalAmount decimalNumberByAdding:discountAmount];
self.total = [PKPaymentSummaryItem summaryItemWithLabel:@"My Company Name" amount:totalAmount];
self.summaryItems = @[self.subtotal, self.discount, self.total];
request.paymentSummaryItems = self.summaryItems;
}
</code>```

This will try to fix your above issue.

Edit:
Just remove below code and check it again or put check condition if value for discount or shipping is greater that 0.0 then you can send shipping and discount as summary item:

```<code>    let ryde = PKPaymentSummaryItem(label: "Your Fare", amount: 1.00)
//change some value here:
    let discount = PKPaymentSummaryItem(label: "Discount", amount: -0.00)
    let shipping = PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "\(shipping)"))
Make sure your subtotal or total is greater that 0.0.
    let subTotal = ryde.amount.adding(discount.amount)
    let total = PKPaymentSummaryItem(label: "rydes", amount: subTotal)
</code>```

Body:
I am able to display Apple Pay view controller on simulator but not on device.

Entitlement added and certificate installed.

class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {

var paymentRequest: PKPaymentRequest!

override func viewDidLoad() {
    super.viewDidLoad()

}

func rydes(shipping: Double) -> [PKPaymentSummaryItem] {

    let ryde = PKPaymentSummaryItem(label: "Your Fare", amount: 1.00)
    let discount = PKPaymentSummaryItem(label: "Discount", amount: -0.00)
    let shipping = PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "\(shipping)"))
    let subTotal = ryde.amount.adding(discount.amount)
    let total = PKPaymentSummaryItem(label: "rydes", amount: subTotal)

    return [ryde, discount, shipping, total]

} // rydes() func

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect shippingMethod: PKShippingMethod, completion: @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) {

        completion(PKPaymentAuthorizationStatus.success, rydes(shipping: Double(shippingMethod.amount)))

    } // paymentAuthorizationViewController( didSelectShippingMethod )

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {

        completion(PKPaymentAuthorizationStatus.success)

    } // paymentAuthorizationViewController( didAuthorizePayment )

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {

        controller.dismiss(animated: true, completion: nil)

    } // paymentAuthorizationViewControllerDidFinish()

@IBAction func applePayPressed(_ sender: Any) {

    print("enable apple pay")

    // send user to Apple Pay to make payment

    let paymentNetworks = [PKPaymentNetwork.visa, .masterCard, .interac, .discover, .amex]
    let merchantId = "merchant.com.xxx"

    if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) {

        paymentRequest = PKPaymentRequest()
        paymentRequest.currencyCode = "CAD"
        paymentRequest.countryCode = "CA"
        paymentRequest.merchantIdentifier = merchantId
        paymentRequest.supportedNetworks = paymentNetworks
        paymentRequest.merchantCapabilities = .capability3DS
        paymentRequest.requiredShippingAddressFields = [.all]
        paymentRequest.paymentSummaryItems = self.rydes(shipping: 0.00)

        // . . .  shipping - not really needed

        let samedayShipping = PKShippingMethod(label: "Same Day", amount: 12.99)
        samedayShipping.detail = "Guaranteed same day delivery."
        samedayShipping.identifier = "sameday"

        let twodayShipping = PKShippingMethod(label: "Two Day", amount: 4.99)
        twodayShipping.detail = "Guaranteed within two days."
        twodayShipping.identifier = "twoday"

        let freeShipping = PKShippingMethod(label: "Same Day", amount: 0.00)
        freeShipping.detail = "Guaranteed same day."
        freeShipping.identifier = "freeShipping"

        paymentRequest.shippingMethods = [samedayShipping, twodayShipping, freeShipping]

        // . . .  shipping - not really needed

        let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
        applePayVC.delegate = self
        self.present(applePayVC, animated: true, completion: nil)

    }  else {

        print("Tell the user they need to set up Apple Pay!")
    }

} // applePayPressed func ACTION

}

The above code just returns this line - Tell the user they need to set up Apple Pay!

I am using a iPhone 6s as the device and Apple Pay and Wallet are enabled with a valid debit card and credit card.  I am from Canada, so I am in a valid region.

Edited Code

class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {

var paymentRequest: PKPaymentRequest! // apple pay

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

func rydes() -> [PKPaymentSummaryItem] {

    let ryde = PKPaymentSummaryItem(label: "Your Fare", amount: 1.00)
    let subTotal = ryde.amount
    let total = PKPaymentSummaryItem(label: "rydes", amount: subTotal)

    return [ryde, total]

} // rydes() func

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {

        completion(PKPaymentAuthorizationStatus.success)

    } // paymentAuthorizationViewController( didAuthorizePayment )

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {

        controller.dismiss(animated: true, completion: nil)

    } // paymentAuthorizationViewControllerDidFinish()

@IBAction func applePayPressed(_ sender: Any) {

    print("enable apple pay")

    // send user to Apple Pay to make payment

    let paymentNetworks = [PKPaymentNetwork.visa, .masterCard, .interac, .discover, .amex]
    let merchantID = "merchant.com.xxx"

    if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) {
        paymentRequest = PKPaymentRequest()
        paymentRequest.currencyCode = "CAD"
        paymentRequest.countryCode = "CA"
        paymentRequest.merchantIdentifier = merchantID
        paymentRequest.supportedNetworks = paymentNetworks
        paymentRequest.merchantCapabilities = .capability3DS
        paymentRequest.requiredShippingAddressFields = [.all]
        paymentRequest.paymentSummaryItems = self.rydes()

        let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
        applePayVC.delegate = self
        self.present(applePayVC, animated: true, completion: nil)

    }  else {

        print("Tell the user they need to set up Apple Pay!")
    }

} // applePayPressed func ACTION

}

Body:
Same issue I face during enable of Apple Pay to my application. Make sure you have entered all the valid shipping, service and total payment value inside PKPaymentSummaryItem.

Also total payment value should be greater that 0.0 to show the payment gate way view. If any of the value is 0.0 then don't add as SummaryItem.

Code for Valid PKPaymentSummaryItem:

{
// 12.75 subtotal
NSDecimalNumber *subtotalAmount = [NSDecimalNumber decimalNumberWithMantissa:1275
 exponent:-2 isNegative:NO];
self.subtotal = [PKPaymentSummaryItem summaryItemWithLabel:@"Subtotal" amount:subtotalAmount];

// 2.00 discount
NSDecimalNumber *discountAmount = [NSDecimalNumber decimalNumberWithMantissa:200 exponent:-2 isNegative:YES];
self.discount = [PKPaymentSummaryItem summaryItemWithLabel:@"Discount" amount:discountAmount];

// 12.75 - 2.00 = 10.75 grand total
NSDecimalNumber *totalAmount = [NSDecimalNumber zero];
totalAmount = [totalAmount decimalNumberByAdding:subtotalAmount];
totalAmount = [totalAmount decimalNumberByAdding:discountAmount];
self.total = [PKPaymentSummaryItem summaryItemWithLabel:@"My Company Name" amount:totalAmount];
self.summaryItems = @[self.subtotal, self.discount, self.total];
request.paymentSummaryItems = self.summaryItems;
}

This will try to fix your above issue.

Edit:
Just remove below code and check it again or put check condition if value for discount or shipping is greater that 0.0 then you can send shipping and discount as summary item:

    let ryde = PKPaymentSummaryItem(label: "Your Fare", amount: 1.00)
//change some value here:
    let discount = PKPaymentSummaryItem(label: "Discount", amount: -0.00)
    let shipping = PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "\(shipping)"))
Make sure your subtotal or total is greater that 0.0.
    let subTotal = ryde.amount.adding(discount.amount)
    let total = PKPaymentSummaryItem(label: "rydes", amount: subTotal)


问:
Is it possible to have function extensions on lambdas?
I'd like to check if some code throws a determined exception.

In particular, for my case, I'd like to write like:

{shaderCodeOf(gl, this::class.java, data + "$FRAGMENT_FAIL.frag")} shallThrow GLException::java.class

I tried to write

infix fun (() -> Unit).shallThrow(java: Class<*>)

but I didn't have much success..

any idea, guys?

答:
Not a straight answer to your question (receiver methods on lambdas), but there's an alternative implementation you could use:

```<code>inline fun <reified T: Throwable> assertThrows(fn: (() -> Unit)) {
    try {
        fn()
    } catch (e: Throwable) {
        if (e is T) {
            return
        } else {
            fail("Expected ${T::class} but caught ${e::class}")
        }
    }
    fail("Expected ${T::class} but caught nothing.")
}
</code>```

Which you can use as assertThrows<MyException> { doStuff(); }

Body:
Not a straight answer to your question (receiver methods on lambdas), but there's an alternative implementation you could use:

inline fun <reified T: Throwable> assertThrows(fn: (() -> Unit)) {
    try {
        fn()
    } catch (e: Throwable) {
        if (e is T) {
            return
        } else {
            fail("Expected ${T::class} but caught ${e::class}")
        }
    }
    fail("Expected ${T::class} but caught nothing.")
}

Which you can use as assertThrows<MyException> { doStuff(); }


问:
How do I run the Visual Studio (2017) Installer?
It's probably really obvious once you know the answer, but I can't find it anywhere.

I'm not talking about making an installer, I'm talking about running the installer that lets me modify which features of Visual Studio 2017 are installed.

The main screen looks like this:

the screen I need is this one:

In Visual Studio 2017, there is a menu entry for "Extensions and Updates" under the Tool menu that doesn't take me to this application.
There is also a "NuGet Package Manager" which isn't even close.

In my Windows 10 start menu, I see Visual Studio 2017 itself, and a folder named "Visual Studio 2017" that contains a couple of command prompts and a "Debuggable Package Manager".

In the Control Panel - Programs and Features, I see Microsoft Visual Studio 2017 but right-click only gives me "Uninstall".

答:
I also found it a bit strange that you cannot modify the installation from Control Panel - Programs and Features. You can however launch the Visual Studio 2017 installer from the following location:

```<code>%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe
</code>```

Body:
I also found it a bit strange that you cannot modify the installation from Control Panel - Programs and Features. You can however launch the Visual Studio 2017 installer from the following location:

%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe


问:
View another file structure then actual in WebStorm
Is it possible to have another view of the file structure then the actual running thing?
I cant change the file structure, because reasons...

Real:
This is the running file hierarchy.

```<code> folder1
 folder2
 folder3
</code>```

Wanted: This is how I want it to be displayed

```<code>parentfolder1
  folder1
  folder2

parentfolder2
  folder3
</code>```

答:
There is no such feature in WebStorm, please follow IDEABKL-6196 for updates.
You can use Favorites as a workaround, as it's suggested in https://youtrack.jetbrains.com/issue/IDEABKL-6196#comment=27-287102</p>

Body:
Is it possible to have another view of the file structure then the actual running thing?
I cant change the file structure, because reasons...

Real:
This is the running file hierarchy.

 folder1
 folder2
 folder3

Wanted: This is how I want it to be displayed

parentfolder1
  folder1
  folder2

parentfolder2
  folder3


问:
Blog posts not listing under Wagtail homepage
I've been successful in setting up the development server up to this tutorial:

http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html

I'm currently at the step "Create a template at blog/templates/blog/blog_page.html:" and I'm able to create child pages that go in homepage/blog/blog-post but they aren't listing in homepage/blog as they do in the tutorial. I can't figure out why and I've tried playing with changing where the blog posts show up by placing them in homepage/blog as blog posts but still nothing.

I think I'm not understanding what needs to be done here:

```<code>from django.db import models

from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailsearch import index

# Keep the definition of BlogIndexPage, and add:

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
    ]
</code>```

More specifically, # Keep the definition of BlogIndexPage, and add:.

Thanks for the help!

答: I figured it out. The homepage doesn't list blog posts until I manually import that from the page itself. They're all listed under /blog, where the guide intends for it to show up until you change it to also list under the homepage, which I will eventually set up. Thanks everyone.</p>

Body:
I've been successful in setting up the development server up to this tutorial:

http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html

I'm currently at the step "Create a template at blog/templates/blog/blog_page.html:" and I'm able to create child pages that go in homepage/blog/blog-post but they aren't listing in homepage/blog as they do in the tutorial. I can't figure out why and I've tried playing with changing where the blog posts show up by placing them in homepage/blog as blog posts but still nothing.

I think I'm not understanding what needs to be done here:

from django.db import models

from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailsearch import index

# Keep the definition of BlogIndexPage, and add:

class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
    ]

More specifically, # Keep the definition of BlogIndexPage, and add:.

Thanks for the help!


问:
Converting date to worded date in c#
I have a date in this format "MM/dd/yyyy".

```<code>string date = "03/30/2017"
</code>```

I want to convert this string to this format- Thursday, March 30, 2017.

How can I do this ?

Thank you

答:
You should parse it by using

```<code>string date = "03/30/2017";
DateTime datetime = DateTime.Parse(date);
string nameddate = datetime.ToString("dddd,MMMMM dd, yyyy");
</code>```

Other format options are found at
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Title: Converting date to worded date in c#

Body:
I have a date in this format "MM/dd/yyyy".

string date = "03/30/2017"

I want to convert this string to this format- Thursday, March 30, 2017.

How can I do this ?

Thank you

Body:
You should parse it by using

string date = "03/30/2017";
DateTime datetime = DateTime.Parse(date);
string nameddate = datetime.ToString("dddd,MMMMM dd, yyyy");

Other format options are found at
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx


问:
Socket.IO keeps reconnecting Websocket on Cloudflare
I have a Node/Express app on server dedicated to sockets and on the client it's Angular 1.5. Running the code locally on http using the same architecture e.g. separate socket server it all works perfectly fine.

When I run the code locally it creates one connection and does very little polling via xhr. On cloudflare with https it does a lot of polling, reconnects continually and not all the messages seem to be getting to the web client

messages hit cloudflare which then redirects them to a loadbalancer running haproxy which then routes the requests to an app running in a docker instance on another machine.

答:
Your Issue is most likely occuring beacause of an issue with cloudflare only allowing traffic to a limited set of ports. Try one of the ports listed in the below link for your server and try connecting to it.

https://support.cloudflare.com/hc/en-us/articles/200169156-Which-ports-will-Cloudflare-work-with-


问:
Python Selenium how to locate element
How can I click via selenium and python on such element:

```<code>      <a href="#create" class="btn toolbarBtn">
          <i class="fa fa-plus-circle"></i> Create
        </a>
</code>```

When I Copy Xpath this element from Chrome i got this:

//*[@id="page"]/div/div/div/div[1]/div[1]/a/i

But when I use it in my code:

driver.find_element_by_xpath('//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()

I got error that:

```<code>Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()"}
</code>```

When I tried to use find_element_by_link_text and partial_link_text I got same error that selenium was unable to find such element.

答:
In this particular case I found that selenium is going too fast, so some elements doesn't have time to load. When I put sleep(5) in the code the errors gone.

To avoid putting too many sleep() in my code I use driver.implicitly_wait(10) which resolved my problem definitely. I also dense my code a lot throwing up nearly all sleep() functions.

Thanks all for help!

Title: Python Selenium how to locate element

Body:
How can I click via selenium and python on such element:

           Create

When I Copy Xpath this element from Chrome i got this:

//*[@id="page"]/div/div/div/div[1]/div[1]/a/i

But when I use it in my code:

driver.find_element_by_xpath('//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()

I got error that:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()"}

When I tried to use find_element_by_link_text and partial_link_text I got same error that selenium was unable to find such element.


问:
Revoking permissions from user on specific tables?
I have granted all permissions on a database to a user 'demo' with this command:

```<code>grant all privileges on wordpress.* to demo@localhost;
</code>```

Now i want to revoke the user permissions on the table wp_users. I used this command:

```<code>revoke all privileges on wordpress.wp_users from demo@localhost;
</code>```

But i get this error:

```<code>ERROR 1147 (42000): There is no such grant defined for user 'demo' on host 'localhost' on table 'wp_users'
</code>```

Why i am getting this error?

答:
Because, as indicated, you're trying to revoke a grant that doesn't exist.

Making a broad grant makes a broad grant; it doesn't automatically make lots of individual grants that you can then cherry-pick away afterwards.

Simply grant access to the tables you want.

Body:
I have granted all permissions on a database to a user 'demo' with this command:

grant all privileges on wordpress.* to demo@localhost;

Now i want to revoke the user permissions on the table wp_users. I used this command:

revoke all privileges on wordpress.wp_users from demo@localhost;

But i get this error:

ERROR 1147 (42000): There is no such grant defined for user 'demo' on host 'localhost' on table 'wp_users'

Why i am getting this error?


问:
Font-Awesome Icons are not centering on page
I have a div that is a page on my site, and I am trying to center these font-awesome icons on it. But for some reason they wont center. I have searched for a solution but none have worked so far.

Click the "about" button to see what I am talking about.

$(function() {

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

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

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

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

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 2.5em;
    padding: .5em;
    border: 3px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

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

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

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

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

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

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

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

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

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

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

<!DOCTYPE html>

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

    <title>Home</title>

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

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

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

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

```

答:
If you can add a content wrapper inside that #bodyContent div, you can solve it easily with flexbox.

Here is the modified code, I reduced the margin on icons as well, wrapped them inside a div (with a height fitting the container), with items aligned to center, and content justified to center. This will render the icons in the absolute middle of the #bodyContent.

$(function() {

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

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

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

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

.fa-twitter,
.fa-github,
.fa-steam {
  display: inline-block;
  position: relative;
  text-align: center;
  font-size: 2.5em;
  padding: .5em;
  border: 3px solid white;
  margin: 0 2px;
}

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

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

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

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

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

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

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

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

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

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

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

.bodyContent-inside {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}</code>```

<!DOCTYPE html>

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

  <title>Home</title>

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

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

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

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

```

Cheers!

Body:
I have a div that is a page on my site, and I am trying to center these font-awesome icons on it. But for some reason they wont center. I have searched for a solution but none have worked so far.

Click the "about" button to see what I am talking about.

$(function() {

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

});

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

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

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

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 2.5em;
    padding: .5em;
    border: 3px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

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

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

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

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

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

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

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

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

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

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

<!DOCTYPE html>

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

    <title>Home</title>

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

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

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

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

Body:
If you can add a content wrapper inside that #bodyContent div, you can solve it easily with flexbox.

Here is the modified code, I reduced the margin on icons as well, wrapped them inside a div (with a height fitting the container), with items aligned to center, and content justified to center. This will render the icons in the absolute middle of the #bodyContent.

$(function() {

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

});

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

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

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

.fa-twitter,
.fa-github,
.fa-steam {
  display: inline-block;
  position: relative;
  text-align: center;
  font-size: 2.5em;
  padding: .5em;
  border: 3px solid white;
  margin: 0 2px;
}

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

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

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

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

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

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

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

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

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

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

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

.bodyContent-inside {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

<!DOCTYPE html>

<html>

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

  <title>Home</title>

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

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

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

<body>

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

  <div id="bodyContent">
    <div class="bodyContent-inside">
      <i class="fa fa-times" aria-hidden="true"></i>
      <i class="fa fa-twitter" aria-hidden="true"></i>
      <i class="fa fa-github" aria-hidden="true"></i>
      <i class="fa fa-steam" aria-hidden="true"></i>
    </div>
  </div>

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

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

</html>

Cheers!


问:
How to remove a comment using AJAX?
I'm trying to write a comment destroy method to remove comments on a page using Ajax (with no page reload).

Here's what I've tried.

posts/show.html.erb

```<code><% @comments.each do |comment| %>
   <div id="comment_<%= comment.id %>">
      <p><strong><%= comment.user.username %></strong></p>
      <p class="comment"><%= comment.comment %><p>
      <%= link_to "Delete", [@post, comment], method: :delete, remote: true %>
   </div>
<% end %>
</code>```

comments_controller.rb

```<code>def destroy
  @post = Post.find(params[:post_id])
  @comment = Comment.find(params[:id])
  @comment.destroy

  respond_to do |format|
  format.html {redirect_to post_path(id: params[:post_id])}
  format.js
end
</code>```

I'm not sure what else I need but I tried this

posts/destroy.js.erb

```<code>$('#comment_<%= @comment.id %>').remove();
</code>```

Any help is appreciated! According to the server logs, the comment is being removed when I click delete, but the JS is not removing the comment on the front end.

答: Rails will always try to render a view that matches your controller and action names. In your case, since you're destroying the comment in the comments_controller, you must write your js code on the view app/views/comments/destroy.js.erb.

Title: How to remove a comment using AJAX?

Body:
I'm trying to write a comment destroy method to remove comments on a page using Ajax (with no page reload).

Here's what I've tried.

posts/show.html.erb

<% @comments.each do |comment| %>
   <div id="comment_<%= comment.id %>">

<%= comment.user.username %>

<%= comment.comment %>

      <%= link_to "Delete", [@post, comment], method: :delete, remote: true %>

<% end %>

comments_controller.rb

def destroy
  @post = Post.find(params[:post_id])
  @comment = Comment.find(params[:id])
  @comment.destroy

  respond_to do |format|
  format.html {redirect_to post_path(id: params[:post_id])}
  format.js
end

I'm not sure what else I need but I tried this

posts/destroy.js.erb

$('#comment_<%= @comment.id %>').remove();

Any help is appreciated! According to the server logs, the comment is being removed when I click delete, but the JS is not removing the comment on the front end.


问:
SSIS package fails with error "If 64-bit driver not installed, run in 32-bit mode"
I am receiving the following error when trying to run the package from the Integration Services catalog in SSMS. I changed the 64BitRuntime option to FALSE but it still does not work. The error below is followed by an error that a connection cannot be made to my Excel connection manager. Any suggestions?

Package Error: The requested OLE DB provider Microsoft.Jet.OLEDB 4.0
  is not registered. If the 64-bit driver is not installed, run the
  package in 32-bit mode. Error code: 0x00000000

答:
You are attempting to run an SSIS package from the SSISDB catalog and need it to be in 32 bit mode.

The TSQL for such would look like the following

```<code>DECLARE @execution_id bigint;
EXEC SSISDB.catalog.create_execution
    @package_name = N'Legacy_DataExport.dtsx'
,   @execution_id = @execution_id OUTPUT
,   @folder_name = N'Legacy_DataExport'
,   @project_name = N'Legacy_DataExport'
,   @use32bitruntime = True
,   @reference_id = NULL;
SELECT
    @execution_id;
DECLARE @var0 smallint = 1;
EXEC SSISDB.catalog.set_execution_parameter_value
    @execution_id
,   @object_type = 50
,   @parameter_name = N'LOGGING_LEVEL'
,   @parameter_value = @var0;
EXEC SSISDB.catalog.start_execution @execution_id;
GO
</code>```

Of note is the penultimate parameter of the first EXEC where we specify @use32bitruntime = True

That says, please run the package Legacy_DataExport.dtsx which can be found in the project Legacy_DataExport which can be found in the folder Legacy_DataExport using the 32bit runtime.

From the UI perspective, it looks like

The click path within SSMS for this would be

Expand the "Integration Services Catalogs" node under "Management"

Expand the only option there of "SSISDB"

Expand the Folder where your project exists - "Legacy_DataExport" in my case

Expand the "Projects" node

Expand your actual project node - my project is also called "Legacy_DataExport"

Expand "Packages"

Find your package, again my example is "Legacy_DataExport.dtsx", right click it and select Execute...

Body:
You are attempting to run an SSIS package from the SSISDB catalog and need it to be in 32 bit mode.

The TSQL for such would look like the following

DECLARE @execution_id bigint;
EXEC SSISDB.catalog.create_execution
    @package_name = N'Legacy_DataExport.dtsx'
,   @execution_id = @execution_id OUTPUT
,   @folder_name = N'Legacy_DataExport'
,   @project_name = N'Legacy_DataExport'
,   @use32bitruntime = True
,   @reference_id = NULL;
SELECT
    @execution_id;
DECLARE @var0 smallint = 1;
EXEC SSISDB.catalog.set_execution_parameter_value
    @execution_id
,   @object_type = 50
,   @parameter_name = N'LOGGING_LEVEL'
,   @parameter_value = @var0;
EXEC SSISDB.catalog.start_execution @execution_id;
GO

Of note is the penultimate parameter of the first EXEC where we specify @use32bitruntime = True

That says, please run the package Legacy_DataExport.dtsx which can be found in the project Legacy_DataExport which can be found in the folder Legacy_DataExport using the 32bit runtime.

From the UI perspective, it looks like

The click path within SSMS for this would be

Expand the "Integration Services Catalogs" node under "Management"

Expand the only option there of "SSISDB"

Expand the Folder where your project exists - "Legacy_DataExport" in my case

Expand the "Projects" node

Expand your actual project node - my project is also called "Legacy_DataExport"

Expand "Packages"

Find your package, again my example is "Legacy_DataExport.dtsx", right click it and select Execute...


问:
getCanonicalFile and getAbsoluteFile returns the current (project) directory instead of the expected one
I try to make a simple program that contains the function of browsing local file system.

However, I met a problem when the address is directly input.

```<code>public void setWorkingDirectory(File newDir)
{
    try
    {
        //try to eliminate redundancy
        this.workingDir = newDir.getCanonicalFile();
    }
    catch (IOException e)
    {
        this.workingDir = newDir;
    }
}
</code>```

I need the absolute path to display on the screen. So I use getCanonicalFile(). Everything works fine except that when I input "D:" the workingDir will be set to the current project directory in Eclipse (I think it should be the current directory when executed independently, the example is "D:\EclipseWorkspace\workspace\FTPClient") but the File newDir contains exactly the same path ("D:") (I traced it).

If I input "C:" or "D:\", then everything is fine. I couldn't find any information about this on the Internet. Could anyone tell me what's going on here and how to solve the problem?

Thanks in advance.

EDIT: I work on Windows XP SP3 with Java 6 if that matters.

答:
Not really know how to explain it, the getCanonicalFile() uses the getCanonicalPath() which is essentially calls the FileSystem.canonicalize(String path) method (this is an abstract method).

In Windows, the java.io.Win32FileSystem.canonicalize(String path) (which extends java.io.FileSystem) calls, essentially, one of the 2 native methods:

```<code>protected native String canonicalize0(String path)
</code>```

OR

```<code>protected native String canonicalizeWithPrefix0(String canonicalPrefix, String pathWithCanonicalPrefix)
</code>```

So, as Kris says, it's basic Windows function.

Body:
I try to make a simple program that contains the function of browsing local file system.

However, I met a problem when the address is directly input.

public void setWorkingDirectory(File newDir)
{
    try
    {
        //try to eliminate redundancy
        this.workingDir = newDir.getCanonicalFile();
    }
    catch (IOException e)
    {
        this.workingDir = newDir;
    }
}

I need the absolute path to display on the screen. So I use getCanonicalFile(). Everything works fine except that when I input "D:" the workingDir will be set to the current project directory in Eclipse (I think it should be the current directory when executed independently, the example is "D:\EclipseWorkspace\workspace\FTPClient") but the File newDir contains exactly the same path ("D:") (I traced it).

If I input "C:" or "D:\", then everything is fine. I couldn't find any information about this on the Internet. Could anyone tell me what's going on here and how to solve the problem?

Thanks in advance.

EDIT: I work on Windows XP SP3 with Java 6 if that matters.

Body:
Not really know how to explain it, the getCanonicalFile() uses the getCanonicalPath() which is essentially calls the FileSystem.canonicalize(String path) method (this is an abstract method).

In Windows, the java.io.Win32FileSystem.canonicalize(String path) (which extends java.io.FileSystem) calls, essentially, one of the 2 native methods:

protected native String canonicalize0(String path)

OR

protected native String canonicalizeWithPrefix0(String canonicalPrefix, String pathWithCanonicalPrefix)

So, as Kris says, it's basic Windows function.


问:
How to detect input field value change in ng-repeat
I will have N number of input fields and every field will have a value CHANGE without getting in or out of focus. How can I detect value change of every input field.

I only found one question related and using that I tried following but it is not working. can Any one help further

for (var i=0;i<$scope.customers.product.length;i++)
{
//i m trying to get unique ids and bining input fields for change
$('#total-i').on('input', function() {
    alert($(this).val()); // get the current value of the input field.
});
}   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>//there will be multiple of input fields having unique ids
<input id="total-{{$index}}" value={{cust.price*cust.quantity}}"/></code>```

答:
I'd create an object to associate with the ng-model and then watch it. Since you didn't provide a Codepen of fiddle instance to meddle with, I'm not sure this works, check it out.</p>

```<code>//for each index
$.each(modelObject, function(key, value) {
   //set a watcher
   var watchString = "modelObject[" +key + "]";
   $scope.$watch(watchString, function (newValue, oldValue) {
      $scope.update(modelObject[key]);
   });
});
</code>```

Body:
I will have N number of input fields and every field will have a value CHANGE without getting in or out of focus. How can I detect value change of every input field.

I only found one question related and using that I tried following but it is not working. can Any one help further

for (var i=0;i<$scope.customers.product.length;i++)
{
//i m trying to get unique ids and bining input fields for change
$('#total-i').on('input', function() {
    alert($(this).val()); // get the current value of the input field.
});
}

//there will be multiple of input fields having unique ids
<input id="total-{{$index}}" value={{cust.price*cust.quantity}}"/>

Body:
I'd create an object to associate with the ng-model and then watch it. Since you didn't provide a Codepen of fiddle instance to meddle with, I'm not sure this works, check it out.

//for each index
$.each(modelObject, function(key, value) {
   //set a watcher
   var watchString = "modelObject[" +key + "]";
   $scope.$watch(watchString, function (newValue, oldValue) {
      $scope.update(modelObject[key]);
   });
});


问:
Replace last character in sql column
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

```<code>abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test
</code>```

Result should be

```<code>abc
123;ghi;789
test123
thisowns
wer;567;457;test
</code>```

答:
You can do:</p>

```<code>select (case when col like '%;' then left(col, len(col) - 1) else col end)
</code>```

Title: Replace last character in sql column

Body:
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test

Result should be

abc
123;ghi;789
test123
thisowns
wer;567;457;test

Body:
You can do:

select (case when col like '%;' then left(col, len(col) - 1) else col end)


问:
Overriding a component method
I'm using VueCharts which is a Google Charts plugin for vue.

I'm trying to give the newer Material Design looks to the charts. I've tried passing "google.charts.Bar" to chart-type prop and it did work. However, many of the options are ignored because, as stated in the Google Charts docs, the options object needs to be converted by using google.charts.Bar.convertOptions(options), something the plugin doesn't do.

Looking at the source, the plugin installs a 'vue-chart' component. This component uses ChartWrapper to handle loading the chart libraries, like so:

```<code>methods: {
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: options,
        containerId: containerId
      })

      return wrapper
    },
</code>```

So all I need is to override this method to convert the options before passing them to the ChartWrapper.

But how? I haven't found a way to simply override a component method in vue docs. I could create a new component and pass the converted options down, but I need access to the google object, which is only loaded internally by the plugin.

I have also read I could use mixins, but it's not clear how. This doesn't work:

```<code>Vue.component('MyCustomChart', {
    mixins: ['vue-chart'],
    methods: {
        buildWrapper (chartType, dataTable, options, containerId) {
            let wrapper = new google.visualization.ChartWrapper({
                chartType: chartType,
                dataTable: dataTable,
                options: google.charts.Bar.convertOptions(options), // that's all I need
                containerId: containerId
            })

            return wrapper
        },
    }
})
</code>```

[Vue warn]: Failed to mount component: template or render function not defined.
  (found in MyCustomChart)

答:
You can use Vue's extend method to customize plugin components.

In your case:

```<code>import VueCharts from 'vue-charts'
Vue.use(VueCharts);

const Base = Vue.options.components["vue-chart"];
const CustomChart = Base.extend({
  methods: {
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: google.charts.Bar.coverOptions(options),
        containerId: containerId
      })

      return wrapper
    },
  })
}

Vue.component('MyCustomChart', CustomChart);
</code>```

(credit to Bert Evans for noting that you need to reference the base component from Vue.options.components before extending to customize)

Title: Overriding a component method

Body:
I'm using VueCharts which is a Google Charts plugin for vue.

I'm trying to give the newer Material Design looks to the charts. I've tried passing "google.charts.Bar" to chart-type prop and it did work. However, many of the options are ignored because, as stated in the Google Charts docs, the options object needs to be converted by using google.charts.Bar.convertOptions(options), something the plugin doesn't do.

Looking at the source, the plugin installs a 'vue-chart' component. This component uses ChartWrapper to handle loading the chart libraries, like so:

methods: {
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: options,
        containerId: containerId
      })

      return wrapper
    },

So all I need is to override this method to convert the options before passing them to the ChartWrapper.

But how? I haven't found a way to simply override a component method in vue docs. I could create a new component and pass the converted options down, but I need access to the google object, which is only loaded internally by the plugin.

I have also read I could use mixins, but it's not clear how. This doesn't work:

Vue.component('MyCustomChart', {
    mixins: ['vue-chart'],
    methods: {
        buildWrapper (chartType, dataTable, options, containerId) {
            let wrapper = new google.visualization.ChartWrapper({
                chartType: chartType,
                dataTable: dataTable,
                options: google.charts.Bar.convertOptions(options), // that's all I need
                containerId: containerId
            })

            return wrapper
        },
    }
})

[Vue warn]: Failed to mount component: template or render function not defined.
  (found in MyCustomChart)

Body:
You can use Vue's extend method to customize plugin components.

In your case:

import VueCharts from 'vue-charts'
Vue.use(VueCharts);

const Base = Vue.options.components["vue-chart"];
const CustomChart = Base.extend({
  methods: {
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: google.charts.Bar.coverOptions(options),
        containerId: containerId
      })

      return wrapper
    },
  })
}

Vue.component('MyCustomChart', CustomChart);

(credit to Bert Evans for noting that you need to reference the base component from Vue.options.components before extending to customize)


问:
matplotlib scatter plot even x and y throw error that says they are not
While trying to just get basic scatter plot code to work, I ran into the much talked about:

Error:

ValueError: x and y must be the same size.

And yet, the answers I am finding on here do not seem to resolve this one.  Here's the code.  Can anyone spot what I am doing wrong?

The data:

```<code>import pandas as pd
iris = pd.read_csv('../week2/data/iris.csv')
iris.head()
</code>```

produces output like this:

output

Scatter plot code:

```<code>%matplotlib inline
import matplotlib.pyplot as plt

PetalLength = iris['Petal.Length']
PetalWidth = iris['Petal.Width']
plt.rcParams['figure.figsize'] = 8, 6
plt.scatter(iris, PetalWidth, PetalLength)
plt.show
</code>```

I ran this code to look into what the error appeared to be saying but everything looks the same:

```<code>print(PetalWidth.shape, PetalLength.shape)
print(type(PetalWidth), type(PetalLength))
print(len(PetalWidth), len(PetalLength))
</code>```

Above outputs this:

```<code>((150L,), (150L,))
(<type 'numpy.ndarray'>, <type 'numpy.ndarray'>)
(150, 150)
</code>```

Final details in case this helps.  I tried converting PetalWidth and PetalLength to lists based on a Stack Overflow post I found but that did not help either.  Any guidance to help me get this code working would be appreciated.

答:
Comments on this post appear to contain the answer.  While some plot types require a data set to be passed in and then x and y are fields in the data set, scatter takes just x and y arguments where x and y are arrays of equal length that contain the data.  The error is most likely being thrown because the entire data set is being treated as x in your example, and then the second argument (that you thought was x) is being treated as y.  In that comparison, the shape of the whole data set is what is triggering the error.

Delete the first argument (for the data set) and see if the problem goes away.

For others who stumble upon this post in the future, others on Stack Overflow have encountered this error for passing in x and y where x and y were not arrays.  There is even one post where someone fixed the problem by converting x and y to lists, but that is probably not the recommended solution.  Finally, if the arrays, x and y do not contain the same number of values (and hence have the same length), then this error will definitely occur.

Body:
While trying to just get basic scatter plot code to work, I ran into the much talked about:

Error:

ValueError: x and y must be the same size.

And yet, the answers I am finding on here do not seem to resolve this one.  Here's the code.  Can anyone spot what I am doing wrong?

The data:

import pandas as pd
iris = pd.read_csv('../week2/data/iris.csv')
iris.head()

produces output like this:

output

Scatter plot code:

%matplotlib inline
import matplotlib.pyplot as plt

PetalLength = iris['Petal.Length']
PetalWidth = iris['Petal.Width']
plt.rcParams['figure.figsize'] = 8, 6
plt.scatter(iris, PetalWidth, PetalLength)
plt.show

I ran this code to look into what the error appeared to be saying but everything looks the same:

print(PetalWidth.shape, PetalLength.shape)
print(type(PetalWidth), type(PetalLength))
print(len(PetalWidth), len(PetalLength))

Above outputs this:

((150L,), (150L,))
(<type 'numpy.ndarray'>, <type 'numpy.ndarray'>)
(150, 150)

Final details in case this helps.  I tried converting PetalWidth and PetalLength to lists based on a Stack Overflow post I found but that did not help either.  Any guidance to help me get this code working would be appreciated.