问:
Why aren't constants all in upper-case in .Net?
Microsoft naming conventions for .Net put constants in Pascal Case. In fact, it explicitly tells us to avoid using all caps for constants:

You might also have to capitalize
  identifiers to maintain compatibility
  with existing, unmanaged symbol
  schemes, where all uppercase
  characters are often used for
  enumerations and constant values. In
  general, these symbols should not be
  visible outside of the assembly that
  uses them.

From MSDN.

On SO I found some questions on the subject, like this one, but I couldn't find a rationale. So, anyone know or have a reference that points to why MS chose this convention?

答:
Just as a BTW -- EBCDIC is the extended version of BCD (binary coded decimal), and as such certainly supports lower case.  It's the 60s vintage and earlier IBM machines (and others) that did not include lower case.

(And, of course, early home computers like the TRS-80 didn't have lower case, either)


来源: stackexchange

问:
Set Div height Dynamically based on highest content in a div
I have multiple divs in a row. I want to set height dynamically to each div based on the highest content in div. Height should be equal to all divs.
Can you all please help me to solve this with javascript/jquery?

Below is the code:

```<code> <div class="table-cellprop">
  <div class="bottom-pane">
      <div class="content-info">
      <p>some imp text  </p>
      <h3>title </h3>
      <div class="text-left"> some text with info
        <h4>title 2 </h4>
        <ul>
          <li class="bm-list"> li one  </li>
          <li class="cm-list"> two </li>
          <li class="mm-list"> three </li>
        </ul>
         </div>
    </div>
  </div>
</div>

<div class="table-cellprop card-btm">
  <div class="bottom-pane">

    <div class="content-info"> TextTextTextTextTextTextTextTextTextTextTextText </div>

  </div>

</div>

<div class="table-cellprop card-btm">
  <div class="bottom-pane">

    <div class="content-info"> TextTextTextText </div>

  </div>

</div>
</code>```

答:
You don't actually need javascript. You can use flexbox.

.flex-container {
  display: flex;
  flex-direction: row;
}

.table-cellprop {
  flex: 1;
  overflow: auto;
}

.table-cellprop:nth-child(1) {
  background-color: #b9f6ca;
}
.table-cellprop:nth-child(2) {
  background-color: #84ffff;
}
.table-cellprop:nth-child(3) {
  background-color: #b388ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
<div class="table-cellprop">
  <div class="bottom-pane">
      <div class="content-info">
      <p>some imp text  </p>
      <h3>title </h3>
      <div class="text-left"> some text with info
        <h4>title 2 </h4>
        <ul>
          <li class="bm-list"> li one  </li>
          <li class="cm-list"> two </li>
          <li class="mm-list"> three </li>
        </ul>
         </div>
    </div>
  </div>
</div>

<div class="table-cellprop card-btm">
  <div class="bottom-pane">

    <div class="content-info"> TextTextTextTextTextTextTextTextTextTextTextText </div>

  </div>

</div>

<div class="table-cellprop card-btm">
  <div class="bottom-pane">

    <div class="content-info"> TextTextTextText </div>

  </div>

</div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have multiple divs in a row. I want to set height dynamically to each div based on the highest content in div. Height should be equal to all divs.
Can you all please help me to solve this with javascript/jquery?

Below is the code:

some imp text

title

 some text with info

title 2

 li one

 two

 three

 TextTextTextTextTextTextTextTextTextTextTextText

 TextTextTextText

Body:
You don't actually need javascript. You can use flexbox.

.flex-container {
  display: flex;
  flex-direction: row;
}

.table-cellprop {
  flex: 1;
  overflow: auto;
}

.table-cellprop:nth-child(1) {
  background-color: #b9f6ca;
}
.table-cellprop:nth-child(2) {
  background-color: #84ffff;
}
.table-cellprop:nth-child(3) {
  background-color: #b388ff;
}

<div class="flex-container">
<div class="table-cellprop">
  <div class="bottom-pane">
      <div class="content-info">
      <p>some imp text  </p>
      <h3>title </h3>
      <div class="text-left"> some text with info
        <h4>title 2 </h4>
        <ul>
          <li class="bm-list"> li one  </li>
          <li class="cm-list"> two </li>
          <li class="mm-list"> three </li>
        </ul>
         </div>
    </div>
  </div>
</div>

<div class="table-cellprop card-btm">
  <div class="bottom-pane">

    <div class="content-info"> TextTextTextTextTextTextTextTextTextTextTextText </div>

  </div>

</div>

<div class="table-cellprop card-btm">
  <div class="bottom-pane">

    <div class="content-info"> TextTextTextText </div>

  </div>

</div>
</div>


问:
How do I get the duration of a video file using C#?
Any library in C# that allows me to do that?</p>

答:
I hope following code snippet will help you :

```<code>using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));
</code>```

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.

ContentLicense: CC BY-SA 2.5

Body:
I hope following code snippet will help you :

using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.


问:
How to setState in child component when child function called from parent component in ReactJS
I want to call child function from parent component so I found a question here

Call child method from parent

So I used this way to to called it (From 1st Answer and 2nd approach).

Now issue is how to set state in the child getAlert function

```<code>class Parent extends Component {
  render() {
    return (
      <div>
        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>
      </div>
    );
  }
}

class Child extends Component {
  constructor(){
     super();
     this.state = {message:""};
  }

  getAlert() {
    alert('clicked');
    //HERE I NEED TO SETSTATE
  }

  render() {
    return (
      {this.state.message!=""?(
         <h1>{this.state.message}</h1>

      ):(

      <h1>Hello</h1>

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

In the getAlert function of child I need to setState but I couldn't able to do it. Please provide any solution

答:
class Parent extends React.Component {
  render() {
    return (

        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>

    );
  }
}

class Child extends React.Component {
  constructor(){
  super()
  this.state = {
    message: 'google'
  }
  this.getAlert = this.getAlert.bind(this)
  }

  getAlert() {
    alert('clicked');
    this.setState ({
      message: 'yahoo'
    }, () => {
      console.log(this.state.message) //the state value will be printed
    });
  }

  render() {
  console.log(this.state.message)
    return (

Hello {this.state.message}

    );
  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div></code>```

you have bind the getAlert() method to scope of the class ie). 'this'.  I have added an sample code..pls check

Body:
I want to call child function from parent component so I found a question here

Call child method from parent

So I used this way to to called it (From 1st Answer and 2nd approach).

Now issue is how to set state in the child getAlert function

class Parent extends Component {
  render() {
    return (

        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>

    );
  }
}

class Child extends Component {
  constructor(){
     super();
     this.state = {message:""};
  }

  getAlert() {
    alert('clicked');
    //HERE I NEED TO SETSTATE
  }

  render() {
    return (
      {this.state.message!=""?(

{this.state.message}

      ):(

Hello

      )}
    );
  }
}

In the getAlert function of child I need to setState but I couldn't able to do it. Please provide any solution

Body:
class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>
      </div>
    );
  }
}

class Child extends React.Component {
  constructor(){
  super()
  this.state = {
    message: 'google'
  }
  this.getAlert = this.getAlert.bind(this)
  }

  getAlert() {
    alert('clicked');
    this.setState ({
      message: 'yahoo'
    }, () => {
      console.log(this.state.message) //the state value will be printed
    });
  }

  render() {
  console.log(this.state.message)
    return (
      <h1>Hello {this.state.message}</h1>
    );
  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

you have bind the getAlert() method to scope of the class ie). 'this'.  I have added an sample code..pls check


问:
Cyclically mapping flat arrays of different sizes and summing the values
I have an issue with two arrays that I need to combine, where the first array contains a list of campaign names ( page_data ) like

```<code>[
    "Campaign 1",
    "Campaign 2",
    "Campaign 3"
]
</code>```

and another array that contains number of leads for the campaigns. But this array will contain twice as many keys as the campaign array like this:

```<code>[
    222,
    342,
    71,
    33,
    43,
    665
]
</code>```

It contains twice as many keys, because it will take leads from two different forms, so the values for key 0 and key 3 will be for campaign 1 and key 2 and key 4 will be for campaign 2. It will always be this way. If there are 5 campaigns, leads array will have 10 keys and key 0 and key 5 will be for campaign one, key 1 an key 6 for campaign 2, etc.

And then I have this piece of code to combine ( push ):

```<code>foreach (json_decode($result) as $key) {
   foreach ($pages["page_data"] as $p => $pvalue) {
       array_push(
           $leadArray,
           array(
               "pageName" => $pvalue["form_name"],
               "pageLeads" => $key[$p]
           )
       );
    }
}
</code>```

That will incorrectly make an array that looks something like:

```<code>[
    "campaign 1" => 222,
    "campaign 2" => 342,
    "campaign 3" => 71
]
</code>```

But that will only take keys 0,1,2 and so key 3,4,5 will not be in the array.

What I want is key 0 and key 3, key 1 and key 4, etc. in the leads array to be combined so the the new leads array will be

```<code>[
    255,
    386,
    736
]
</code>```

which I can then combine with the campaigns array as the number of keys from the two arrays will now match which will give me an array that looks like

```<code>[
    "campaign 1" => 255,
    "campaign 2" => 386,
    "campaign 3" => 736
]
</code>```

答:
Use array_chunk function for split your second array and it will be easy to sum values.

When you use this function, your array will splitted into two arrays. In first array you will have values 0, 1, 2, and in second you will have 3, 4, 5 values. Now iterate through your first array, using keys you will have access to value pairs: 0-3, 1-4, 2-5.

Check out this code:

```<code><?php

$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [0 => 222, 1 => 342, 2 => 71, 3 => 33, 4 => 43, 5 => 665];

$chunkedArray2 = array_chunk($array2, count($array1), false);

$result = [];
foreach($array1 as $key => $value) {
    $result[$value] = $chunkedArray2[0][$key] + $chunkedArray2[1][$key];
}

var_dump($result);
</code>```

And result is:

```<code>Array
(
    [Campaign 1] => 255
    [Campaign 2] => 385
    [Campaign 3] => 736
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an issue with two arrays that I need to combine, where the first array contains a list of campaign names ( page_data ) like

[
    "Campaign 1",
    "Campaign 2",
    "Campaign 3"
]

and another array that contains number of leads for the campaigns. But this array will contain twice as many keys as the campaign array like this:

[
    222,
    342,
    71,
    33,
    43,
    665
]

It contains twice as many keys, because it will take leads from two different forms, so the values for key 0 and key 3 will be for campaign 1 and key 2 and key 4 will be for campaign 2. It will always be this way. If there are 5 campaigns, leads array will have 10 keys and key 0 and key 5 will be for campaign one, key 1 an key 6 for campaign 2, etc.

And then I have this piece of code to combine ( push ):

foreach (json_decode($result) as $key) {
   foreach ($pages["page_data"] as $p => $pvalue) {
       array_push(
           $leadArray,
           array(
               "pageName" => $pvalue["form_name"],
               "pageLeads" => $key[$p]
           )
       );
    }
}

That will incorrectly make an array that looks something like:

[
    "campaign 1" => 222,
    "campaign 2" => 342,
    "campaign 3" => 71
]

But that will only take keys 0,1,2 and so key 3,4,5 will not be in the array.

What I want is key 0 and key 3, key 1 and key 4, etc. in the leads array to be combined so the the new leads array will be

[
    255,
    386,
    736
]

which I can then combine with the campaigns array as the number of keys from the two arrays will now match which will give me an array that looks like

[
    "campaign 1" => 255,
    "campaign 2" => 386,
    "campaign 3" => 736
]

Body:
Use array_chunk function for split your second array and it will be easy to sum values.

When you use this function, your array will splitted into two arrays. In first array you will have values 0, 1, 2, and in second you will have 3, 4, 5 values. Now iterate through your first array, using keys you will have access to value pairs: 0-3, 1-4, 2-5.

Check out this code:

<?php

$array1 = [0 => "Campaign 1", 1 => "Campaign 2", 2 => "Campaign 3"];
$array2 = [0 => 222, 1 => 342, 2 => 71, 3 => 33, 4 => 43, 5 => 665];

$chunkedArray2 = array_chunk($array2, count($array1), false);

$result = [];
foreach($array1 as $key => $value) {
    $result[$value] = $chunkedArray2[0][$key] + $chunkedArray2[1][$key];
}

var_dump($result);

And result is:

Array
(
    [Campaign 1] => 255
    [Campaign 2] => 385
    [Campaign 3] => 736
)


问:
Rails: Sidekiq Workers must be thread-safe. What Does it mean?
I read this about Sidekiq:

Sidekiq is multithreaded so your Workers must be thread-safe.

What does it mean? What is 'thread-safe' code? Can someone make example about that? Thank you very much.

答:
There are a lot of possible ways to get non-thread safe code. Here is one example of the non-thread safe code:

```<code># shared resource
$resource = StringIO.new

class NonThreadSafeWorker
  include Sidekiq::Worker

  def perform(_)
    random_letter = ('a'..'z').to_a.sample
    # concurrency problem: data race
    100_000.times do
      $resource.write random_letter
    end
  end
end

# Suppose you run 2 workers, result might be the next: "aaaabbabbabba..."
</code>```

and it's thread safe complement:

```<code>require 'thread'

mutex = Mutex.new

class ThreadSafeWorker
  include Sidekiq::Worker

  def perform(_)
    random_letter = ('a'..'z').to_a.sample
    mutex.synchronize do
      # synchronize access to shared resource
      100_000.times do
        $resource.write random_letter
      end
    end
  end
end

# Suppose you run 2 workers, result must be the next: "aaaaaaa...bbbbbb..."
</code>```

Pay attention, MRI GIL forces execution of the only one thread in a time at interpreter level. But that doesn't mean you will not meet concurrent issues similar to described above. JRuby and Rubinius are "true" concurrent execution environments, but less common, exactly because many libraries (including standard) should be rewritten with thread-safe in mind.

Sidekiq doesn't responsible of the libraries you are going to use inside the worker, but it gracefully cautious you to understand consequences of using non-thread safe libraries.

Body:
There are a lot of possible ways to get non-thread safe code. Here is one example of the non-thread safe code:

# shared resource
$resource = StringIO.new

class NonThreadSafeWorker
  include Sidekiq::Worker

  def perform(_)
    random_letter = ('a'..'z').to_a.sample
    # concurrency problem: data race
    100_000.times do
      $resource.write random_letter
    end
  end
end

# Suppose you run 2 workers, result might be the next: "aaaabbabbabba..."

and it's thread safe complement:

require 'thread'

mutex = Mutex.new

class ThreadSafeWorker
  include Sidekiq::Worker

  def perform(_)
    random_letter = ('a'..'z').to_a.sample
    mutex.synchronize do
      # synchronize access to shared resource
      100_000.times do
        $resource.write random_letter
      end
    end
  end
end

# Suppose you run 2 workers, result must be the next: "aaaaaaa...bbbbbb..."

Pay attention, MRI GIL forces execution of the only one thread in a time at interpreter level. But that doesn't mean you will not meet concurrent issues similar to described above. JRuby and Rubinius are "true" concurrent execution environments, but less common, exactly because many libraries (including standard) should be rewritten with thread-safe in mind.

Sidekiq doesn't responsible of the libraries you are going to use inside the worker, but it gracefully cautious you to understand consequences of using non-thread safe libraries.


问:
Uncheck checkbox in React pop up
I want to uncheck all the checkboxes everytime the popup shows. Have written a function for it which it getting called on click of the popup show button but the previously checked checkboxes are still remaining checked. In the popup i have ul with li's that are generated by mapping.

My function is:

```<code>clearList() {
    var list_items = document.getElementById("bucket-list").getElementsByTagName("li");
    for(var i=0; i<list_items.length; i++) {
      list_items[i].getElementsByTagName("input").checked = false;
    }
  }
</code>```

Inside render function:

```<code><ul id="bucket-list">
              {this.state.buckets.map(function (bucket, i) {
                return (
                <li key={i}>
                  <input
                    type="checkbox"
                    value={bucket.id}
                    refs="status_changed"
                    onChange={self.onCheckUncheck.bind(self, "status_changed")} />
                  <label>{bucket.name}</label>
                </li>
                )
              })}
              </ul>
</code>```

答:
well since you are buckets array to provide the checkbox props then you can add the you can add the checked property to this array, and whenever you want to clear, you only modify this property to false,
for your convenience use some checkbox library such as react-icheck, install it using npm install --save react-icheck for instance,
import it to your file : import {Checkbox} from 'react-icheck'
now add the checked prop to your buckets array, checked:false ,
and replace your code with something similar:

```<code>         <ul>
          {this.state.buckets.map(function (bucket, i) {
            return (
            <li key={i}>
              <Checkbox
                increaseArea="20%"
                label={bucket.name}
                name={bucket.id}
                onChange={this.handleBucketCheckChange}
                checked={bucket.checked}/>
            </li>
            )
          })}
          </ul>
</code>```

and to clear the checkboxes:

```<code>clearList() {
 let localBucketsArray = [...this.state.buckets];

 map(localBucketsArray, function(bucket,key){
  bucket.checked = false;
 })

  this.setState({buckets: localBuckets})
  }
</code>```

Title: Uncheck checkbox in React pop up

Body:
I want to uncheck all the checkboxes everytime the popup shows. Have written a function for it which it getting called on click of the popup show button but the previously checked checkboxes are still remaining checked. In the popup i have ul with li's that are generated by mapping.

My function is:

clearList() {
    var list_items = document.getElementById("bucket-list").getElementsByTagName("li");
    for(var i=0; i<list_items.length; i++) {
      list_items[i].getElementsByTagName("input").checked = false;
    }
  }

Inside render function:

              {this.state.buckets.map(function (bucket, i) {
                return (

                  <input
                    type="checkbox"
                    value={bucket.id}
                    refs="status_changed"
                    onChange={self.onCheckUncheck.bind(self, "status_changed")} />
                  {bucket.name}

                )
              })}

Body:
well since you are buckets array to provide the checkbox props then you can add the you can add the checked property to this array, and whenever you want to clear, you only modify this property to false,
for your convenience use some checkbox library such as react-icheck, install it using npm install --save react-icheck for instance,
import it to your file : import {Checkbox} from 'react-icheck'
now add the checked prop to your buckets array, checked:false ,
and replace your code with something similar:

         <ul>
          {this.state.buckets.map(function (bucket, i) {
            return (
            <li key={i}>
              <Checkbox
                increaseArea="20%"
                label={bucket.name}
                name={bucket.id}
                onChange={this.handleBucketCheckChange}
                checked={bucket.checked}/>
            </li>
            )
          })}
          </ul>

and to clear the checkboxes:

clearList() {
 let localBucketsArray = [...this.state.buckets];

 map(localBucketsArray, function(bucket,key){
  bucket.checked = false;
 })

  this.setState({buckets: localBuckets})
  }


问:
Crop image via finger(touch) in Ionic App
I am Working on ionic based Application.My ionic app version is 1.2.4. I want to Crop Functionality in my application. I want to crop image Via Touch with irregular Shape. So anyone has Create touch cropper So plz help me.

For more clearly, look at below gif what I want.

Last 2 day I'm googling to find the solution and found that it's easy to do simple crop or square or rectangular crop but not getting crop image by touch.

If anybody has done it then suggest me in the right direction.

答:
You need

import { CropPlugin } from 'ionic-native';

You can look at https://github.com/alexk111/ngImgCrop and https://github.com/jeduan/cordova-plugin-crop


问:
Retrieve the instance created by class_based_view
Django documentation specify as_view method in
class-based-views

as_view() class method creates an instance of the class and calls its dispatch() method.

I attempt to print the instance.
 For illustration:

```<code> # urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
    url(r'^about/$', MyView.as_view()),
]

#views.py
from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')
</code>```

I added a print statement to views.py:

```<code>class MyView(View):
    print(self)
    def get(self, request):
        # <view logic>
        return HttpResponse('result')
</code>```

It reports NameError.

How can I print the instance created by class 'View'?

答:
You can use __repr__ or __str__ method of the view (those methods are by default inherited by every python class). There are 2 options:

Get the representation (__repr__ do you get it yet? :D) every time a REST method gets called:

```<code>class MyView(View):
    def get(self, request):
        # <view logic>
        print(self.__repr__())
        return HttpResponse(result)
</code>```

or return it in the HttpResponse:

```<code>class MyView(View):
    def get(self, request):
        # <view logic>
        result['self_repr'] = self.__repr__()
        return HttpResponse(result)
</code>```

Get the representation of the class each time it gets instantiated:

```<code>class MyView(View):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print(self.__repr__())
</code>```

The end result though will be something like this:

```<code><my_app.views.MyView object at 0x7f63b5e05668>
</code>```

which is not very helpful. You can override the __str__() method to return something more specific but that is up to you!

Body:
Django documentation specify as_view method in
class-based-views

as_view() class method creates an instance of the class and calls its dispatch() method.

I attempt to print the instance.
 For illustration:

 # urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
    url(r'^about/$', MyView.as_view()),
]

#views.py
from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')

I added a print statement to views.py:

class MyView(View):
    print(self)
    def get(self, request):
        # <view logic>
        return HttpResponse('result')

It reports NameError.

How can I print the instance created by class 'View'?

Body:
You can use __repr__ or __str__ method of the view (those methods are by default inherited by every python class). There are 2 options:

Get the representation (__repr__ do you get it yet? :D) every time a REST method gets called:

class MyView(View):
    def get(self, request):
        # <view logic>
        print(self.__repr__())
        return HttpResponse(result)

or return it in the HttpResponse:

class MyView(View):
    def get(self, request):
        # <view logic>
        result['self_repr'] = self.__repr__()
        return HttpResponse(result)

Get the representation of the class each time it gets instantiated:

class MyView(View):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print(self.__repr__())

The end result though will be something like this:

<my_app.views.MyView object at 0x7f63b5e05668>

which is not very helpful. You can override the __str__() method to return something more specific but that is up to you!


答:
The problem seems to be that when calling setState inside the getAlert function of child, this.setState will come undefined. This happens because this inside your getAlert function doesn't refer to the context of the React Component and setState is defined for the Component. You can solve this by binding the getAlert function.

You can do it in two ways.

First: using .bind(this) in constructor

```<code>class Child extends Component {

  constructor() {
     super();
     this.getAlert = this.getAlert.bind(this);
  }
  getAlert() {
    alert('clicked');
    //HERE I NEED TO SETSTATE
  }

  render() {
    return (
      <h1>Hello</h1>
    );
  }
}
</code>```

Second: use Arrow function

```<code>getAlert = ()  => {
    alert('clicked');
    //HERE I NEED TO SETSTATE
  }
</code>```

Check this answer on Why do we need to bind React functions

Check the working snippet

class Parent extends React.Component {
  render() {
    return (

        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>

    );
  }
}

class Child extends React.Component {
  constructor(){
     super();
     this.state = {message:""};
  }

  getAlert = () => {
    alert('clicked');
    this.setState({message: "somemessage"});
  }

  render() {
    return (

{this.state.message!=""?(

{this.state.message}

      ):(

Hello

      )}

    );
  }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/></code>```

Title: How to setState in child component when child function called from parent component in ReactJS

Body:
The problem seems to be that when calling setState inside the getAlert function of child, this.setState will come undefined. This happens because this inside your getAlert function doesn't refer to the context of the React Component and setState is defined for the Component. You can solve this by binding the getAlert function.

You can do it in two ways.

First: using .bind(this) in constructor

class Child extends Component {

  constructor() {
     super();
     this.getAlert = this.getAlert.bind(this);
  }
  getAlert() {
    alert('clicked');
    //HERE I NEED TO SETSTATE
  }

  render() {
    return (
      <h1>Hello</h1>
    );
  }
}

Second: use Arrow function

getAlert = ()  => {
    alert('clicked');
    //HERE I NEED TO SETSTATE
  }

Check this answer on Why do we need to bind React functions

Check the working snippet

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>
      </div>
    );
  }
}

class Child extends React.Component {
  constructor(){
     super();
     this.state = {message:""};
  }

  getAlert = () => {
    alert('clicked');
    this.setState({message: "somemessage"});
  }

  render() {
    return (
      <div>{this.state.message!=""?(
         <h1>{this.state.message}</h1>

      ):(

      <h1>Hello</h1>

      )}</div>
    );
  }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>


问:
Calculating player rank based on games played
I need to display a chart where can show game, score, all-time rank, weekly rank, rank with friends.

I have two tables:

1) high_scores (playerid, gameid, score, time(timestamp))

2) friends (playerid, friendid)

I was wondering how I can do so using the minimum number of queries.

I'm using PHP & MySQL for my game site.

答:
could manage to make query for it as follow:

```<code>SELECT
    gamescores.gameid,
    COUNT(*)+1 AS rank,
    playergamescores.total,
    gamename,
    foldername
FROM (
    SELECT gameid, playerid, SUM( score ) AS total, time
    FROM high_scores
    GROUP BY gameid, playerid
    ORDER BY gameid, total DESC
) AS gamescores
INNER JOIN
(
    SELECT gameid, SUM(score) AS total
    FROM high_scores
    WHERE playerid = 361822
    GROUP BY gameid
    ORDER BY total DESC
) AS playergamescores
ON playergamescores.gameid = gamescores.gameid
INNER JOIN gamemaster
ON gamescores.gameid = gamemaster.gameid
WHERE gamescores.total > (
    SELECT SUM( score ) AS total
    FROM high_scores
    WHERE gamescores.gameid = gameid
    AND playerid = 361822
)
GROUP BY gamescores.gameid
ORDER BY gamescores.time DESC
</code>```

Thanks for answering anyway...
-Navi

Body:
could manage to make query for it as follow:

SELECT
    gamescores.gameid,
    COUNT(*)+1 AS rank,
    playergamescores.total,
    gamename,
    foldername
FROM (
    SELECT gameid, playerid, SUM( score ) AS total, time
    FROM high_scores
    GROUP BY gameid, playerid
    ORDER BY gameid, total DESC
) AS gamescores
INNER JOIN
(
    SELECT gameid, SUM(score) AS total
    FROM high_scores
    WHERE playerid = 361822
    GROUP BY gameid
    ORDER BY total DESC
) AS playergamescores
ON playergamescores.gameid = gamescores.gameid
INNER JOIN gamemaster
ON gamescores.gameid = gamemaster.gameid
WHERE gamescores.total > (
    SELECT SUM( score ) AS total
    FROM high_scores
    WHERE gamescores.gameid = gameid
    AND playerid = 361822
)
GROUP BY gamescores.gameid
ORDER BY gamescores.time DESC

Thanks for answering anyway...
-Navi


问:
Robolectric Creating Dummy SharedPreferences of a Different Application
I have searched through posts here as well as Google for a solution to a problem that I am having with doing unit tests using Robolectric. One thing that I need to test involves looking up the shared preferences file that resides within another application. So, I don't need to generate/create/lookup the shared preferences file on the activity I am testing, I need the shared preferences file that resides in a different application. So, I need to trick the environment by thinking that this file exists for that application. So TLDR

App1 performing unit tests on

App1 accesses SharedPreferences of App2

Need to generate fake SharedPreferneces file of App2 so App1 can access and continue on with tests. Any help is appreciated. Thank you!.

答:
I would first rework the code to achieve next:

You have a class that works with any SharedPreferences file

You have a class that opens/copy file for another application

You have a class that orchestrate this by providing output of file reading class to shared preference processor class

And then the unit test would look like:

Check if shared preferences class does required operations

Check that class that copies/reads file from one location to another
3a. Check that orchestrator class pass correct paths to file operations class
3b. Check that orchestrator class pass result (stream, string, etc) to shared preferences class

Hope it helps!


问:
use SOAP for laravel authentication
I am using a SOAP interface as a way of dealing with data on a legacy system. I need to validate users using the information in this system.  I found the following as part of a Laravel (5.,4) installation

app\config\auth.php

```<code>| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
</code>```

I made a demo of SOAP working in Laravel (so it data does fetch from then needed table). I used this: https://github.com/artisaninweb/laravel-soap  It seems to work so far ...

For the authentication system, what changes do I need to make in Laravel so that it will recognize a rows retrieved from SOAP and not a row fetched from the DB?
TIA

答:
Try this package http://github.com/ACFBentveld/Soap it is much easier to use and mostly faster. For your auth you have to create a new provider. In the Auth config you can define which providers laravel uses to authenticate users.

For more information see

https://laravel.com/docs/5.4/authentication#adding-custom-user-providers
https://devmarketer.io/learn/setting-multi-authentication-laravel-5-4-part-1/

Title: use SOAP for laravel authentication

Body:
I am using a SOAP interface as a way of dealing with data on a legacy system. I need to validate users using the information in this system.  I found the following as part of a Laravel (5.,4) installation

app\config\auth.php

| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.

I made a demo of SOAP working in Laravel (so it data does fetch from then needed table). I used this: https://github.com/artisaninweb/laravel-soap  It seems to work so far ...

For the authentication system, what changes do I need to make in Laravel so that it will recognize a rows retrieved from SOAP and not a row fetched from the DB?
TIA


问:
Replace Opencv Fillpoly functions with Halide Funcs
I'm trying to realize some opencv functions by Halide, one of the difficulty I have met is how to write the cv::fillpoly in Halide. This function, in opencv,  fills a polygon according to the given vertex of this polygon. The details in Opencv: https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html

I wonder if it's possible to realize it in Halide?

答: It is possible, but likely difficult and not obviously productive as polygon rendering does not have a regular static data parallel pattern and is already really well optimized in various places. It would be interesting to see if it can be done and made performant but it is a lot of work and isn't obviously going to be as fast or faster than existing graphics libraries. Especially if running on GPU hardware where it has to compete with hardware rasterization. I'd look into using define_extern to call out to existing rendering routines.


问:
Drupal 8 disable template (page & node) cache
I have tried several articles to disable the page and template cache in Drupal 8.  I am not using drush and find it very annoying I have to manually clear the cache after every change.

sites/default/default.services.yaml

List item

debug: true

cache: false

auto_reload: true

create sites/settings.php & sites/settings.local.php

$config['system.performance']['css']['preprocess'] = FALSE;

$config['system.performance']['js']['preprocess'] = FALSE;

$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

$settings['cache']['bins']['page'] = 'cache.backend.null';

in development.services.yml add the following

```<code>    1. twig.config:
        debug: true
        auto_reload: true
        cache: false
</code>```

Rebuild the cache

http://yoursite/core/rebuild.php or drush cr

Disable cache in configuration -> performance

Be sure to disable dev tools cache

If I make an adjustment to page.html.twig nothing happens til I clear the cache, any other ideas would be great. This would be the latest version of Drupal 8

答:
Good day!
Try to add in you yml file:

```<code>services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
</code>```

Hope it will help you!

Body:
I have tried several articles to disable the page and template cache in Drupal 8.  I am not using drush and find it very annoying I have to manually clear the cache after every change.

sites/default/default.services.yaml

List item

debug: true

cache: false

auto_reload: true

create sites/settings.php & sites/settings.local.php

$config['system.performance']['css']['preprocess'] = FALSE;

$config['system.performance']['js']['preprocess'] = FALSE;

$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

$settings['cache']['bins']['page'] = 'cache.backend.null';

in development.services.yml add the following

    1. twig.config:
        debug: true
        auto_reload: true
        cache: false

Rebuild the cache

http://yoursite/core/rebuild.php or drush cr

Disable cache in configuration -> performance

Be sure to disable dev tools cache

If I make an adjustment to page.html.twig nothing happens til I clear the cache, any other ideas would be great. This would be the latest version of Drupal 8

Body:
Good day!
Try to add in you yml file:

services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

Hope it will help you!


问:
How do I strip down a URL into separate parts in Bash?
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

```<code>URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)
</code>```

答:
```<code>#!/bin/bash

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | awk -F'/' '{print $1FS$2FS$3}')
USER=$(echo ${URL} | awk -F'/' '{print $4}')
THING=$(echo ${URL} | awk -F'/' '{print $5}')

echo $DOMAIN $USER $THING
</code>```

output:

```<code>https://example.com someone something
</code>```

Body:
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)

Body:
#!/bin/bash

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | awk -F'/' '{print $1FS$2FS$3}')
USER=$(echo ${URL} | awk -F'/' '{print $4}')
THING=$(echo ${URL} | awk -F'/' '{print $5}')

echo $DOMAIN $USER $THING

output:

https://example.com someone something


问:
Convert ArrayList to Double Array in java
How to Convert ArrayList to Double Array in Java6?

```<code> List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);
</code>```

How convert above list to array?

答:
With this you will make the list and add what you like. Then make the array the same size and fill front to back.

```<code>public static void main(String[] args){
        List lst = new ArrayList();
        lst.add(343.34);
        lst.add(432.34);
        System.out.println("LST " + lst);

        double[] dbl= new double[lst.size()];
        int iter = 0;
        for (Object d: lst
             ) {
            double e = (double) d;
            dbl[iter++] = e;
        }
        System.out.println("DBL " + Arrays.toString(dbl));
    }
</code>```

Result: LST [343.34,432.34] DBL [343.34,432.34]

Body:
How to Convert ArrayList to Double Array in Java6?

 List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);

How convert above list to array?

Body:
With this you will make the list and add what you like. Then make the array the same size and fill front to back.

public static void main(String[] args){
        List lst = new ArrayList();
        lst.add(343.34);
        lst.add(432.34);
        System.out.println("LST " + lst);

        double[] dbl= new double[lst.size()];
        int iter = 0;
        for (Object d: lst
             ) {
            double e = (double) d;
            dbl[iter++] = e;
        }
        System.out.println("DBL " + Arrays.toString(dbl));
    }

Result: LST [343.34,432.34] DBL [343.34,432.34]


问:
Accessing Spring beans in JerseyTest
I'm trying to figure out how to access Spring beans from a subclass of JerseyTest.
Extending JerseyTest I've managed to load the Spring context in my tests, but I haven't figured out how to access the spring context. My setup looks like this:

```<code>public abstract class SpringJerseyTest extends JerseyTest {
    public SpringJerseyTest() throws Exception {
        super(new WebAppDescriptor.Builder("com.acme.resources")
            .contextPath("/")
            .contextParam("contextConfigLocation", "classpath:applicationContext.xml")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .build());
    }

}
</code>```

The setup is using the default Grizzly Web Container. I've never used Grizzly before, but in Jetty I would do something like this:

```<code>    public Object getSpringBean(String beanName) {
        WebAppContext context = (WebAppContext) server.getHandler();
        ServletContext sc = context.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
        return applicationContext.getBean(beanName);
    }
</code>```

Could anyone point me in the right direction?

答: Been using the solution described here for a week, and it's working fine. </p>

Title: Accessing Spring beans in JerseyTest

Body:
I'm trying to figure out how to access Spring beans from a subclass of JerseyTest.
Extending JerseyTest I've managed to load the Spring context in my tests, but I haven't figured out how to access the spring context. My setup looks like this:

public abstract class SpringJerseyTest extends JerseyTest {
    public SpringJerseyTest() throws Exception {
        super(new WebAppDescriptor.Builder("com.acme.resources")
            .contextPath("/")
            .contextParam("contextConfigLocation", "classpath:applicationContext.xml")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .build());
    }

}

The setup is using the default Grizzly Web Container. I've never used Grizzly before, but in Jetty I would do something like this:

    public Object getSpringBean(String beanName) {
        WebAppContext context = (WebAppContext) server.getHandler();
        ServletContext sc = context.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
        return applicationContext.getBean(beanName);
    }

Could anyone point me in the right direction?


问:
How to click on handle Chrome's "save as" dialog using Java in LeanFT Tool?
Using LeanFT's Java SDK, is it possible to perform click operation on "Save" button from Chrome's "Save As" dialog?</p>

答:
Have you tried to use the Object Identification Tool to identify the Save button?

In any case, I understand you are now working with Web technology, then you click on a Save button, which then prompts you to save the file in a location.

You have two options:

Set Chrome to no longer ask where to save files;

Describe the Save button that you want to Click using the STD technology.

Example of such description:

```<code>Desktop.describe(Window.class, new WindowDescription.Builder()
        .ownedWindow(false)
        .childWindow(false)
        .windowClassRegExp("Chrome_WidgetWin_1")
        .windowTitleRegExp(" Google Chrome").build())
    .describe(Dialog.class, new DialogDescription.Builder()
        .ownedWindow(true)
        .childWindow(false)
        .text("Save As")
        .nativeClass("#32770").build())
    .describe(Button.class, new ButtonDescription.Builder()
        .text("&Save")
        .nativeClass("Button").build());
</code>```

Then you can call the .click method on this object (or cancel, or so on).

Body:
Have you tried to use the Object Identification Tool to identify the Save button?

In any case, I understand you are now working with Web technology, then you click on a Save button, which then prompts you to save the file in a location.

You have two options:

Set Chrome to no longer ask where to save files;

Describe the Save button that you want to Click using the STD technology.

Example of such description:

Desktop.describe(Window.class, new WindowDescription.Builder()
        .ownedWindow(false)
        .childWindow(false)
        .windowClassRegExp("Chrome_WidgetWin_1")
        .windowTitleRegExp(" Google Chrome").build())
    .describe(Dialog.class, new DialogDescription.Builder()
        .ownedWindow(true)
        .childWindow(false)
        .text("Save As")
        .nativeClass("#32770").build())
    .describe(Button.class, new ButtonDescription.Builder()
        .text("&Save")
        .nativeClass("Button").build());

Then you can call the .click method on this object (or cancel, or so on).


问:
Converting string with time to minutes
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

```<code>str = str.replaceAll("[^\\d.]", "");
</code>```

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

答:
If you can get each minute and hours separately you can use string.replace("mins", "") then use Integer.parseInt().
If you get overral like 6 hours 43 mins you must split the string.

Title: Converting string with time to minutes

Body:
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

str = str.replaceAll("[^\\d.]", "");

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min


问:
how would i remove some portion of
 from a table in php?
this is my table -

```<code> <table>
     <tr>
      <td>ABC</td>
     </tr>
     <tr>
      <td> </td>
     </tr>
 </table>
</code>```

and I want to remove this one table row:

```<code><tr>
   <td> </td>
</tr>
</code>```

my expected output is:

```<code> <table>
   <tr>
     <td>ABC</td>
   </tr>
 </table>
</code>```

is it possible??please help me

答:
As you have tagged your question with the tag php i would recommend using a regular expression.

The pattern \s*
\s* <\/td>\s*<\/tr> will find the tr with an empty ( ) td.

To test and look into the regex you can have a look here: https://regex101.com/r/ax6Xdg/1

Put together this will look something like this:

```<code>$table = "<table>
    <tr>
        <td>ABC</td>
    </tr>
    <tr>
        <td> </td>
    </tr>
</table>";

$pattern = "/\s*<tr>\s*<td> <\/td>\s*<\/tr>/";

var_dump( preg_replace( $pattern , "" , $table ) );
</code>```

This will output something very simmilar to this:

```<code>string '<table>
    <tr>
        <td>ABC</td>
    </tr>
</table>' (length=60)
</code>```

Title: how would i remove some portion of <tr><td> from a table in php?

Body:
this is my table -

      ABC

and I want to remove this one table row:

my expected output is:

     ABC

is it possible??please help me

Body:
As you have tagged your question with the tag php i would recommend using a regular expression.

The pattern \s*<tr>\s*<td>&nbsp;<\/td>\s*<\/tr> will find the tr with an empty ( ) td.

To test and look into the regex you can have a look here: https://regex101.com/r/ax6Xdg/1

Put together this will look something like this:

$table = "<table>
    <tr>
        <td>ABC</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
    </tr>
</table>";

$pattern = "/\s*<tr>\s*<td>&nbsp;<\/td>\s*<\/tr>/";

var_dump( preg_replace( $pattern , "" , $table ) );

This will output something very simmilar to this:

string '<table>
    <tr>
        <td>ABC</td>
    </tr>
</table>' (length=60)


问:
JUnitTest for Karaf Startup
I want to write a JUnitTest, which ensures that my Karaf Server is started fine and all (needed) Bundles are installed and active.

For this I have a Test, calling a helper method "assertBundleState" which ensures, that the given Bundle is in the given State. The test looks like following:

```<code>@Test (timeout=30000L)
public void testBundlesStarted() throws Exception {
    assertBundleState("bundle.Name", BundleLifecycleState.Active);
... <other bundles in similar way>
}
</code>```

This worked fine in the past. The timeout was never reached.

Unfortunately I now have to load a bundle, which need a bit longer for startup. So the Bundles are not yet started, when the test is executed. And so the test fails.

I have tried it with a sleep in a BeforeClass method, but I am not really happy with this solution. Because I  can't ensure that the given sleep time is enough on every machine at every time. So I am looking for some event-based solution to interact with Karaf.

```<code>@BeforeClass
public static void init() throws Exception {
    Thread.sleep(120000L);
}
</code>```

Does anybody have an idea how I can solve it in a better way?
Thanks

答:
It sounds like assertBundleState can successfully determine whether the Karaf server has started and 'is ready'. But the issue is that you don't know how long to wait before checking this; if you don't wait long enough you risk a false negative, if you wait too long then your build elapsed time is falsely prolonged.

I presume you cannot register some sort of listener or callback hook which the Karaf server will invoke when it 'is ready'. Indeed, even if that was possible you would still have to cater for the failure case i.e. where the Karaf server does not start (and hence could never invoke a listener).

So, I think you just have to wait for the Karaf server to become available and hide the ugliness of Thread.sleep calls and the potential lost time in waiting too long. You could use Awaitility to tick those boxes. For example:

```<code>@Test
public void aTest() {
    // run your test

    // this will wait until Karaf is available for at most 10 seconds
    // and will check every 100ms so if Karaf becomes available earlier
    // than 10 seconds then the test will complete almost as soon as
    // it becomes available but if Karaf does not become available
    // within 10 seconds then the test will fail
    await().atMost(10, SECONDS).until(karafIsAvailable());

    // assert
    // ...
}

private Callable<Boolean> karafIsAvailable() {
    return new Callable<Boolean>() {
        public Boolean call() throws Exception {
            // return true if your condition has been met
            // e.g. assertBundleState
            return ...;
        }
    };
}
</code>```

Title: JUnitTest for Karaf Startup

Body:
I want to write a JUnitTest, which ensures that my Karaf Server is started fine and all (needed) Bundles are installed and active.

For this I have a Test, calling a helper method "assertBundleState" which ensures, that the given Bundle is in the given State. The test looks like following:

@Test (timeout=30000L)
public void testBundlesStarted() throws Exception {
    assertBundleState("bundle.Name", BundleLifecycleState.Active);
... <other bundles in similar way>
}

This worked fine in the past. The timeout was never reached.

Unfortunately I now have to load a bundle, which need a bit longer for startup. So the Bundles are not yet started, when the test is executed. And so the test fails.

I have tried it with a sleep in a BeforeClass method, but I am not really happy with this solution. Because I  can't ensure that the given sleep time is enough on every machine at every time. So I am looking for some event-based solution to interact with Karaf.

@BeforeClass
public static void init() throws Exception {
    Thread.sleep(120000L);
}

Does anybody have an idea how I can solve it in a better way?
Thanks

Body:
It sounds like assertBundleState can successfully determine whether the Karaf server has started and 'is ready'. But the issue is that you don't know how long to wait before checking this; if you don't wait long enough you risk a false negative, if you wait too long then your build elapsed time is falsely prolonged.

I presume you cannot register some sort of listener or callback hook which the Karaf server will invoke when it 'is ready'. Indeed, even if that was possible you would still have to cater for the failure case i.e. where the Karaf server does not start (and hence could never invoke a listener).

So, I think you just have to wait for the Karaf server to become available and hide the ugliness of Thread.sleep calls and the potential lost time in waiting too long. You could use Awaitility to tick those boxes. For example:

@Test
public void aTest() {
    // run your test

    // this will wait until Karaf is available for at most 10 seconds
    // and will check every 100ms so if Karaf becomes available earlier
    // than 10 seconds then the test will complete almost as soon as
    // it becomes available but if Karaf does not become available
    // within 10 seconds then the test will fail
    await().atMost(10, SECONDS).until(karafIsAvailable());

    // assert
    // ...
}

private Callable<Boolean> karafIsAvailable() {
    return new Callable<Boolean>() {
        public Boolean call() throws Exception {
            // return true if your condition has been met
            // e.g. assertBundleState
            return ...;
        }
    };
}


问:
How can i able to handle two id's (1 jquery id and 1 vue js id)?
I need to include a sliding for my products for that i am using jquery id and for displaying of items i am using vue js? So, how can I able to manage this two..

```<code><script type="text/javascript">
        $(window).load(function() {

          $("#flexiselDemo1").flexisel({
...............................................

});
}
<script>

<ul id="flexiselDemo1">
            <li>
                <a href="details.php"><img src="images/f0.jpg" alt=""/></a>
</li>
<li>
........................
</code>```

This is how my static file looks like and is working fine.

So, to make dynamic i include vue js to display data.. And now my file looks as

```<code>  <script type="text/javascript">
  new Vue({
    el: '#fe' ,
    data: {
      data: {},
    },
    mounted() {

        $(window).load(function() {

          data("mycustomname").flexisel({
                visibleItems: 5,
                animationSpeed: 1000,
                autoPlay: true,
                autoPlaySpeed: 3000,
                pauseOnHover: false,
                enableResponsiveBreakpoints: true,
                responsiveBreakpoints: {
                    portrait: {
                        changePoint:480,
                        visibleItems: 2
                    },
                    landscape: {
                        changePoint:640,
                        visibleItems: 3
                    },
                    tablet: {
                        changePoint:800,
                        visibleItems: 4
                    }
                }
            });
            });
       var self = this;

              $.ajax({
          url: ',
          data: {
                      },
          type: "POST",
          dataType: 'json',
          success: function (e) {
            if (e.status == 1) {
              self.data = e.data;
              console.log(e.data)
            }
          }
        });
        console.log(lat);
      }
      function error(err) {
        console.log(err)
      }
    }
  })
</script>
</code>```

So, when I display my html codes becomes

```<code><div class="review-slider" id="fe">

            <ul id="flexiselDemo1" data-mycustomname="flexisel">
                <div v-for="row in data">
            <li>{{row.name}}</li>
</div>
                </ul>
</div>
</code>```

When I do this way id="flexiselDemo1" doesnot works and layout is completely changing.. So, can anyone please help me to manage this situation?? I am a beginner in js and vue js.. Please have a help on this side..

答:
If change in ID will break your code why not use data attributes, its totally meant for situations like this.Modify your markup:

Add className to ul tag:

```<code><ul id="flexiselDemo1" class="flexis1">
</code>```

In your javascript replace $("#flexiselDemo1") with

```<code>$(".flexis1#flexiselDemo1")
</code>```

Body:
I need to include a sliding for my products for that i am using jquery id and for displaying of items i am using vue js? So, how can I able to manage this two..

So, when I display my html codes becomes

{{row.name}}

When I do this way id="flexiselDemo1" doesnot works and layout is completely changing.. So, can anyone please help me to manage this situation?? I am a beginner in js and vue js.. Please have a help on this side..

Body:
If change in ID will break your code why not use data attributes, its totally meant for situations like this.Modify your markup:

Add className to ul tag:

<ul id="flexiselDemo1" class="flexis1">

In your javascript replace $("#flexiselDemo1") with

$(".flexis1#flexiselDemo1")


问:
Post-build events in Qt Creator?
Is it possible to have post-build events (as in VC++) in Qt Creator? In particular, I would like to copy the executable to a different folder after it has been built. Can it be done?</p>

答: Add execution of a script to copy the files as a build step as below,

Title: Post-build events in Qt Creator?


问:
Spring boot - tests for servlet request/response, how to inject mock classes?
I'm quite new to spring boot and got a basic microservice put together (It accepts a Yelp url and scrapes the images for that restaurant). I thought it would be a good time to write some unit tests, but one thing I'm having trouble with is injecting mock classes into my tests for the servlet request/response.

The code I'm trying to test is quite simple, it looks like this. This is basically the entry point for my service, it accepts a JSON body, extracts a Yelp url from it, and thenYelpRequestController.makeYelpRequest() takes care of scraping the images and returning the image links in an ArrayList.

```<code>@RestController
public class RequestController {

    @PostMapping(value = "/")
    public ArrayList<String> index(@RequestBody String reqBodyString) {

        //my own function to parse the json string
        HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
        String yelpURL = requestBody.get("yelpURL");

        YelpRequestController yelpRequest = new YelpRequestController(yelpURL);
        ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest();
        return yelpImgLinks;
    }

}
</code>```

This is my unit test code. It basically creates a JSON string and sends a request to my RequestController and makes sure the response is okay. It passes right now, but I want the test to just test RequestController and nothing else. Currently it sends the url from the test through YelpRequestController and starts scraping images, which is what I don't want since I just want to isolate the RequestController in this test. I've been trying to mock the YelpRequestController class and return result, but I'm really having a lot of trouble.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RequestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void postRequestController() throws Exception {
        ObjectMapping jsonObject = new ObjectMapping();
        jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
        Gson gson = new Gson();
        String json = gson.toJson(jsonObject);
        mvc.perform(MockMvcRequestBuilders.post("/")
                .accept(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isOk());
    }
}
</code>```

I've been reading about how to use Mockito, and understand how to mock another class and inject it into a class you are testing. But I'm really stuck trying to apply that here. Any help would be appreciated.

答:
As pointed out in the comments you want to use dependency injection in your controller to make it testable in isolation.
You can then use a WebMvcTest targeting this specific controller. In contrast to a SpringBootTest this doesn't load your full ApplicationContext.

This could look something like this:

```<code>@RestController
public class RequestController {

    @Autowired
    private YelpRequestController yelpRequest;

    @PostMapping(value = "/")
    public ArrayList<String> index(@RequestBody String reqBodyString) {

        //my own function to parse the json string
        HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
        String yelpURL = requestBody.get("yelpURL");

        ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest(yelpURL);
        return yelpImgLinks;
    }

}
</code>```

In your test class you annotate the class that you want to have mocked with @MockBean and Spring will automatically use it for @Autowired fields:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(RequestController.class)
@AutoConfigureMockMvc
public class RequestControllerTest {

    @Autowired
    private MockMvc mvc;
    @MockBean
    private YelpRequestController yelpRequest;

    @Test
    public void postRequestController() throws Exception {
        ObjectMapping jsonObject = new ObjectMapping();
        jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
        Gson gson = new Gson();
        String json = gson.toJson(jsonObject);
        mvc.perform(MockMvcRequestBuilders.post("/")
                .accept(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isOk());
    }
}
</code>```

Body:
I'm quite new to spring boot and got a basic microservice put together (It accepts a Yelp url and scrapes the images for that restaurant). I thought it would be a good time to write some unit tests, but one thing I'm having trouble with is injecting mock classes into my tests for the servlet request/response.

The code I'm trying to test is quite simple, it looks like this. This is basically the entry point for my service, it accepts a JSON body, extracts a Yelp url from it, and thenYelpRequestController.makeYelpRequest() takes care of scraping the images and returning the image links in an ArrayList.

@RestController
public class RequestController {

    @PostMapping(value = "/")
    public ArrayList<String> index(@RequestBody String reqBodyString) {

        //my own function to parse the json string
        HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
        String yelpURL = requestBody.get("yelpURL");

        YelpRequestController yelpRequest = new YelpRequestController(yelpURL);
        ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest();
        return yelpImgLinks;
    }

}

This is my unit test code. It basically creates a JSON string and sends a request to my RequestController and makes sure the response is okay. It passes right now, but I want the test to just test RequestController and nothing else. Currently it sends the url from the test through YelpRequestController and starts scraping images, which is what I don't want since I just want to isolate the RequestController in this test. I've been trying to mock the YelpRequestController class and return result, but I'm really having a lot of trouble.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RequestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void postRequestController() throws Exception {
        ObjectMapping jsonObject = new ObjectMapping();
        jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
        Gson gson = new Gson();
        String json = gson.toJson(jsonObject);
        mvc.perform(MockMvcRequestBuilders.post("/")
                .accept(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isOk());
    }
}

I've been reading about how to use Mockito, and understand how to mock another class and inject it into a class you are testing. But I'm really stuck trying to apply that here. Any help would be appreciated.

Body:
As pointed out in the comments you want to use dependency injection in your controller to make it testable in isolation.
You can then use a WebMvcTest targeting this specific controller. In contrast to a SpringBootTest this doesn't load your full ApplicationContext.

This could look something like this:

@RestController
public class RequestController {

    @Autowired
    private YelpRequestController yelpRequest;

    @PostMapping(value = "/")
    public ArrayList<String> index(@RequestBody String reqBodyString) {

        //my own function to parse the json string
        HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
        String yelpURL = requestBody.get("yelpURL");

        ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest(yelpURL);
        return yelpImgLinks;
    }

}

In your test class you annotate the class that you want to have mocked with @MockBean and Spring will automatically use it for @Autowired fields:

@RunWith(SpringRunner.class)
@WebMvcTest(RequestController.class)
@AutoConfigureMockMvc
public class RequestControllerTest {

    @Autowired
    private MockMvc mvc;
    @MockBean
    private YelpRequestController yelpRequest;

    @Test
    public void postRequestController() throws Exception {
        ObjectMapping jsonObject = new ObjectMapping();
        jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
        Gson gson = new Gson();
        String json = gson.toJson(jsonObject);
        mvc.perform(MockMvcRequestBuilders.post("/")
                .accept(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isOk());
    }
}


问:
Prevent wrapping in CSS Flexbox
I have a re-sizable sidebar using Javascript. The problem is when the size of the sidebar is less than the content's wrapping occurs. (i think because of flex-box).

My grid is based on Rows and Columns kinda like Bootstrap.

```<code>.column {
    flex-basis: 0;
    max-width: 100%;
    flex-grow: 1;
}

.row {
    display: flex;
    flex-wrap: nowrap;
    margin: 0 -1rem;
}
</code>```

What I want to achieve is truncating the content (without shrinking) indicating that there is more.

Here is a fiddle with what i achieved so far.

答:
When it comes to Flexbox, you need to set min-width: 0 or overflow: hidden to every level, down from the child of the element with the width constraint, to the one having ellipsis.

So in this case, from the sidebar's child, and the reason is that a flex item's min-width defaults to auto, which mean it can't be smaller than its content.

To make it easy to follow how I mean, I created a flex-ellipsis class and added it to all elements down that chain.

Note, I also removed the negative margin, margin: 0 -1rem;, from the row class, or else one can't see the ellipsis.

Updated fiddle

Stack snippet

const resizeHandle = document.getElementsByClassName("vertical-resize")[0];
const navbar = document.getElementById('sidebar');

function resizeNavbar(e) {
  let size = (e.pageX + 5);

  navbar.style.width = (e.pageX + 5) + "px";
}

function removeEvents() {
  document.removeEventListener('mousemove', resizeNavbar);
  document.removeEventListener('mouseup', resizeNavbar);
}

resizeHandle.addEventListener('mousedown', () => {
  document.addEventListener('mousemove', resizeNavbar);
  document.addEventListener('mouseup', removeEvents);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  user-select: none;
  color: #dadada;
}

.flex-ellipsis {
  min-width: 0;                          /*  added  */
  /* or overflow: hidden; */
}

p,
h6 {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.rounded-circle {
  border-radius: 50% !important;
}

.no-margin {
  margin: 0 !important;
}

.column {
  flex-basis: 0;
  max-width: 100%;
  flex-grow: 1;
  background: #4a4a4a;
}

.column-1 {
  flex: 0 0 8.33333%;
  max-width: 8.33333%;
}

.row {
  display: flex;
  flex-wrap: nowrap; /*Even though no-wrap it still wraps as shown in picture.*/
  /*margin: 0 -1rem;*/
}

.custom {
  margin: auto;
  padding: 10px 0px;
  flex-wrap: nowrap;
}

.vertical-resize {
  position: relative;
  right: 0;
  top: 0;
  cursor: col-resize;
  width: 5px;
  background: aquamarine;
  height: 100vh;
}</code>```

Ahmed Tarek

01 January, 0001

```

Title: Prevent wrapping in CSS Flexbox

Body:
I have a re-sizable sidebar using Javascript. The problem is when the size of the sidebar is less than the content's wrapping occurs. (i think because of flex-box).

My grid is based on Rows and Columns kinda like Bootstrap.

.column {
    flex-basis: 0;
    max-width: 100%;
    flex-grow: 1;
}

.row {
    display: flex;
    flex-wrap: nowrap;
    margin: 0 -1rem;
}

What I want to achieve is truncating the content (without shrinking) indicating that there is more.

Here is a fiddle with what i achieved so far.

Body:
When it comes to Flexbox, you need to set min-width: 0 or overflow: hidden to every level, down from the child of the element with the width constraint, to the one having ellipsis.

So in this case, from the sidebar's child, and the reason is that a flex item's min-width defaults to auto, which mean it can't be smaller than its content.

To make it easy to follow how I mean, I created a flex-ellipsis class and added it to all elements down that chain.

Note, I also removed the negative margin, margin: 0 -1rem;, from the row class, or else one can't see the ellipsis.

Updated fiddle

Stack snippet

const resizeHandle = document.getElementsByClassName("vertical-resize")[0];
const navbar = document.getElementById('sidebar');

function resizeNavbar(e) {
  let size = (e.pageX + 5);

  navbar.style.width = (e.pageX + 5) + "px";
}

function removeEvents() {
  document.removeEventListener('mousemove', resizeNavbar);
  document.removeEventListener('mouseup', resizeNavbar);
}

resizeHandle.addEventListener('mousedown', () => {
  document.addEventListener('mousemove', resizeNavbar);
  document.addEventListener('mouseup', removeEvents);
});

* {
  user-select: none;
  color: #dadada;
}

.flex-ellipsis {
  min-width: 0;                          /*  added  */
  /* or overflow: hidden; */
}

p,
h6 {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.rounded-circle {
  border-radius: 50% !important;
}

.no-margin {
  margin: 0 !important;
}

.column {
  flex-basis: 0;
  max-width: 100%;
  flex-grow: 1;
  background: #4a4a4a;
}

.column-1 {
  flex: 0 0 8.33333%;
  max-width: 8.33333%;
}

.row {
  display: flex;
  flex-wrap: nowrap; /*Even though no-wrap it still wraps as shown in picture.*/
  /*margin: 0 -1rem;*/
}

.custom {
  margin: auto;
  padding: 10px 0px;
  flex-wrap: nowrap;
}

.vertical-resize {
  position: relative;
  right: 0;
  top: 0;
  cursor: col-resize;
  width: 5px;
  background: aquamarine;
  height: 100vh;
}

<div class="row">
  <div id="sidebar" style="width: 570px;">
    <div class="align-items-center row custom flex-ellipsis" id="sidebar">
      <div style="max-width: 2.5rem;" class="column-1">
        <img class="rounded-circle" style="max-width: 28px; min-width: 28px;" alt="Avatar" src="https://d30y9cdsu7xlg0.cloudfront.net/png/138926-200.png">
      </div>
      <div class="column flex-ellipsis">
        <div class="row">
          <div class="column">
            <p class="no-margin">Ahmed Tarek</p>
          </div>
        </div>
        <div class="row flex-ellipsis">
          <div class="column flex-ellipsis">
            <h6 style="font-size: 11px;" class="no-margin">01 January, 0001</h6>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="vertical-resize"></div>
  <div class="column">

  </div>
</div>


问:
android location finder from latitude and longitude
How can we get address or location name from latitude and longitude in android In my application I have set of latitude and longitude, But I need an API which will return me the location name corresponding to the latitude and longitude.
thanks.</p>

答:
Through Geocoder we can get the location name according to lattitude and longitude</p>

```<code>List<Address> addresses = new Geocoder(<CurrentActivityName>.this,Locale.getDefault()).getFromLocation(cur_lat, cur_lon, 1);

          Address addr= addresses.get(0);

          String Country=addr.getCountryName();
          String  State=addr.getSubAdminArea();
          String  City=addr.getLocality();
</code>```

Body:
Through Geocoder we can get the location name according to lattitude and longitude

List<Address> addresses = new Geocoder(<CurrentActivityName>.this,Locale.getDefault()).getFromLocation(cur_lat, cur_lon, 1);

          Address addr= addresses.get(0);

          String Country=addr.getCountryName();
          String  State=addr.getSubAdminArea();
          String  City=addr.getLocality();


问:
When route change to next Component, don't scroll to the top automatically
In my Vue/Vuetify single page app, when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me to the next page but it doesn't scroll to the top of the next page/Component.

As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if user scroll to the top of the page.

Page 01 - I'm in the middle of a long list, just a example

Page 02 - The next Component loads at the middle

答:
You can use vue-router's scrollBehavior method to change the scroll position on page navigation. Instead of created () { window.scrollTo(0, 0) } you should use:

```<code>new VueRouter ({
  routes: [...],
  scrollBehavior () {
    return { x: 0, y: 0 }
  }
})
</code>```

See more examples on vue-router's documentation:

https://router.vuejs.org/guide/advanced/scroll-behavior.html

Body:
You can use vue-router's scrollBehavior method to change the scroll position on page navigation. Instead of created () { window.scrollTo(0, 0) } you should use:

new VueRouter ({
  routes: [...],
  scrollBehavior () {
    return { x: 0, y: 0 }
  }
})

See more examples on vue-router's documentation:

https://router.vuejs.org/guide/advanced/scroll-behavior.html


问:
content select option based on previous select option angularjs
i want to create 2 select option which the content of the other one selected option based to previous option. here is my html

```<code><div class="col-sm-2">
            <select class="form-control" ng-model="y">
                <option value="1">a</option>
                <option value="2">b</option>
            </select>
        </div>
        <div class="col-sm-2">
            <select class="form-control" ng-model="z">
                <option ng-repeat = "x in list" value="{{x.idproduct}}">{{x.descproduct}}</option>
            </select>
        </div>
</code>```

but there is error, the other select option wont showing the option like in this picture

here is my js file

```<code>if ($scope.y === 1) {
         $scope.list = [
          {idproduct:"13", descproduct:"cc"},
          {idproduct:"14", descproduct:"dd"}
         ];
       }
       if ($scope.y === 2) {
         $scope.list = [
          {idproduct:"15", descproduct:"ee"}
         ];
       }
</code>```

答:
The value of your option is String value="2"

And you're comparing it to an Integer if ($scope.y === 2)

You should compare it like if ($scope.y === '2') or if (parseInt($scope.y) === 2)

Body:
i want to create 2 select option which the content of the other one selected option based to previous option. here is my html

            <select class="form-control" ng-model="y">
                <option value="1">a</option>
                <option value="2">b</option>
            </select>

            <select class="form-control" ng-model="z">
                <option ng-repeat = "x in list" value="{{x.idproduct}}">{{x.descproduct}}</option>
            </select>

but there is error, the other select option wont showing the option like in this picture

here is my js file

if ($scope.y === 1) {
         $scope.list = [
          {idproduct:"13", descproduct:"cc"},
          {idproduct:"14", descproduct:"dd"}
         ];
       }
       if ($scope.y === 2) {
         $scope.list = [
          {idproduct:"15", descproduct:"ee"}
         ];
       }


问:
How to pivot on multiple columns?
I'm trying to pivot on multiple columns and I'm using SQL Server 2014, however, I cannot figure out how to do that. Here's what I've tried so far:

```<code>DECLARE @Table TABLE (
    Name NVARCHAR(MAX),
    TypeId INT,
    TotalOrders INT,
    GrandTotal MONEY
)

INSERT INTO @Table
    (Name, TypeId, TotalOrders, GrandTotal)
VALUES
    ('This Month', 1, 10, 1),
    ('This Month', 2, 5, 7),
    ('This Week', 1, 8, 3),
    ('Last Week', 1, 8, 12),
    ('Yesterday', 1, 10, 1),
    ('Yesterday', 2, 1, 5)
</code>```

Which produces the following result:

```<code>Name                             TypeId      TotalOrders GrandTotal
-------------------------------- ----------- ----------- ---------------------
This Month                       1           10          1.00
This Month                       2           5           7.00
This Week                        1           8           3.00
Last Week                        1           8           12.00
Yesterday                        1           10          1.00
Yesterday                        2           1           5.00
</code>```

To bring those rows into columns, I've tried this:

```<code>SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month]
    )
) AS p1
</code>```

Which produces the following result set:

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders
----------- -------------------- ------------------- ------------------- --------------------
1           10                   8                   8                   10
2           1                    0                   0                   5
</code>```

Now, I need to have few other columns for GrandTotal such as YesterdayGrandTotal, ThisWeekGrandTotal, and so on and so forth but I can't figure out how to achieve this.

Any help would be highly appreciated.

UPDATE#1: Here's the expected result set:

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00
</code>```

答:
You could also use of CTE by separating your pivots.. P1 for TotalOrders & P2 for GrandTotal

```<code>;WITH CTE AS
   (
     SELECT
    P1.TypeId,
    ISNULL(P1.[Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL(P1.[This Week], 0) AS ThisWeekTotalOrders,
    ISNULL(P1.[Last Week], 0) AS LastWeekTotalOrders,
    ISNULL(P1.[This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (SUM(TotalOrders) FOR src.Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month])) AS P1
   ), CTE1 AS
   (

SELECT
    P1.TypeId,
    ISNULL(P1.[Yesterday], 0) AS YesterdayGrandTotal,
    ISNULL(P1.[This Week], 0) AS ThisWeekTGrandTotal,
    ISNULL(P1.[Last Week], 0) AS LastWeekGrandTotal,
    ISNULL(P1.[This Month], 0) AS ThisMonthGrandTotal
FROM
    (SELECT Name, TypeId, GrandTotal FROM @Table) AS src
PIVOT (SUM(GrandTotal) FOR src.Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month])) AS P1
       )

       SELECT C.TypeId  ,    C.YesterdayTotalOrders, C.ThisWeekTotalOrders, C.LastWeekTotalOrders, C.ThisMonthTotalOrders , C1.YesterdayGrandTotal  , C1.ThisWeekTGrandTotal ,C1.LastWeekGrandTotal , C1.ThisMonthGrandTotal FROM CTE C
       INNER JOIN CTE1 C1 ON C1.TypeId = C.TypeId
</code>```

Result :

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00
</code>```

Title: How to pivot on multiple columns?

Body:
I'm trying to pivot on multiple columns and I'm using SQL Server 2014, however, I cannot figure out how to do that. Here's what I've tried so far:

DECLARE @Table TABLE (
    Name NVARCHAR(MAX),
    TypeId INT,
    TotalOrders INT,
    GrandTotal MONEY
)

INSERT INTO @Table
    (Name, TypeId, TotalOrders, GrandTotal)
VALUES
    ('This Month', 1, 10, 1),
    ('This Month', 2, 5, 7),
    ('This Week', 1, 8, 3),
    ('Last Week', 1, 8, 12),
    ('Yesterday', 1, 10, 1),
    ('Yesterday', 2, 1, 5)

Which produces the following result:

Name                             TypeId      TotalOrders GrandTotal
-------------------------------- ----------- ----------- ---------------------
This Month                       1           10          1.00
This Month                       2           5           7.00
This Week                        1           8           3.00
Last Week                        1           8           12.00
Yesterday                        1           10          1.00
Yesterday                        2           1           5.00

To bring those rows into columns, I've tried this:

SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month]
    )
) AS p1

Which produces the following result set:

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders
----------- -------------------- ------------------- ------------------- --------------------
1           10                   8                   8                   10
2           1                    0                   0                   5

Now, I need to have few other columns for GrandTotal such as YesterdayGrandTotal, ThisWeekGrandTotal, and so on and so forth but I can't figure out how to achieve this.

Any help would be highly appreciated.

UPDATE#1: Here's the expected result set:

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00

Body:
You could also use of CTE by separating your pivots.. P1 for TotalOrders & P2 for GrandTotal

;WITH CTE AS
   (
     SELECT
    P1.TypeId,
    ISNULL(P1.[Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL(P1.[This Week], 0) AS ThisWeekTotalOrders,
    ISNULL(P1.[Last Week], 0) AS LastWeekTotalOrders,
    ISNULL(P1.[This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (SUM(TotalOrders) FOR src.Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month])) AS P1
   ), CTE1 AS
   (

SELECT
    P1.TypeId,
    ISNULL(P1.[Yesterday], 0) AS YesterdayGrandTotal,
    ISNULL(P1.[This Week], 0) AS ThisWeekTGrandTotal,
    ISNULL(P1.[Last Week], 0) AS LastWeekGrandTotal,
    ISNULL(P1.[This Month], 0) AS ThisMonthGrandTotal
FROM
    (SELECT Name, TypeId, GrandTotal FROM @Table) AS src
PIVOT (SUM(GrandTotal) FOR src.Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month])) AS P1
       )

       SELECT C.TypeId  ,    C.YesterdayTotalOrders, C.ThisWeekTotalOrders, C.LastWeekTotalOrders, C.ThisMonthTotalOrders , C1.YesterdayGrandTotal  , C1.ThisWeekTGrandTotal ,C1.LastWeekGrandTotal , C1.ThisMonthGrandTotal FROM CTE C
       INNER JOIN CTE1 C1 ON C1.TypeId = C.TypeId

Result :

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00


问:
LibGDX: Parallax effect with tiled maps
Need to make parallax effect in the game with LibGDX and tiled map. Background should move with different speed then foreground. In the docs https://github.com/libgdx/libgdx/wiki/Tile-maps said:

By rendering each layer separately and modifying the view for every
  layer, you can also achieve a parallax effect.

Current implementation: with PlayScreenVariantOne all works but background moving with same speed like foreground

public class PlayScreenVariantOne implements Screen {

    private TextureAtlas atlas;
    private OrthographicCamera gameCam;
    private Viewport viewport;
    private TmxMapLoader mapLoader;
    private TiledMap map;
    private OrthogonalTiledMapRenderer renderer;
    ...

    // ...
    // ... bla-bla-bla...
    // ...
    @Override
    public void render(float delta) {
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        renderer.setView(gameCam);
        renderer.render();

        game.batch.setProjectionMatrix(gameCam.combined);
        game.batch.begin();

        player.draw(game.batch);
        game.batch.end();
        hud.stage.draw();

    }
 }
```

<p><strong>Parallax implementation</strong>: with <code>PlayScreenVariantTwo</code> foreground and background rendered with same speed. Parallax effect does not work! :*(</p>

<pre class="lang-java prettyprint-override"><code>public class PlayScreenVariantTwo implements Screen {

    private TextureAtlas atlas;
    private OrthographicCamera gameCam;
    private Viewport viewport;
    private TmxMapLoader mapLoader;
    private TiledMap map;
    private OrthogonalTiledMapRenderer renderer;
    ...

    // ...
    // ... bla-bla-bla...
    // ...
    @Override
    public void render(float delta) {
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        int[] backgroundLayers = { 7 };
        int[] ground = { 9 };

        renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2 - 2), gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);
        renderer.render(backgroundLayers);

        renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2) / 10, gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth  * 10, gameCam.viewportHeight);
        renderer.render(ground);

        game.batch.setProjectionMatrix(gameCam.combined);
        game.batch.begin();

        player.draw(game.batch);
        game.batch.end();

        hud.stage.draw();

    }
 }
</code>```

答:
Did you try to simply multiply X (or Y, what ever you need) coordinate for background with factor:

```<code>  renderer.setView(gameCam.combined, (gameCam.position.x*0.5 - gameCam.viewportWidth / 2 - 2), gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);
</code>```

or

```<code>  renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2 - 2)*0.5, gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);
</code>```

I added that "*0.5", so background would move twice slower. Not sure which one of those 2 rows will give you better results - you have to try for your self, but that's the ide - multiply background coordinates, X or Y, which one you need to set different speed.

Title: LibGDX: Parallax effect with tiled maps

Body:
Need to make parallax effect in the game with LibGDX and tiled map. Background should move with different speed then foreground. In the docs https://github.com/libgdx/libgdx/wiki/Tile-maps said:

By rendering each layer separately and modifying the view for every
  layer, you can also achieve a parallax effect.

Current implementation: with PlayScreenVariantOne all works but background moving with same speed like foreground

public class PlayScreenVariantOne implements Screen {

    private TextureAtlas atlas;
    private OrthographicCamera gameCam;
    private Viewport viewport;
    private TmxMapLoader mapLoader;
    private TiledMap map;
    private OrthogonalTiledMapRenderer renderer;
    ...

    // ...
    // ... bla-bla-bla...
    // ...
    @Override
    public void render(float delta) {
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        renderer.setView(gameCam);
        renderer.render();

        game.batch.setProjectionMatrix(gameCam.combined);
        game.batch.begin();

        player.draw(game.batch);
        game.batch.end();
        hud.stage.draw();

    }
 }

Parallax implementation: with PlayScreenVariantTwo foreground and background rendered with same speed. Parallax effect does not work! :*(

public class PlayScreenVariantTwo implements Screen {

    private TextureAtlas atlas;
    private OrthographicCamera gameCam;
    private Viewport viewport;
    private TmxMapLoader mapLoader;
    private TiledMap map;
    private OrthogonalTiledMapRenderer renderer;
    ...

    // ...
    // ... bla-bla-bla...
    // ...
    @Override
    public void render(float delta) {
        update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        int[] backgroundLayers = { 7 };
        int[] ground = { 9 };

        renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2 - 2), gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);
        renderer.render(backgroundLayers);

        renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2) / 10, gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth  * 10, gameCam.viewportHeight);
        renderer.render(ground);

        game.batch.setProjectionMatrix(gameCam.combined);
        game.batch.begin();

        player.draw(game.batch);
        game.batch.end();

        hud.stage.draw();

    }
 }

Body:
Did you try to simply multiply X (or Y, what ever you need) coordinate for background with factor:

  renderer.setView(gameCam.combined, (gameCam.position.x*0.5 - gameCam.viewportWidth / 2 - 2), gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);

or

  renderer.setView(gameCam.combined, (gameCam.position.x - gameCam.viewportWidth / 2 - 2)*0.5, gameCam.position.y - gameCam.viewportHeight / 2, gameCam.viewportWidth, gameCam.viewportHeight);

I added that "*0.5", so background would move twice slower. Not sure which one of those 2 rows will give you better results - you have to try for your self, but that's the ide - multiply background coordinates, X or Y, which one you need to set different speed.


问:
Iterating between 2 lists while adding content from one to the other in Python
If I have the following lists:

```<code>a = ['a','b','c']
b = ['1','2','3']
</code>```

How can I get python to output this:

```<code>['a',1,'b',2,'c',3]
</code>```

Thanks in advance !!

答:
Try this:

```<code>a = ['a', 'b', 'c']
b = ['1', '2', '3']

c = []
for x, y in zip(a, b):
    c.append(x)
    c.append(y)

print (c)
</code>```

output:

```<code>['a', '1', 'b', '2', 'c', '3']
</code>```

Of course you can change it to match your needs, if needed

Body:
If I have the following lists:

a = ['a','b','c']
b = ['1','2','3']

How can I get python to output this:

['a',1,'b',2,'c',3]

Thanks in advance !!

Body:
Try this:

a = ['a', 'b', 'c']
b = ['1', '2', '3']

c = []
for x, y in zip(a, b):
    c.append(x)
    c.append(y)

print (c)

output:

['a', '1', 'b', '2', 'c', '3']

Of course you can change it to match your needs, if needed


问:
Manipulation DOM in saga redux
I have application with long list and click last element must scroll to top page. What best decision: use react-scroll or use saga for this task?

And use saga for manipulate DOM and web page the good way?

答:
What best decision: use react-scroll or use saga for this task?

Saga is commonly applicable for long-running process, affecting redux state in asynchronous manner, like API call or optimistic update. Often redux state includes information about domain and presentation layers, so, if actual UI state is stored in redux store, there is no barrier to use saga to manipulate it.

For example, there is library https://www.npmjs.com/package/react-redux-scroll to support scrolling using saga and listening actions respectively. In other words, manipulation of state in one point, at root of redux state, by saga processes - is best use case.

Title: Manipulation DOM in saga redux