问:
http call not triggering in promise callback angular 2
In my angular 2 project I make this call to get some data:

```<code>this.http.getfromgraphql()
      .map((response: Response) => response.json())
      .subscribe(
        (data) => {
          console.log(data);
        });
</code>```

This triggers the getfromgraphql function shown below, before I make that call though, I have to check if the access token is still valid in checkaccesstokenvalidity, there I set some variables and resolve the function.

the console logs 'in then' but my http post does not trigger.

Why is that?

Also, I am sure there is a better way to do this, but for the life of me I can't figure it out, a better solution is much appreciated

```<code>checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    // if(!this.access_token) {
    return new Promise((resolve, reject) => {
      this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .subscribe(function(response) {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
          },
          error => console.log("Error: ", error),
          function() {
            console.log('resolving');
            resolve();
          });

    });
    // }
  }
  getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity().then(function() {
      console.log('in then');
      //noinspection TypeScriptValidateTypes
      return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    });
  }
</code>```

答:
Try replacing your post call with this :

```<code>return this.http.post(this.URL + '/api/v1/graphql', this.query, options).subscribe(() => {});
</code>```

and see if it works now.

Body:
In my angular 2 project I make this call to get some data:

this.http.getfromgraphql()
      .map((response: Response) => response.json())
      .subscribe(
        (data) => {
          console.log(data);
        });

This triggers the getfromgraphql function shown below, before I make that call though, I have to check if the access token is still valid in checkaccesstokenvalidity, there I set some variables and resolve the function.

the console logs 'in then' but my http post does not trigger.

Why is that?

Also, I am sure there is a better way to do this, but for the life of me I can't figure it out, a better solution is much appreciated

checkAccessTokenValidity() {
    let headers = new Headers();
    headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });
    // if(!this.access_token) {
    return new Promise((resolve, reject) => {
      this.http.post(this.URL + 'oauth/token', this.authentication, options)
        .subscribe(function(response) {
            this.authObj = response.json();
            this.expirationDate = new Date();
            this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
            console.log(this.authObj, this.expirationDate);
          },
          error => console.log("Error: ", error),
          function() {
            console.log('resolving');
            resolve();
          });

    });
    // }
  }
  getfromgraphql() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    // headers.append('Authorization', 'Bearer ' + this.access_token );
    let options = new RequestOptions({ headers: headers });

    this.checkAccessTokenValidity().then(function() {
      console.log('in then');
      //noinspection TypeScriptValidateTypes
      return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
    });
  }

Body:
Try replacing your post call with this :

return this.http.post(this.URL + '/api/v1/graphql', this.query, options).subscribe(() => {});

and see if it works now.


来源: stackexchange

问:
Conversion failed when converting the varchar value 'D' to data type int
I have been staring at this query for 20 minutes and I can't see why I am getting the error in the title. Can you understand why this is happening? Thanks!</p>

```<code> SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

DECLARE @StartDate DATETIME  = '2016-06-05 00:00:00.000';
DECLARE @EndDate DATETIME = '2016-08-06 23:59:59.000';
select count(tptC.MovConID)  as [Count of Collections], sum(cgtC.[Chargeable weight]) as [Total Col Chg Wt], sum(tptrevenueC.amount)  as [Rev Col],
count(tptD.MovConID) as [Count of Deliveries], sum(cgtD.[Chargeable weight]) as [Total Del Chg Wt], sum(tptrevenueD.amount) as [Rev Del]
from tptVehicle tptv
inner join tptHeader tpth on tpth.VehicleID = tptv.VehicleID
left join tptDetails tptC on tptC.RunID = tpth.RunID and tptC.RunType = 'C'
left join tptDetails tptD on tptD.RunID = tpth.RunID and tptD.RunID = 'D'
left join tptVehicleRevenueDaily tptrevenueC on tptrevenueC.Reference = tptC.MovConID
left join tptVehicleRevenueDaily tptrevenueD on tptrevenueD.Reference = tptD.MovConID
left join cgtConsignment cgtC on cgtC.[Consignment Reference] = tptrevenueC.Reference
left join cgtConsignment cgtD on cgtD.[Consignment Reference] = tptrevenueD.Reference
where tpth.JourneyDate >= @StartDate and tpth.JourneyDate <= @EndDate and tpth.RunReference like 'belf%'
</code>```

答:
Probably because tpt.RunID is an int, and you're trying to compare it to 'D' in one of your left joins.

Try changing this:

```<code>left join tptDetails tptD on tptD.RunID = tpth.RunID and tptD.RunID = 'D'
</code>```

to this:

```<code>left join tptDetails tptD on tptD.RunID = tpth.RunID and tptD.RunType = 'D'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been staring at this query for 20 minutes and I can't see why I am getting the error in the title. Can you understand why this is happening? Thanks!

 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

DECLARE @StartDate DATETIME  = '2016-06-05 00:00:00.000';
DECLARE @EndDate DATETIME = '2016-08-06 23:59:59.000';
select count(tptC.MovConID)  as [Count of Collections], sum(cgtC.[Chargeable weight]) as [Total Col Chg Wt], sum(tptrevenueC.amount)  as [Rev Col],
count(tptD.MovConID) as [Count of Deliveries], sum(cgtD.[Chargeable weight]) as [Total Del Chg Wt], sum(tptrevenueD.amount) as [Rev Del]
from tptVehicle tptv
inner join tptHeader tpth on tpth.VehicleID = tptv.VehicleID
left join tptDetails tptC on tptC.RunID = tpth.RunID and tptC.RunType = 'C'
left join tptDetails tptD on tptD.RunID = tpth.RunID and tptD.RunID = 'D'
left join tptVehicleRevenueDaily tptrevenueC on tptrevenueC.Reference = tptC.MovConID
left join tptVehicleRevenueDaily tptrevenueD on tptrevenueD.Reference = tptD.MovConID
left join cgtConsignment cgtC on cgtC.[Consignment Reference] = tptrevenueC.Reference
left join cgtConsignment cgtD on cgtD.[Consignment Reference] = tptrevenueD.Reference
where tpth.JourneyDate >= @StartDate and tpth.JourneyDate <= @EndDate and tpth.RunReference like 'belf%'

Body:
Probably because tpt.RunID is an int, and you're trying to compare it to 'D' in one of your left joins.

Try changing this:

left join tptDetails tptD on tptD.RunID = tpth.RunID and tptD.RunID = 'D'

to this:

left join tptDetails tptD on tptD.RunID = tpth.RunID and tptD.RunType = 'D'


问:
How do I optimize filtering in AngularJS?
I have here a filter for AngularJS. Is there any better way for this?</p>

```<code> return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < selected.length; j++) {
                    if (data[i].Type == selected[j]) {
                        result.push(data[i]);
                    }
                }
            }
        }

        return result;
    };
</code>```

答:
```<code>return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
           result=data.filter(x=>selected.indexOf(x.Type)>-1);
        }

        return result;
    };
</code>```

Body:
I have here a filter for AngularJS. Is there any better way for this?

 return function (data, selected) {
        var result = [];
        if (selected[0] == 'All Types') {
            result = data;
        }
        else {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < selected.length; j++) {
                    if (data[i].Type == selected[j]) {
                        result.push(data[i]);
                    }
                }
            }
        }

        return result;
    };


问:
Running two debug processes in Visual Studio Code (Python, Django, Celery)
Is it possible to run several debug processes at one click? For example, I would like to run Django development server + Celery daemon in order to be able to debug it at one time. Has anyone tried to do so?</p>

答:
Try looking into Multitarget debugging: https://code.visualstudio.com/Docs/editor/debugging#_multitarget-debugging

This allows you to debug multiple processes in VSCode. You can switch back and forth between the currently debugged process using the drop down in the debug widget


问:
How do I programmatically add a view right under the navigation bar?
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

```<code>override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}
</code>```

With this being the result:

And I tried by setting the frame of my subview:

```<code>override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}
</code>```

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?

答:
Replace this

```<code>self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
</code>```

with

```<code>self.label = UILabel(frame: CGRect(x: 0, y: 64, width: 300, height: 100))
</code>```

naviagtion bar & status bar together has a height of 64. Make it the y position

Body:
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}

With this being the result:

And I tried by setting the frame of my subview:

override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?

Body:
Replace this

self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))

with

self.label = UILabel(frame: CGRect(x: 0, y: 64, width: 300, height: 100))

naviagtion bar & status bar together has a height of 64. Make it the y position


问:
Google Maps v3 panTo() from getCenter() lat lng doesn't go to same location
I'm using getCenter() to use the lat lng in a url so users can share / bookmark a location on Google Maps. I then use panTo() to try and jump back to the same location. Though it always jumps back to approximately the same location it's never exactly the same view.

I've thought about using setCenter() instead of panTo() but this can mess up the referencing calculation for the custom map layer I'm displaying. Depends where the center happens to be.

To see the problem in action you can go to http://www.topomap.co.nz/ and use the "Share" tab to get a url generated from getCenter(). Using the url you'll notice they show slightly different centers.

Please note that I'm currently using latLng.toUrlValue() which reduces some of the accuracy, but you can manually tweak the url from the individual lat long given in the "Share" tab and you'll still see the same problem.

Any ideas what might be going on?

答: Seems panTo() is no substitute for setCenter(). I just have to code around my Prime Meridian issue and use setCenter() instead.</p>

ContentLicense: CC BY-SA 2.5


问:
Why every time in Selenium Webdriver the “ID” of any web element gets changed?
I have written a script which sends an email using Selenium Webdriver (Python bindings). But sometimes, when I run that script the ID of element gets changed.

Error trace-back:

```<code>self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium-3.4.3-
py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 194, in
check_response
raise exception_class(message, screen, stacktrace)
elenium.common.exceptions.NoSuchElementException: Message: no such
element: Unable to locate element: {"method":"id","selector":":pm"}
</code>```

And sometimes, if I am using valid XPath, or CSS Selector, then the same error is displayed.

Can anyone suggest the best way to make the script work? Also, why is it that every time the Id of the element gets changed?

My code:

```<code>from selenium import webdriver
import time
from time import sleep

driver = webdriver.Chrome()
driver.get("https://accounts.google.com")
driver.implicitly_wait(30)
usr = driver.find_element_by_id("identifierId").clear()
usr.send_keys("id@anymail.com")

nextb = driver.find_element_by_id("identifierNext")
nextb.click()

pwd = driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input')
pwd.send_keys("**Enter your password**")

nextpwd = driver.find_element_by_xpath('//*[@id="passwordNext"]/content/span')
nextpwd.click()

driver.implicitly_wait(30)
driver.find_element_by_xpath("//*[@id=':hs']/div/div").click()

time.sleep(3)
to = driver.find_element_by_id(":nf")
to.send_keys("XYZ@gmail.com")

sub = driver.find_element_by_id(":my")
sub.send_keys("with attachment")

descp = driver.find_element_by_id(":nx")
descp.send_keys(" Hi! this second one.")

driver.find_element_by_id(":om").click() #attachmment
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("/home/example.png")
#sead the mail
driver.find_element_by_id(":mo").click()
</code>```

答:
You mean that Id is dynamic? It means that upon each page load element's id changing fully or partly.

In case there's no static part (each time id is 100% random) - you won't be able to use it as locator and should use other attributes/elements to find required one. Like //someParentElement/div[@class='someClass'] - meaning that you can find element's parent element, or use additional attributes like class/value/etc.

In case there's static part upon each load - you can use css or xPath locator that search for element which contains/starts-with static part.

Search for element where id contains some part:

//*[contains(@id,'part')] - id contains part xpath locator

[id*=part] - id contains part css locator

Search for element where id starts with some part:

//*[starts-with(@id,'part')] - id starts with part xpath locator

[id^=part] - id starts with part css locator

Body:
I have written a script which sends an email using Selenium Webdriver (Python bindings). But sometimes, when I run that script the ID of element gets changed.

Error trace-back:

self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium-3.4.3-
py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 194, in
check_response
raise exception_class(message, screen, stacktrace)
elenium.common.exceptions.NoSuchElementException: Message: no such
element: Unable to locate element: {"method":"id","selector":":pm"}

And sometimes, if I am using valid XPath, or CSS Selector, then the same error is displayed.

Can anyone suggest the best way to make the script work? Also, why is it that every time the Id of the element gets changed?

My code:

from selenium import webdriver
import time
from time import sleep

driver = webdriver.Chrome()
driver.get("https://accounts.google.com")
driver.implicitly_wait(30)
usr = driver.find_element_by_id("identifierId").clear()
usr.send_keys("id@anymail.com")

nextb = driver.find_element_by_id("identifierNext")
nextb.click()

pwd = driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input')
pwd.send_keys("**Enter your password**")

nextpwd = driver.find_element_by_xpath('//*[@id="passwordNext"]/content/span')
nextpwd.click()

driver.implicitly_wait(30)
driver.find_element_by_xpath("//*[@id=':hs']/div/div").click()

time.sleep(3)
to = driver.find_element_by_id(":nf")
to.send_keys("XYZ@gmail.com")

sub = driver.find_element_by_id(":my")
sub.send_keys("with attachment")

descp = driver.find_element_by_id(":nx")
descp.send_keys(" Hi! this second one.")

driver.find_element_by_id(":om").click() #attachmment
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("/home/example.png")
#sead the mail
driver.find_element_by_id(":mo").click()


问:
Searching for records with the same date
What is the best way to determine records from the same table with the same dates.

I have 2 rows from my instalments table:

```<code>ORDER_1  | 13 | Paid | 2017-02-01 00:00:00.000 |
ORDER_2  | 14 | Paid | 2017-02-01 00:00:00.000 |
</code>```

I need to be able to show all the instalments where the date is the same.

I have tried:

```<code>SELECT *  FROM ORDER_INSTALMENT WHERE DATEDUE = DATEDUE
</code>```

答:
```<code>SELECT a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
FROM ORDER_INSTALMENT AS a INNER JOIN ORDER_INSTALMENT AS b
ON a.DATEDUE = b.DATEDUE
AND a.OrderID <> b.OrderID
GROUP BY a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
ORDER BY a.DATEDUE
</code>```

even the result and speed is same if you are using index in your table, you can use distinct for make it simple :

```<code>SELECT DISTINCT a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
FROM ORDER_INSTALMENT AS a INNER JOIN ORDER_INSTALMENT AS b
ON a.DATEDUE = b.DATEDUE
AND a.OrderID <> b.OrderID
ORDER BY a.DATEDUE
</code>```

Body:
What is the best way to determine records from the same table with the same dates.

I have 2 rows from my instalments table:

ORDER_1  | 13 | Paid | 2017-02-01 00:00:00.000 |
ORDER_2  | 14 | Paid | 2017-02-01 00:00:00.000 |

I need to be able to show all the instalments where the date is the same.

I have tried:

SELECT *  FROM ORDER_INSTALMENT WHERE DATEDUE = DATEDUE

Body:
SELECT a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
FROM ORDER_INSTALMENT AS a INNER JOIN ORDER_INSTALMENT AS b
ON a.DATEDUE = b.DATEDUE
AND a.OrderID <> b.OrderID
GROUP BY a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
ORDER BY a.DATEDUE

even the result and speed is same if you are using index in your table, you can use distinct for make it simple :

SELECT DISTINCT a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
FROM ORDER_INSTALMENT AS a INNER JOIN ORDER_INSTALMENT AS b
ON a.DATEDUE = b.DATEDUE
AND a.OrderID <> b.OrderID
ORDER BY a.DATEDUE


问:
Flex not working in firefox while working correctly in chrome and safari
I am currently learning flex CSS property, and I am using it display a bunch of divs with four per row at maximum. Here is HTML and CSS for it:

.outer {
  display: flex;
  flex-wrap: wrap;
  margin: -5% -5% 0 -5%;
}

.step {
  text-align: center;
  display: inline-block;
  border: 2px solid black;
  margin: 5% 5% 0 5%;
  flex-grow: 1;
  height: 100px;
  width: 13%;
  overflow: auto;
}

.child {
  font-size: 1.25em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer" id="container">
  <div class='step' id=step0>
    <p class='child'> 1</p>
  </div>
  <div class='step' id=step1>
    <p class='child'> 2</p>
  </div>
  <div class='step' id=step2>
    <p class='child'>3</p>
  </div>
  <div class='step' id=step3>
    <p class='child'> 4</p>
  </div>
  <div class='step error' id=step7>
    <p class='child'>8</p>
  </div>
  <div class='step' id=step6>
    <p class='child'>7</p>
  </div>
  <div class='step' id=step5>
    <p class='child'>6</p>
  </div>
  <div class='step' id=step4>
    <p class='child'>5</p>
  </div>
  <div class='step' id=step8>
    <p class='child'>9</p>
  </div>
  <div class='step' id=step9>
    <p class='child'>10</p>
  </div>
</div></code>```

The css Works exactly the way I want it to work in Chrome, but in firefox vertical gap between different rows is zero, while it is not so in Chrome. What am I doing wrong?
(I have made a fiddle as well, https://jsfiddle.net/vLmnq7fL/2/ . Open in Chrome and firefox to see the difference)

答:
Using percent for padding's and margin's on flex items might render in different outputs on different browser since the spec's let them.

Also, when using percent for the top value in your margin:5%5% 0 5%; will be based on the parent's width, not height, will as well can give unpredictable result.

If you use viewport units it won't though margin:5vh5% 0 5%;

.outer {
  display: flex;
  flex-wrap: wrap;
  margin: -5vh -5% 0 -5%;
}

.step {
  text-align: center;
  display: inline-block;
  border: 2px solid black;
  margin: 5vh 5% 0 5%;
  flex-grow: 1;
  height: 100px;
  width: 13%;
  overflow: auto;
}

.child {
  font-size: 1.25em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer" id="container">
  <div class='step' id=step0>
    <p class='child'> 1</p>
  </div>
  <div class='step' id=step1>
    <p class='child'> 2</p>
  </div>
  <div class='step' id=step2>
    <p class='child'>3</p>
  </div>
  <div class='step' id=step3>
    <p class='child'> 4</p>
  </div>
  <div class='step error' id=step7>
    <p class='child'>8</p>
  </div>
  <div class='step' id=step6>
    <p class='child'>7</p>
  </div>
  <div class='step' id=step5>
    <p class='child'>6</p>
  </div>
  <div class='step' id=step4>
    <p class='child'>5</p>
  </div>
  <div class='step' id=step8>
    <p class='child'>9</p>
  </div>
  <div class='step' id=step9>
    <p class='child'>10</p>
  </div></code>```

I also recommend to not use negative margin's in the way you do in this sample, I suggest you do something like this instead, where you use margin's on the flex items child instead

I also used viewport units on all margin's instead of percent.

.outer {
  display: flex;
  flex-wrap: wrap;
}

.step {
  text-align: center;
  height: 100px;
  flex-grow: 1;
  flex-basis: 25%;
  overflow: auto;
}

.child {
  border: 2px solid black;
  margin: 5vh 5vw 0 5vw;
  height: calc(100% - 5vh);
  font-size: 1.25em;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer" id="container">
  <div class='step' id=step0>
    <p class='child'> 1</p>
  </div>
  <div class='step' id=step1>
    <p class='child'> 2</p>
  </div>
  <div class='step' id=step2>
    <p class='child'>3</p>
  </div>
  <div class='step' id=step3>
    <p class='child'> 4</p>
  </div>
  <div class='step error' id=step7>
    <p class='child'>8</p>
  </div>
  <div class='step' id=step6>
    <p class='child'>7</p>
  </div>
  <div class='step' id=step5>
    <p class='child'>6</p>
  </div>
  <div class='step' id=step4>
    <p class='child'>5</p>
  </div>
  <div class='step' id=step8>
    <p class='child'>9</p>
  </div>
  <div class='step' id=step9>
    <p class='child'>10</p>
  </div></code>```

Body:
I am currently learning flex CSS property, and I am using it display a bunch of divs with four per row at maximum. Here is HTML and CSS for it:

.outer {
  display: flex;
  flex-wrap: wrap;
  margin: -5% -5% 0 -5%;
}

.step {
  text-align: center;
  display: inline-block;
  border: 2px solid black;
  margin: 5% 5% 0 5%;
  flex-grow: 1;
  height: 100px;
  width: 13%;
  overflow: auto;
}

.child {
  font-size: 1.25em;
}

 1

 2

3

 4

8

7

6

5

9

10

The css Works exactly the way I want it to work in Chrome, but in firefox vertical gap between different rows is zero, while it is not so in Chrome. What am I doing wrong?
(I have made a fiddle as well, https://jsfiddle.net/vLmnq7fL/2/ . Open in Chrome and firefox to see the difference)

Body:
Using percent for padding's and margin's on flex items might render in different outputs on different browser since the spec's let them.

Also, when using percent for the top value in your margin:5%5% 0 5%; will be based on the parent's width, not height, will as well can give unpredictable result.

If you use viewport units it won't though margin:5vh5% 0 5%;

.outer {
  display: flex;
  flex-wrap: wrap;
  margin: -5vh -5% 0 -5%;
}

.step {
  text-align: center;
  display: inline-block;
  border: 2px solid black;
  margin: 5vh 5% 0 5%;
  flex-grow: 1;
  height: 100px;
  width: 13%;
  overflow: auto;
}

.child {
  font-size: 1.25em;
}

<div class="outer" id="container">
  <div class='step' id=step0>
    <p class='child'> 1</p>
  </div>
  <div class='step' id=step1>
    <p class='child'> 2</p>
  </div>
  <div class='step' id=step2>
    <p class='child'>3</p>
  </div>
  <div class='step' id=step3>
    <p class='child'> 4</p>
  </div>
  <div class='step error' id=step7>
    <p class='child'>8</p>
  </div>
  <div class='step' id=step6>
    <p class='child'>7</p>
  </div>
  <div class='step' id=step5>
    <p class='child'>6</p>
  </div>
  <div class='step' id=step4>
    <p class='child'>5</p>
  </div>
  <div class='step' id=step8>
    <p class='child'>9</p>
  </div>
  <div class='step' id=step9>
    <p class='child'>10</p>
  </div>

I also recommend to not use negative margin's in the way you do in this sample, I suggest you do something like this instead, where you use margin's on the flex items child instead

I also used viewport units on all margin's instead of percent.

.outer {
  display: flex;
  flex-wrap: wrap;
}

.step {
  text-align: center;
  height: 100px;
  flex-grow: 1;
  flex-basis: 25%;
  overflow: auto;
}

.child {
  border: 2px solid black;
  margin: 5vh 5vw 0 5vw;
  height: calc(100% - 5vh);
  font-size: 1.25em;
  box-sizing: border-box;
}

<div class="outer" id="container">
  <div class='step' id=step0>
    <p class='child'> 1</p>
  </div>
  <div class='step' id=step1>
    <p class='child'> 2</p>
  </div>
  <div class='step' id=step2>
    <p class='child'>3</p>
  </div>
  <div class='step' id=step3>
    <p class='child'> 4</p>
  </div>
  <div class='step error' id=step7>
    <p class='child'>8</p>
  </div>
  <div class='step' id=step6>
    <p class='child'>7</p>
  </div>
  <div class='step' id=step5>
    <p class='child'>6</p>
  </div>
  <div class='step' id=step4>
    <p class='child'>5</p>
  </div>
  <div class='step' id=step8>
    <p class='child'>9</p>
  </div>
  <div class='step' id=step9>
    <p class='child'>10</p>
  </div>


问:
Dynamically sized charts in SSRS 2008R2
I'm stuck on an issue where I want my bar chart to grow vertically based on the number of groups display in my graph.

I have a shared dataset looking at a SharePoint list then I have a dataset
in my report referencing this but applying some filters based on date ranges.  I've then set that as the dataset for my graph which works neatly but there's a widely varying number of potential grouping categories to be displayed.  I was looking at this article here which is a neat way to do it, but I don't want a manually set parameter, I just want it to grow based on whatever shows up. One thought I had was in the DynamicHeight expression was to check the number of "CategoryGroups" that show up but I can't see a way of getting to the chart object in the VB expression editor.

I saw an example of doing group by in SQL in the dataset editor but I don't get that option looking at a SharePoint list.  Is there a way in DynamicHeight expression editor to reference report objects?

答:
Similar to the article, you can use a distinct count of the group items in a expression in order to dynamically size your chart.

The expression could look like:

```<code>=  (2 + CountDistinct(Fields!item.Value, "DataSet1")) & ” cm”
</code>```

Which is (minimum size + size for each group item) in cm (or any unit you prefer)

Title: Dynamically sized charts in SSRS 2008R2

Body:
Similar to the article, you can use a distinct count of the group items in a expression in order to dynamically size your chart.

The expression could look like:

=  (2 + CountDistinct(Fields!item.Value, "DataSet1")) & ” cm”

Which is (minimum size + size for each group item) in cm (or any unit you prefer)


问:
How to revert search portlet configuration json for facets?
We had updated search portlet configuration facets configuration json with new facets.The purpose was to show documents and media files with a given set of file extension by adding the below json to the existing configuration json.
We referred the given link Faceted search to add the below json:

{
    "displayStyle": "asset_entries",
    "static": true,
    "weight": 1.5,
    "order": "OrderHitsDesc",
    "data": {
    "values": [
        "com.liferay.portlet.documentlibrary.model.DLFileEntry"
    ],
    "frequencyThreshold": 0
    },
    "className": "com.liferay.portal.kernel.search.facet.AssetEntriesFacet",
    "label": "asset-type",
    "fieldName": "entryClassName"
},
{
    "displayStyle": "asset_entries",
    "static": true,
    "weight": 1.5,
    "order": "OrderHitsDesc",
    "data": {
    "values": ["bmp", "gif", "jpeg", "jpg", "odg", "png", "svg"],
    "frequencyThreshold": 0
    },
    "className": "com.liferay.portal.kernel.search.facet.MultiValueFacet",
    "label": "images",
    "fieldName": "extension"
}

which throws the below exception

```<code>org.json.JSONException: Expected a ',' or ']' at 4141 [character 1 line 138]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONArray.<init>(JSONArray.java:129)
at org.json.JSONTokener.nextValue(JSONTokener.java:366)
at org.json.JSONObject.<init>(JSONObject.java:212)
at org.json.JSONObject.<init>(JSONObject.java:314)
</code>```

Now accessing the search portlet configuration throws a blank page.How can I fix this?

答:
On analysing the source code,the file configuration.jsp in directory portal-web\docroot\html\portlet\searchgenerates the configuration view.
The given code

```<code>JSONObject searchConfigurationJSONObject = JSONFactoryUtil.createJSONObject(searchConfiguration);
</code>```

retrieves search config from

String searchConfiguration = portletPreferences.getValue("searchConfiguration", StringPool.BLANK);

Hence we had to manually update search configuration in DB in portletpreferencestable to update the json with the missing ,before the start of the added json.
Please suggest any other cleaner approach to solve this issue,if any.

Body:
We had updated search portlet configuration facets configuration json with new facets.The purpose was to show documents and media files with a given set of file extension by adding the below json to the existing configuration json.
We referred the given link Faceted search to add the below json:

{
    "displayStyle": "asset_entries",
    "static": true,
    "weight": 1.5,
    "order": "OrderHitsDesc",
    "data": {
    "values": [
        "com.liferay.portlet.documentlibrary.model.DLFileEntry"
    ],
    "frequencyThreshold": 0
    },
    "className": "com.liferay.portal.kernel.search.facet.AssetEntriesFacet",
    "label": "asset-type",
    "fieldName": "entryClassName"
},
{
    "displayStyle": "asset_entries",
    "static": true,
    "weight": 1.5,
    "order": "OrderHitsDesc",
    "data": {
    "values": ["bmp", "gif", "jpeg", "jpg", "odg", "png", "svg"],
    "frequencyThreshold": 0
    },
    "className": "com.liferay.portal.kernel.search.facet.MultiValueFacet",
    "label": "images",
    "fieldName": "extension"
}

which throws the below exception

org.json.JSONException: Expected a ',' or ']' at 4141 [character 1 line 138]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONArray.<init>(JSONArray.java:129)
at org.json.JSONTokener.nextValue(JSONTokener.java:366)
at org.json.JSONObject.<init>(JSONObject.java:212)
at org.json.JSONObject.<init>(JSONObject.java:314)

Now accessing the search portlet configuration throws a blank page.How can I fix this?

Body:
On analysing the source code,the file configuration.jsp in directory portal-web\docroot\html\portlet\searchgenerates the configuration view.
The given code

JSONObject searchConfigurationJSONObject = JSONFactoryUtil.createJSONObject(searchConfiguration);

retrieves search config from

String searchConfiguration = portletPreferences.getValue("searchConfiguration", StringPool.BLANK);

Hence we had to manually update search configuration in DB in portletpreferencestable to update the json with the missing ,before the start of the added json.
Please suggest any other cleaner approach to solve this issue,if any.


问:
Exporting aws management console settings
When using the aws web management console it's very handy to add favourite services and switch between different roles. However when using a different browser or different computer with the same login it's not showing up.

How to export these settings so they can be imported or synced between computers?

答: That is not supported my AWS Management Console</p>


问:
Python - split a list into many lists in a for loop
Given this input:

```<code>['1636 19 02 2F', '1637 19 02 2F', '1631 19 02 2F']
</code>```

I'd like to produce this output:

```<code>['1636']
['19']
['02']
['2F']
['1637']
['19']
['02']
['2F']
</code>```

I tried:

```<code>byte = ['1636 19 02 2F', '1637 19 02 2F', '1631 19 02 2F']

for i in byte:
    d = i.split(' ')
    list_byte = d # ('\n'.join(d))
    print(list(list_byte,))
</code>```

But its output is:

```<code>['1636', '19', '02', '2F']
['1637', '19', '02', '2F']
</code>```

I have also tried a nested loop but then it splits into every character and join but that just wrote out the wrong type.

How can I have the output in separate lists, like this?

```<code>['1636']
['19']
['02']
['2F']
['1637']
['19']
['02']
['2F']
</code>```

Body:
Given this input:

['1636 19 02 2F', '1637 19 02 2F', '1631 19 02 2F']

I'd like to produce this output:

['1636']
['19']
['02']
['2F']
['1637']
['19']
['02']
['2F']

I tried:

byte = ['1636 19 02 2F', '1637 19 02 2F', '1631 19 02 2F']

for i in byte:
    d = i.split(' ')
    list_byte = d # ('\n'.join(d))
    print(list(list_byte,))

But its output is:

['1636', '19', '02', '2F']
['1637', '19', '02', '2F']

I have also tried a nested loop but then it splits into every character and join but that just wrote out the wrong type.

How can I have the output in separate lists, like this?

['1636']
['19']
['02']
['2F']
['1637']
['19']
['02']
['2F']

Body:
for a_string in byte:
    for split_result in a_string.split(' '):
        print [split_result]

This gives you a print in the format...

['1636']
['19']
['02']
['2F']
['1637']
['19']
['02']
['2F']
['1631']
['19']
['02']
['2F']


问:
How do I place a UIWebView in a table view cell and maintain its scroll bars?
How can I place a UIWebView in a table view cell, yet maintain the UIWebView's scrollbars?  My table view does have multiple cells and a header frame as well, and I do need it to be scrollable because it has many rows.

The text displays perfectly fine when I use UITextView and it shows scrollers as well, but the problem is that my content is rich text, so I don't have any other option but to show the content in UIWebView. Any ideas, hacks?

答:
The problem with adding UIWebView into a table cell is both these objects are scrollable (tableview and webview) which will create complications if not used appropriately. Does you tableview have any cells other than uiwebview? and do you need the tableview to be scrollable? In case the tableview need not be scrollable, make scrolling enabled in the webview and disabled for the tableview. That should work.

But if you want to just display text, why not use a UITextView (though you'll face the same problem for UITextView too)?

OwnerDisplayName: Mustafa

OwnerDisplayName: lostInTransit


问:
Modifying an Android Libraries' package using gradle
Is it, or would it be possible to modify a libraries' packagename at compile time using a gradle task similar to how jarjar works for changing the packagenames of a .jar file.

The library is pretty standard and included as follows:

```<code>dependencies {
    compile 'com.scottyab:rootbeer-lib:0.0.6'
}
</code>```

The purpose of this would be to change the name to avoid static detection of the library by root cloaking apps.

Any advice or guidance much appreciated! Thanks

答:
There is already a Gradle plugin that does something similar. It relocates dependencies, Shadow.

It bundles and relocates common dependencies in libraries to avoid classpath conflicts.Shadow uses the ASM library to modify class byte code to replace the package name and any import statements for a class. Any non-class files that are stored within a package structure are also relocated to the new location.

This is how you relocate a package:

```<code>shadowJar {
   relocate 'junit.framework', 'shadow.junit'
}
</code>```

The code snippet will rewrite the location for any class in the junit.framework to be shadow.junit. For example, the class junit.textui.TestRunner becomes shadow.junit.TestRunner. In the resulting JAR, the class file is relocated from junit/textui/TestRunner.class to shadow/junit/TestRunner.class.

Body:
Is it, or would it be possible to modify a libraries' packagename at compile time using a gradle task similar to how jarjar works for changing the packagenames of a .jar file.

The library is pretty standard and included as follows:

dependencies {
    compile 'com.scottyab:rootbeer-lib:0.0.6'
}

The purpose of this would be to change the name to avoid static detection of the library by root cloaking apps.

Any advice or guidance much appreciated! Thanks

Body:
There is already a Gradle plugin that does something similar. It relocates dependencies, Shadow.

It bundles and relocates common dependencies in libraries to avoid classpath conflicts.Shadow uses the ASM library to modify class byte code to replace the package name and any import statements for a class. Any non-class files that are stored within a package structure are also relocated to the new location.

This is how you relocate a package:

shadowJar {
   relocate 'junit.framework', 'shadow.junit'
}

The code snippet will rewrite the location for any class in the junit.framework to be shadow.junit. For example, the class junit.textui.TestRunner becomes shadow.junit.TestRunner. In the resulting JAR, the class file is relocated from junit/textui/TestRunner.class to shadow/junit/TestRunner.class.


问:
Mass find and replace with a Bass Script in PHP Application
In a Zend Framework 2 application, there are 8/9 modules. In these modules, the View has over 15 odd phtml pages with hard coded links like

```<code>href='/controller/action'
</code>```

What I need to do is build a bash script which will go through the modules look for places in which the view has the href above and change it to look like this

```<code>href="<?php $this->url('controller'), action->'action' ?>"
</code>```

答:
You could loop through the modules attaining the filenames and then:

```<code> sed -r "s%href='/(.*)/(.*)'$%href=\"<?php $this->url('\1'), action->'\2' ?>\"%" filename
</code>```

s%original text%replacement text%

Use -r to enable the interpretation of regular expressions

Make sure that you escape the quotation marks in the replacement text with \

Use (.*) as place holders for the dynamic text and then refer to them as \1 and \2 in the replacement text.

Body:
In a Zend Framework 2 application, there are 8/9 modules. In these modules, the View has over 15 odd phtml pages with hard coded links like

href='/controller/action'

What I need to do is build a bash script which will go through the modules look for places in which the view has the href above and change it to look like this

href="<?php $this->url('controller'), action->'action' ?>"

Body:
You could loop through the modules attaining the filenames and then:

 sed -r "s%href='/(.*)/(.*)'$%href=\"<?php $this->url('\1'), action->'\2' ?>\"%" filename

s%original text%replacement text%

Use -r to enable the interpretation of regular expressions

Make sure that you escape the quotation marks in the replacement text with \

Use (.*) as place holders for the dynamic text and then refer to them as \1 and \2 in the replacement text.


问:
How to find exact querystring value in angular js
How to find exact querystring parameter value in angularjs

```<code>Querystring is-->http://localhost/Emp/EmpInfoPage.aspx?empId=104569&empAccessId=100,101,102&empLoc=IND
</code>```

So,I need to find out exact empAccessId=100,101,102 which has comma too.
Thanks is Advance

答:
You can use this npm package called Query String Manager
That package has a two relevant methods for your.

first method is called get() which works like this

```<code>var accessId = qsm.get(window.location.href, 'empAccessId');
// accessId === 100,101,102
</code>```

the second method is called objectify() and this returns the correct datatype for the querystring aswell, which means a comma separated string converts into an array like this

```<code>var queryObj = qsm.objectify('http://localhost/Emp/EmpInfoPage.aspx?empId=104569&empAccessId=100,101,102&empLoc=IND');

queryObj = {
  empId: 104569, // <- this is an integer/number
  empAccessId: [100, 101, 102], // <- this is an array
  empLoc: 'IND' // <- this is a regular string.
}
</code>```

Body:
How to find exact querystring parameter value in angularjs

Querystring is-->http://localhost/Emp/EmpInfoPage.aspx?empId=104569&empAccessId=100,101,102&empLoc=IND

So,I need to find out exact empAccessId=100,101,102 which has comma too.
Thanks is Advance

Body:
You can use this npm package called Query String Manager
That package has a two relevant methods for your.

first method is called get() which works like this

var accessId = qsm.get(window.location.href, 'empAccessId');
// accessId === 100,101,102

the second method is called objectify() and this returns the correct datatype for the querystring aswell, which means a comma separated string converts into an array like this

var queryObj = qsm.objectify('http://localhost/Emp/EmpInfoPage.aspx?empId=104569&empAccessId=100,101,102&empLoc=IND');

queryObj = {
  empId: 104569, // <- this is an integer/number
  empAccessId: [100, 101, 102], // <- this is an array
  empLoc: 'IND' // <- this is a regular string.
}


答:
You can use exists or an inner join:

```<code>SELECT *
FROM ORDER_INSTALMENT o
WHERE EXISTS
(
    SELECT 1
    FROM ORDER_INSTALMENT i
    WHERE o.DATEDUE = i.DATEDUE
    AND i.<UniqueColumnName> <> o.<UniqueColumnName>
)
</code>```

Or

```<code>SELECT DISTINCT t1.*
FROM ORDER_INSTALMENT t1
INNER JOIN ORDER_INSTALMENT t2
ON t1.DATEDUE = t2.DATEDUE
AND t1.<UniqueColumnName> <> t2.<UniqueColumnName>
</code>```

Please note that you need to change <UniqueColumnName> to a column name that is unique in your table.

Another option:

```<code>;WITH CTE AS
(
    SELECT DATEDUE, COUNT(*) As NumberOfRows
    FROM ORDER_INSTALMENT
    GROUP BY DATEDUE
)
SELECT *
FROM ORDER_INSTALMENT t
INNER JOIN CTE
ON t.DATEDUE = CTE.DATEDUE
WHERE NumberOfRows > 1
</code>```

Title: Searching for records with the same date

Body:
You can use exists or an inner join:

SELECT *
FROM ORDER_INSTALMENT o
WHERE EXISTS
(
    SELECT 1
    FROM ORDER_INSTALMENT i
    WHERE o.DATEDUE = i.DATEDUE
    AND i.<UniqueColumnName> <> o.<UniqueColumnName>
)

Or

SELECT DISTINCT t1.*
FROM ORDER_INSTALMENT t1
INNER JOIN ORDER_INSTALMENT t2
ON t1.DATEDUE = t2.DATEDUE
AND t1.<UniqueColumnName> <> t2.<UniqueColumnName>

Please note that you need to change <UniqueColumnName> to a column name that is unique in your table.

Another option:

;WITH CTE AS
(
    SELECT DATEDUE, COUNT(*) As NumberOfRows
    FROM ORDER_INSTALMENT
    GROUP BY DATEDUE
)
SELECT *
FROM ORDER_INSTALMENT t
INNER JOIN CTE
ON t.DATEDUE = CTE.DATEDUE
WHERE NumberOfRows > 1


问:
How to create data in Json format for highcharts
I am getting below result through ajax and the data which I get in ajax success is

```<code>[{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}]
</code>```

I am trying to convert this data to format

```<code>[{
  name: 'MCW',
  data: [6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000
]},{
  name: 'SJCPL',
  data: [4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385]
}]
</code>```

I am trying to convert to this format for generating highcharts as https://jsfiddle.net/mcj075jf/

How do I convert to the above format in jQuery using for loop or $.each. Please help.

答:
Here you go with the solution https://jsfiddle.net/z10jheo2/</p>

```<code>var data = [{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}];

var newData = [];

for(var i=0; i<data.length; i++) {
   var tempData = {};
   tempData.name = data[i].plant_name;
   tempData.data = data[i].employees_data.split(',');
   newData.push(tempData);
   console.log(newData);
}
</code>```

Body:
I am getting below result through ajax and the data which I get in ajax success is

[{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}]

I am trying to convert this data to format

[{
  name: 'MCW',
  data: [6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000
]},{
  name: 'SJCPL',
  data: [4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385]
}]

I am trying to convert to this format for generating highcharts as https://jsfiddle.net/mcj075jf/

How do I convert to the above format in jQuery using for loop or $.each. Please help.

Body:
Here you go with the solution https://jsfiddle.net/z10jheo2/

var data = [{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}];

var newData = [];

for(var i=0; i<data.length; i++) {
   var tempData = {};
   tempData.name = data[i].plant_name;
   tempData.data = data[i].employees_data.split(',');
   newData.push(tempData);
   console.log(newData);
}


问:
How to write Join and where in Spark DataFrame (Converting SQL to DataFrame)
I need to write SQL Query into DataFrame

SQL Query

A_join_Deals = sqlContext.sql("SELECT * FROM A_transactions LEFT
JOIN Deals ON (Deals.device = A_transactions.device_id) WHERE
A_transactions.device_id IS NOT NULL AND A_transactions.device_id != '' AND
A_transactions.advertiser_app_object_id = '%s'"%(adv_id))
```

<p><strong>Code written up to now</strong></p>

<pre class="lang-scala prettyprint-override"><code>val A_join_Deals = Deals.join(A_transactions,Deals("device") === A_transactions("device_id"),"left")
</code>```

Now I am stuck how to write the where Clause.

Any Suggestion or Help is Highly appreciated.

答:
Here is what you can do

```<code>where(A_transactions("device_id").isNotNull &&
   A_transactions("device_id") =!= "" &&
   A_transactions("advertiser_app_object_id") === s"${adv_id}%")
</code>```

This works if adv_id is a variable and not Column

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I need to write SQL Query into DataFrame

SQL Query

A_join_Deals = sqlContext.sql("SELECT * FROM A_transactions LEFT
JOIN Deals ON (Deals.device = A_transactions.device_id) WHERE
A_transactions.device_id IS NOT NULL AND A_transactions.device_id != '' AND
A_transactions.advertiser_app_object_id = '%s'"%(adv_id))

Code written up to now

val A_join_Deals = Deals.join(A_transactions,Deals("device") === A_transactions("device_id"),"left")

Now I am stuck how to write the where Clause.

Any Suggestion or Help is Highly appreciated.

Body:
Here is what you can do

where(A_transactions("device_id").isNotNull &&
   A_transactions("device_id") =!= "" &&
   A_transactions("advertiser_app_object_id") === s"${adv_id}%")

This works if adv_id is a variable and not Column

Hope this helps!


答:
```<code>override func viewDidAppear(_ animated: Bool) {
let label = UILabel(frame: CGRect(x: 0, y: (navigationController?.navigationBar.frame.height)! + 20, width: UIScreen.main.bounds.width, height: 40))
label.translatesAutoresizingMaskIntoConstraints = true
label.text = "Hello"
label.backgroundColor = UIColor.red
self.view.addSubview(label)

}
</code>```

Title: How do I programmatically add a view right under the navigation bar?

Body:
I'm trying to add a view to a UINavigationController with its top aligned with the navigation bar's bottom.

I tried using constraints by adding the following to my UINavigationController subclass:

override func viewDidAppear(_ animated: Bool) {
           self.label = UILabel()
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)
    let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
                                           toItem: topLayoutGuide, attribute: .bottom,
                                           multiplier: 1.0, constant: 0.0)
    let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)

    let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horConstraint, widthConstr, heightConstr])
}

With this being the result:

And I tried by setting the frame of my subview:

override func viewDidAppear(_ animated: Bool) {

    self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
    self.label?.translatesAutoresizingMaskIntoConstraints = false
    self.label?.backgroundColor = UIColor.red
    self.label?.text = "label text"
    self.view.addSubview(self.label!)

}

And this came out:

In both cases my label covers part of the navigation bar. How to I fix this?


问:
How to mock static method without powermock
Is there any way we can mock the static util method while testing in JUnit?

I know Powermock can mock static calls, but I don't want to use Powermock.

Are there any alternatives?

答:
(I assume you can use Mockito though) Nothing dedicated comes to my mind but I tend to use the following strategy when it comes to situations like that:

1) In the class under test, replace the static direct call with a call to a package level method that wraps the static call itself:

```<code>public class ToBeTested{

    public void myMethodToTest(){
         ...
         String s = makeStaticWrappedCall();
         ...
    }

    String makeStaticWrappedCall(){
        return Util.staticMethodCall();
    }
}
</code>```

2) Spy the class under test while testing and mock the wrapped package level method:

```<code>public class ToBeTestedTest{

    @Spy
    ToBeTested tbTestedSpy = new ToBeTested();

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void myMethodToTestTest() throws Exception{
       // Arrange
       doReturn("Expected String").when(tbTestedSpy).makeStaticWrappedCall();

       // Act
       tbTestedSpy.myMethodToTest();
    }
}
</code>```

Here is an article I wrote on spying that includes similar case, if you need more insight: sourceartists.com/mockito-spying

Body:
(I assume you can use Mockito though) Nothing dedicated comes to my mind but I tend to use the following strategy when it comes to situations like that:

1) In the class under test, replace the static direct call with a call to a package level method that wraps the static call itself:

public class ToBeTested{

    public void myMethodToTest(){
         ...
         String s = makeStaticWrappedCall();
         ...
    }

    String makeStaticWrappedCall(){
        return Util.staticMethodCall();
    }
}

2) Spy the class under test while testing and mock the wrapped package level method:

public class ToBeTestedTest{

    @Spy
    ToBeTested tbTestedSpy = new ToBeTested();

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void myMethodToTestTest() throws Exception{
       // Arrange
       doReturn("Expected String").when(tbTestedSpy).makeStaticWrappedCall();

       // Act
       tbTestedSpy.myMethodToTest();
    }
}

Here is an article I wrote on spying that includes similar case, if you need more insight: sourceartists.com/mockito-spying


问:
Bootstrap toggle switch onclick in Spring
I am unable to fire onclick event after i click confirm on the pop up when i click the toggle switch. Anybody know what i wrong with it?

View

```<code><td><a onclick="return confirmDelete(this, '<c:url value='active-user-${user.name}' />')"><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" type="checkbox"></a></td>
</code>```

Script

```<code> function confirmDelete(delForm, delUrl) {
                var stateValue = $("#tblClient #activeSwitch").is(":checked");

                if (confirm("Do you want to inActive this user?")) {
                            delForm.href = delUrl;
                            elForm.submit();

                            return true;
                        }

                        $('#tblClient #activeSwitch').bootstrapSwitch('toggleState', true, true);
                            return false;

                };
</code>```

答:
Why are you returning the function in the HTML?
You don't need to return the function. It's the function who returns something. So you just call the function normally without returning.</p>

Body:
I am unable to fire onclick event after i click confirm on the pop up when i click the toggle switch. Anybody know what i wrong with it?

View

<a onclick="return confirmDelete(this, '<c:url value='active-user-${user.name}' />')"><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" type="checkbox">

Script

 function confirmDelete(delForm, delUrl) {
                var stateValue = $("#tblClient #activeSwitch").is(":checked");

                if (confirm("Do you want to inActive this user?")) {
                            delForm.href = delUrl;
                            elForm.submit();

                            return true;
                        }

                        $('#tblClient #activeSwitch').bootstrapSwitch('toggleState', true, true);
                            return false;

                };


答:
When you have static code that gives you trouble in your unit tests; so that you feel you have to "mock it away", you have exactly these options:

You turn to PowerMock(ito). Works fine.

You turn to JMockit. Works fine, too.

If you are testing code you have written yourself, you might want to step back and ask yourself: "why did I write code that I now find hard to unit test?"

In other words: if you want to use a mocking framework, you have to use one of those listed above. On the one side, that is absolutely fair. static is one part of the Java language; so why not use a framework that allows you to deal with it?

But of course: you still have the static call in your production code then. Leading to tight coupling, and preventing polymorphism.

So: if you can get rid of the static call (even when just using the workaround suggested in the other answer) - all the better. If not: Mockito can't help; you need the magic of byte code manipulation resp. JVM agents.

Title: How to mock static method without powermock

Body:
Is there any way we can mock the static util method while testing in JUnit?

I know Powermock can mock static calls, but I don't want to use Powermock.

Are there any alternatives?


问:
Calculate/validate bz2 (bzip2) CRC32 in Python
I'm trying to calculate/validate the CRC32 checksums for compressed bzip2 archives.

```<code>.magic:16                       = 'BZ' signature/magic number
.version:8                      = 'h' for Bzip2 ('H'uffman coding)
.hundred_k_blocksize:8          = '1'..'9' block-size 100 kB-900 kB

.compressed_magic:48            = 0x314159265359 (BCD (pi))
.crc:32                         = checksum for this block
...
...
.eos_magic:48                   = 0x177245385090 (BCD sqrt(pi))
.crc:32                         = checksum for whole stream
.padding:0..7                   = align to whole byte
</code>```

http://en.wikipedia.org/wiki/Bzip2

So I know where the CRC checksums are in a bz2 file, but how would I go about validating them. What chunks should I binascii.crc32() to get both CRCs? I've tried calculating the CRC of various chunks, byte-by-byte, but have not managed to get a match.

Thank you. I'll be looking into the bzip2 sources and bz2 Python library code, to maybe find something, especially in the decompress() method.

Update 1:

The block headers are identified by the following tags as far as I can see. But tiny bz2 files do not contain the ENDMARK ones. (Thanks to adw, we've found out that one should look for bit shifted values of the ENDMARK, since the compressed data is not padded to bytes.)

```<code>#define BLOCK_HEADER_HI  0x00003141UL
#define BLOCK_HEADER_LO  0x59265359UL

#define BLOCK_ENDMARK_HI 0x00001772UL
#define BLOCK_ENDMARK_LO 0x45385090UL
</code>```

This is from the bzlib2recover.c source, blocks seem to start always at bit 80, right before the CRC checksum, which should be omitted from the CRC calculation, as one can't CRC its own CRC to be the same CRC (you get my point).

```<code>searching for block boundaries ...
block 1 runs from 80 to 1182
</code>```

Looking into the code that calculates this.

Update 2:

bzlib2recover.c does not have the CRC calculating functions, it just copies the CRC from the damaged files. However, I did manage to replicate the block calculator functionality in Python, to mark out the starting and ending bits of each block in a bz2 compressed file. Back on track, I have found that compress.c refers to some of the definitions in bzlib_private.h.

```<code>#define BZ_INITIALISE_CRC(crcVar) crcVar = 0xffffffffL;
#define BZ_FINALISE_CRC(crcVar) crcVar = ~(crcVar);
#define BZ_UPDATE_CRC(crcVar,cha)              \
{                                              \
   crcVar = (crcVar << 8) ^                    \
            BZ2_crc32Table[(crcVar >> 24) ^    \
                           ((UChar)cha)];      \
}
</code>```

These definitions are accessed by bzlib.c as well, s->blockCRC is initialized and updated in bzlib.c and finalized in compress.c. There's more than 2000 lines of C code, which will take some time to look through and figure out what goes in and what does not. I'm adding the C tag to the question as well.

By the way, here are the C sources for bzip2 http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz

Update 3:

Turns out bzlib2 block CRC32 is calculated using the following algorithm:

dataIn is the data to be encoded.

```<code>crcVar = 0xffffffff # Init
    for cha in list(dataIn):
        crcVar = crcVar & 0xffffffff # Unsigned
        crcVar = ((crcVar << 8) ^ (BZ2_crc32Table[(crcVar >> 24) ^ (ord(cha))]))

    return hex(~crcVar & 0xffffffff)[2:-1].upper()
</code>```

Where BZ2_crc32Table is defined in crctable.c

For dataIn = "justatest" the CRC returned is 7948C8CB, having compressed a textfile with that data, the crc:32 checksum inside the bz2 file is 79 48 c8 cb which is a match.

Conclusion:

bzlib2 CRC32 is (quoting crctable.c)

Vaguely derived from code by Rob
  Warnock, in Section 51 of the
  comp.compression FAQ...

...thus, as far as I understand, cannot be precalculated/validated using standard CRC32 checksum calculators, but rather require the bz2lib implementation (lines 155-172 in bzlib_private.h).

答:
The following is the CRC algorithm used by bzip2, written in Python:

```<code>crcVar = 0xffffffff # Init
    for cha in list(dataIn):
        crcVar = crcVar & 0xffffffff # Unsigned
        crcVar = ((crcVar << 8) ^ (BZ2_crc32Table[(crcVar >> 24) ^ (ord(cha))]))

    return hex(~crcVar & 0xffffffff)[2:-1].upper()
</code>```

(C code definitions can be found on lines 155-172 in bzlib_private.h)

BZ2_crc32Table array/list can be found in crctable.c from the bzip2 source code. This CRC checksum algorithm is, quoting: "..vaguely derived from code by Rob Warnock, in Section 51 of the comp.compression FAQ..." (crctable.c)

The checksums are calculated over the uncompressed data.

Sources can be downloaded here: http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz

Body:
I'm trying to calculate/validate the CRC32 checksums for compressed bzip2 archives.

.magic:16                       = 'BZ' signature/magic number
.version:8                      = 'h' for Bzip2 ('H'uffman coding)
.hundred_k_blocksize:8          = '1'..'9' block-size 100 kB-900 kB

.compressed_magic:48            = 0x314159265359 (BCD (pi))
.crc:32                         = checksum for this block
...
...
.eos_magic:48                   = 0x177245385090 (BCD sqrt(pi))
.crc:32                         = checksum for whole stream
.padding:0..7                   = align to whole byte

http://en.wikipedia.org/wiki/Bzip2

So I know where the CRC checksums are in a bz2 file, but how would I go about validating them. What chunks should I binascii.crc32() to get both CRCs? I've tried calculating the CRC of various chunks, byte-by-byte, but have not managed to get a match.

Thank you. I'll be looking into the bzip2 sources and bz2 Python library code, to maybe find something, especially in the decompress() method.

Update 1:

The block headers are identified by the following tags as far as I can see. But tiny bz2 files do not contain the ENDMARK ones. (Thanks to adw, we've found out that one should look for bit shifted values of the ENDMARK, since the compressed data is not padded to bytes.)

#define BLOCK_HEADER_HI  0x00003141UL
#define BLOCK_HEADER_LO  0x59265359UL

#define BLOCK_ENDMARK_HI 0x00001772UL
#define BLOCK_ENDMARK_LO 0x45385090UL

This is from the bzlib2recover.c source, blocks seem to start always at bit 80, right before the CRC checksum, which should be omitted from the CRC calculation, as one can't CRC its own CRC to be the same CRC (you get my point).

searching for block boundaries ...
block 1 runs from 80 to 1182

Looking into the code that calculates this.

Update 2:

bzlib2recover.c does not have the CRC calculating functions, it just copies the CRC from the damaged files. However, I did manage to replicate the block calculator functionality in Python, to mark out the starting and ending bits of each block in a bz2 compressed file. Back on track, I have found that compress.c refers to some of the definitions in bzlib_private.h.

#define BZ_INITIALISE_CRC(crcVar) crcVar = 0xffffffffL;
#define BZ_FINALISE_CRC(crcVar) crcVar = ~(crcVar);
#define BZ_UPDATE_CRC(crcVar,cha)              \
{                                              \
   crcVar = (crcVar << 8) ^                    \
            BZ2_crc32Table[(crcVar >> 24) ^    \
                           ((UChar)cha)];      \
}

These definitions are accessed by bzlib.c as well, s->blockCRC is initialized and updated in bzlib.c and finalized in compress.c. There's more than 2000 lines of C code, which will take some time to look through and figure out what goes in and what does not. I'm adding the C tag to the question as well.

By the way, here are the C sources for bzip2 http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz

Update 3:

Turns out bzlib2 block CRC32 is calculated using the following algorithm:

dataIn is the data to be encoded.

crcVar = 0xffffffff # Init
    for cha in list(dataIn):
        crcVar = crcVar & 0xffffffff # Unsigned
        crcVar = ((crcVar << 8) ^ (BZ2_crc32Table[(crcVar >> 24) ^ (ord(cha))]))

    return hex(~crcVar & 0xffffffff)[2:-1].upper()

Where BZ2_crc32Table is defined in crctable.c

For dataIn = "justatest" the CRC returned is 7948C8CB, having compressed a textfile with that data, the crc:32 checksum inside the bz2 file is 79 48 c8 cb which is a match.

Conclusion:

bzlib2 CRC32 is (quoting crctable.c)

Vaguely derived from code by Rob
  Warnock, in Section 51 of the
  comp.compression FAQ...

...thus, as far as I understand, cannot be precalculated/validated using standard CRC32 checksum calculators, but rather require the bz2lib implementation (lines 155-172 in bzlib_private.h).

Body:
The following is the CRC algorithm used by bzip2, written in Python:

crcVar = 0xffffffff # Init
    for cha in list(dataIn):
        crcVar = crcVar & 0xffffffff # Unsigned
        crcVar = ((crcVar << 8) ^ (BZ2_crc32Table[(crcVar >> 24) ^ (ord(cha))]))

    return hex(~crcVar & 0xffffffff)[2:-1].upper()

(C code definitions can be found on lines 155-172 in bzlib_private.h)

BZ2_crc32Table array/list can be found in crctable.c from the bzip2 source code. This CRC checksum algorithm is, quoting: "..vaguely derived from code by Rob Warnock, in Section 51 of the comp.compression FAQ..." (crctable.c)

The checksums are calculated over the uncompressed data.

Sources can be downloaded here: http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz


问:
TLS certificate installation in ejabberd for STARTTLS negotiation
I read that ejabberd recommends to use STARTTLS negotiation for secure connection between communicating entities. When I install ejabberd, by default it comes with a TLS certificate.

Then, why do I need to buy a certificate to install? what is the purpose of buying a new certificate from Certificate Authoririty since we have a default certificate?

When I deploy ejabberd on the machine, how the default certificate will be used for my domain? How the default certificate will be verified by client?

答:
The client will verify whether the certificate is issued for the domain name of the Jabber ID (JID), the part behind the '@'. (There are other options, but they are incompatible with the policies enforced by the browser vendors against CAs and therefore not practical.)

Unless you already have a business relationship to a certificate authority (CA), I would recommend anyone to use Let's Encrypt and stay away from self-signed certificates.

Some instructions to automate this and be nice to the Let's Encrypt servers can be found here and the linked wiki pages.

Summary (assuming you are running Ubuntu 16.04 LTS, want to run it on the domain example.org and only use the certificate for ejabberd):

Create /usr/local/sbin/auto-renew-letsencrypt with the following content:

```#!/bin/bash
# Renew all Let's Encrypt certificates which are due for renewal
t=`mktemp`
# Try to be quiet unless an error is returned
letsencrypt renew > $t || cat $t
# Hooks are not yet supported by `letsencrypt` shipping with Ubuntu 16.04 LTE
# Crudely emulate --renew-hook; breaks if diagnostic messages change
if grep -q "The following certs have been renewed" $t; then
  cat /etc/letsencrypt/live/<b>example.org</b>/{privkey,fullchain}.pem > /etc/ejabberd/ejabberd.pem
  service ejabberd reload
fi
rm $t
```

Run the following commands to create and activate the certificate and the automatic renewal

```apt install letsencrypt
letsencrypt certonly --standalone --domain <b>example.org</b>
cat /etc/letsencrypt/live/<b>example.org</b>/{privkey,fullchain}.pem > /etc/ejabberd/ejabberd.pem
chown ejabberd:ejabberd /etc/ejabberd/ejabberd.pem
chmod 640 /etc/ejabberd/ejabberd.pem
chmod 755 /usr/local/sbin/auto-renew-letsencrypt
echo $(($RANDOM % 60)) $((RANDOM % 6)) "* * * root /usr/local/sbin/auto-renew-letsencrypt" > /etc/cron.d/auto-renew-letsencrypt
```

Body:
The client will verify whether the certificate is issued for the domain name of the Jabber ID (JID), the part behind the '@'. (There are other options, but they are incompatible with the policies enforced by the browser vendors against CAs and therefore not practical.)

Unless you already have a business relationship to a certificate authority (CA), I would recommend anyone to use Let's Encrypt and stay away from self-signed certificates.

Some instructions to automate this and be nice to the Let's Encrypt servers can be found here and the linked wiki pages.

Summary (assuming you are running Ubuntu 16.04 LTS, want to run it on the domain example.org and only use the certificate for ejabberd):

Create /usr/local/sbin/auto-renew-letsencrypt with the following content:

#!/bin/bash
# Renew all Let's Encrypt certificates which are due for renewal
t=`mktemp`
# Try to be quiet unless an error is returned
letsencrypt renew > $t || cat $t
# Hooks are not yet supported by `letsencrypt` shipping with Ubuntu 16.04 LTE
# Crudely emulate --renew-hook; breaks if diagnostic messages change
if grep -q "The following certs have been renewed" $t; then
  cat /etc/letsencrypt/live/example.org/{privkey,fullchain}.pem > /etc/ejabberd/ejabberd.pem
  service ejabberd reload
fi
rm $t

Run the following commands to create and activate the certificate and the automatic renewal

apt install letsencrypt
letsencrypt certonly --standalone --domain example.org
cat /etc/letsencrypt/live/example.org/{privkey,fullchain}.pem > /etc/ejabberd/ejabberd.pem
chown ejabberd:ejabberd /etc/ejabberd/ejabberd.pem
chmod 640 /etc/ejabberd/ejabberd.pem
chmod 755 /usr/local/sbin/auto-renew-letsencrypt
echo $(($RANDOM % 60)) $((RANDOM % 6)) "* * * root /usr/local/sbin/auto-renew-letsencrypt" > /etc/cron.d/auto-renew-letsencrypt


问:
AWS auto scaling : could not create exact replica of instance
I created a t2.micro EC2 instance and configured node.js on it. That is running fine.

Next I tried to create an Auto Scaling group with this instance that creates a Launch Configuration then Auto Scaling group with Launch Configuaration also created successfully.

The problem is that when Auto Scaling works, the new instance created is not the exact replica (image) of the old instance. It does not copy my node.js configuaration and the data files.

Where I am going wrong and how achieve this requirement on AWS?

答:
When Auto Scaling launches a new Amazon EC2 instance, it uses the Amazon Machine Image (AMI) specified in the Launch Configuration. The new instance will have the exact same contents as the AMI.

It sounds like you are either using a standard Amazon-issued AMI, or you created your own AMI before you configured your instance. Any configurations done after the AMI creation will not carry across to new instances because it is not part of the AMI.

You should:

Launch an instance and configure it how you wish

Create an AMI (Actions / Image / Create Image)

Create a Launch Configuration that uses that AMI

Edit your Auto Scaling group to use that Launch Configuration

Any new instances launched by Auto Scaling will use the new AMI, which will have all your configurations.

An alternate to create a custom AMI is to use a User Data Script that will automatically run when a new instance starts. This script can download software, change settings and generally personalize the instance. This could be easier to update rather than having to create new AMIs when you want to change something. The User Data script can be entered into the Launch Configuration, which will be used by Auto Scaling when launching new instances.


问:
Confuse about activity launch
```<code>Notification.Builder builder = new Notification.Builder(getContext());
            builder.setAutoCancel(true);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher));
            builder.setContentTitle("abc");
            builder.setContentText("abc");
            builder.setContentIntent(PendingIntent.getActivity(getContext(), 0,
                    new Intent(getContext(), MainActivity.class).replaceExtras(bundle).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP),
                    PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setDefaults(Notification.DEFAULT_SOUND);
            NotificationManager manager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(0, builder.build());
</code>```

first way to set launch mode.

```<code><activity
        android:name=".activity.mainActivity.MainActivity"
        android:theme="@style/AppTheme.NoActionBar"
        android:launchMode="singleTask"/>
</code>```

second way to set launch mode.

Google offical document.

```<code>FLAG_ACTIVITY_NEW_TASK
</code>```

Start the Activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().
This produces the same behavior as the "singleTask" launchMode value, discussed in the previous section.

activity stack a,b,MainActivity

Why onNewIntent() not invoked in first way.
Why activity(a,b) not cleaned in first way.

答:
by using android:launchMode="singleTask"
"singleTask" and "singleInstance" activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task.

by using FLAG_ACTIVITY_NEW_TASK It set, this activity will become the start of a new task on this history stack.

Title: Confuse about activity launch

Body:
Notification.Builder builder = new Notification.Builder(getContext());
            builder.setAutoCancel(true);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher));
            builder.setContentTitle("abc");
            builder.setContentText("abc");
            builder.setContentIntent(PendingIntent.getActivity(getContext(), 0,
                    new Intent(getContext(), MainActivity.class).replaceExtras(bundle).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP),
                    PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setDefaults(Notification.DEFAULT_SOUND);
            NotificationManager manager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(0, builder.build());

first way to set launch mode.

<activity
        android:name=".activity.mainActivity.MainActivity"
        android:theme="@style/AppTheme.NoActionBar"
        android:launchMode="singleTask"/>

second way to set launch mode.

Google offical document.

FLAG_ACTIVITY_NEW_TASK

Start the Activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().
This produces the same behavior as the "singleTask" launchMode value, discussed in the previous section.

activity stack a,b,MainActivity

Why onNewIntent() not invoked in first way.
Why activity(a,b) not cleaned in first way.


问:
setting gradient in a UITabBar background
What is the easiest way that I can achieve something like this:

Is it through subclassing a UITabBarController? If yes what property needs to be changed?

答:
I had the same problem with my app and I came up with following:
in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

```<code>- (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
    CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

    //set up your gradient
    //......

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage;
}
</code>```

get the instance of UITabBarController

```<code>UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;
</code>```

set your gradient

```<code>[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];
</code>```

I'm not sure if that's a correct approach but it did work for me.

Body:
I had the same problem with my app and I came up with following:
in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

- (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
    CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

    //set up your gradient
    //......

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage;
}

get the instance of UITabBarController

UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;

set your gradient

[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];

I'm not sure if that's a correct approach but it did work for me.


问:
Kotlin - Is kotlin contain Object class like base class in java?
In my code i defined below variable,

```<code>var obj_str: Object = "NEW" as Object
</code>```

which gives warning This class shouldn't be used in Kotlin. Use kotlin.Any instead

So, i need to know Any is similar to Object in kotlin or any thing else?

Also need to know for wait method like wait(), notify() etc are available in Object class but not in Any, so perform that operation in kotlin?

答:
Your code could be written like this.

var obj_str: Any = "NEW" //You don't need to cast it
or

var obj_str: Any? = "NEW" //If obj_str could be null

Body:
In my code i defined below variable,

var obj_str: Object = "NEW" as Object

which gives warning This class shouldn't be used in Kotlin. Use kotlin.Any instead

So, i need to know Any is similar to Object in kotlin or any thing else?

Also need to know for wait method like wait(), notify() etc are available in Object class but not in Any, so perform that operation in kotlin?


问:
Apache Spark's performance tuning
I am working on a project where in I have to tune spark's performance. I have found four most important parameters that will help in tuning spark's performance. They are as follows:

spark.memory.fraction

spark.memory.offHeap.size

spark.storage.memoryFraction

spark.shuffle.memoryFraction

I wanted to know whether I am going in the right direction or not? Please let
me know if I missed out on some other parameters also.

Thanks in advance.

答:
This is is quite broad to answer honestly. The right path to optimize performance is mainly described in the official documentation in the section concerning Tuning Spark.

Generally speaking, there is lots of factors to optimize spark jobs :

Data Serialization

Memory Tuning

Level of Parallelism

Memory Usage of Reduce Tasks

Broadcasting Large Variables

Data Locality

It's mainly centralized around data serialization, memory tuning and a trade-off between precision/approximation techniques to get the job done fast.

EDIT:

Courtesy of @zero323 :

I'd point out, that all but one option mentioned in the question, are deprecated and used only in legacy mode.

Title: Apache Spark's performance tuning


问:
How to setup two route groups using middleware in Laravel 5.4
I'm setting up a web application in which I would like to distinguish two route groups. Both groups work as expected on their own, but when combined one of them fails. I've checked documentation on L5.4 website and followed instructions. After a whole day of digging decided to ask you.

Here is my routes/web.php file:

```<code>Route::group(['middleware' => ['auth']], function () {

    Route::group(['middleware' => ['medewerker']], function () {
        Route::get('/urencorrectie','UrenRegelsController@urencorrectie');
    });

    Route::group(['middleware' => ['officemanager']], function () {
        Route::get('/', 'DashboardController@index');
        Route::post('/', 'DashboardController@index');
        Route::get('/profile', function(){
        return view('profile');});
    });
});
Auth::routes();

Route::get('/home', 'HomeController@index');
</code>```

In order to enable roles I addes a column Rolid to the user model. Rol 1 is officemanager and role 3 is employee.

Then in the subsequent middleware we find employee.php:

```<code>namespace App\Http\Middleware;
use Closure;
use Auth;
class Employee
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->Rolid=='3')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}
</code>```

The Middleware officemanager.php file contains:

```<code>namespace App\Http\Middleware;
use Closure;
use Auth;

class Officemanager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user=Auth::user();
        if(Auth::user()->Rolid=='1')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}
</code>```

The code as is produces the following result:
- When an Officemanager logs in, he/she is redirected to the proper routes. Everything works fine.
- When an Employee logs in, he/she gets redirected to the /home redirect (bottom of routing/web.php file).

Any clues or help is very welcome. Kinda stuck on something probably basic.

[UPDATE]

In kernel.php both classes are mapped:

```<code>protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'officemanager' => \App\Http\Middleware\Officemanager::class,
    'employee' => \App\Http\Middleware\Employee::class,
];
</code>```

答:
The only thing that I can think of is that the Rolid of employee is not 3 - so try to debug it.

In general, it is not recommended to rely on DB ids in your code, because they can change between environments. I would add a relation for the user model and check the rol name:

User model:

```<code>public function role()
{
    return $this->belongsTo('App\Role', 'Rolid');
}
</code>```

Employee middlaware

```<code>class Employee
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role->name == 'employee')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}
</code>```

Office manger middleware:

```<code>class Officemanager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role->name == 'officemanager')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}
</code>```

Body:
I'm setting up a web application in which I would like to distinguish two route groups. Both groups work as expected on their own, but when combined one of them fails. I've checked documentation on L5.4 website and followed instructions. After a whole day of digging decided to ask you.

Here is my routes/web.php file:

Route::group(['middleware' => ['auth']], function () {

    Route::group(['middleware' => ['medewerker']], function () {
        Route::get('/urencorrectie','UrenRegelsController@urencorrectie');
    });

    Route::group(['middleware' => ['officemanager']], function () {
        Route::get('/', 'DashboardController@index');
        Route::post('/', 'DashboardController@index');
        Route::get('/profile', function(){
        return view('profile');});
    });
});
Auth::routes();

Route::get('/home', 'HomeController@index');

In order to enable roles I addes a column Rolid to the user model. Rol 1 is officemanager and role 3 is employee.

Then in the subsequent middleware we find employee.php:

namespace App\Http\Middleware;
use Closure;
use Auth;
class Employee
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->Rolid=='3')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}

The Middleware officemanager.php file contains:

namespace App\Http\Middleware;
use Closure;
use Auth;

class Officemanager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user=Auth::user();
        if(Auth::user()->Rolid=='1')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}

The code as is produces the following result:
- When an Officemanager logs in, he/she is redirected to the proper routes. Everything works fine.
- When an Employee logs in, he/she gets redirected to the /home redirect (bottom of routing/web.php file).

Any clues or help is very welcome. Kinda stuck on something probably basic.

[UPDATE]

In kernel.php both classes are mapped:

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'officemanager' => \App\Http\Middleware\Officemanager::class,
    'employee' => \App\Http\Middleware\Employee::class,
];

Body:
The only thing that I can think of is that the Rolid of employee is not 3 - so try to debug it.

In general, it is not recommended to rely on DB ids in your code, because they can change between environments. I would add a relation for the user model and check the rol name:

User model:

public function role()
{
    return $this->belongsTo('App\Role', 'Rolid');
}

Employee middlaware

class Employee
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role->name == 'employee')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}

Office manger middleware:

class Officemanager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role->name == 'officemanager')
        {
            return $next($request);
        }
        else
        {
            return redirect('/home');
        }
    }
}


问:
how i can make the drop down menu in jQuery
today on the forum i found somebody talking about http://educationtechnologysummit.com/sponsors-a-partners.html

i need a drop down list as same as in the page.

how i can make my own who have effect all like this.

答:
If you're referring to the nice animated drop down menu, this website will help you build something very similar: http://www.queness.com/post/1047/easy-to-style-jquery-drop-down-menu-tutorial

This techniques is the simplest you can use and doesn't require a plugin to do it. Adjust animation speeds and other things that you need.

Unfortunately, the site you're referring to uses Mootools... :) But if you're into jQuery plugins you should be looking for animated menu jquery plugin

OwnerDisplayName: Steven Spielberg


问:
How to create custom java library and call its function inside Android App
I am new to java and android development and I want to create my own java library (JAR files) and I want to call this jar lib function inside android app code base.

Although there are numerous online tutorials available which demonstrate how to do this I couldnt find one for a newbee person like me.

The resources available on the internet, assume that a person should be hands on java and android platform. This is not the case with me.

I have just started learning it and I want to create a java library and call its function into an Android App.

So to achieve this, below are the steps I have performed.

Step 1 : Created a sample program "Addition of 2 numbers" so this is what I have written.

```<code> package MyPackage;
 import java.io.*;
 import java.net.*;

 public class MyAddition {
    public static int addition(int a, int b){
       return (a+b);
    }
 }
</code>```

Saved it as MyAddition.java .Compiled and created its  class file MyAddition.class inside folder [folder_path]..../mylib/MyPackage/

Steps 2 : Created its JAR files using following command

```<code>   jar -cf mylib.jar [folder_path]../mylib
</code>```

Steps 3 :

Now I have installed Android Studio in order to create my android app code base where I want to call this JAR lib function.

In Android Studio, I have created a new project using its predefined "bottom Navigation activity"  as "My Application" so the whole project is set up by the Android Studio. Here is a screenshot for the whole setup.

Step 4 : : I have my complete application set up which looks like this.

Step 5 : : Now I want to integrate my JAR file which I've created earlier into this app. So to achieve this I've added the jar lib "mylib.jar" inside apps/libs folder like this.

Step 6 : : After doing all this, I am adding following line into the build.gradle file
     compile files 'libs/mylib.jar'

and then sync.

After Adding the Jar, I am calling its function inside Android App Function
but in this case its showing me error "can not resolve the MyPackage", where as it shows me this inside the application scope

Now I could not proceed further in order to include and call jar files function.

Any help is appreciated .

答:
in your app>build.gradle</p>

```<code>dependencies {
    ....
    compile files('libs/mylib.jar')   // add this
}
</code>```

Body:
I am new to java and android development and I want to create my own java library (JAR files) and I want to call this jar lib function inside android app code base.

Although there are numerous online tutorials available which demonstrate how to do this I couldnt find one for a newbee person like me.

The resources available on the internet, assume that a person should be hands on java and android platform. This is not the case with me.

I have just started learning it and I want to create a java library and call its function into an Android App.

So to achieve this, below are the steps I have performed.

Step 1 : Created a sample program "Addition of 2 numbers" so this is what I have written.

 package MyPackage;
 import java.io.*;
 import java.net.*;

 public class MyAddition {
    public static int addition(int a, int b){
       return (a+b);
    }
 }

Saved it as MyAddition.java .Compiled and created its  class file MyAddition.class inside folder [folder_path]..../mylib/MyPackage/

Steps 2 : Created its JAR files using following command

   jar -cf mylib.jar [folder_path]../mylib

Steps 3 :

Now I have installed Android Studio in order to create my android app code base where I want to call this JAR lib function.

In Android Studio, I have created a new project using its predefined "bottom Navigation activity"  as "My Application" so the whole project is set up by the Android Studio. Here is a screenshot for the whole setup.

Step 4 : : I have my complete application set up which looks like this.

Step 5 : : Now I want to integrate my JAR file which I've created earlier into this app. So to achieve this I've added the jar lib "mylib.jar" inside apps/libs folder like this.

Step 6 : : After doing all this, I am adding following line into the build.gradle file
     compile files 'libs/mylib.jar'

and then sync.

After Adding the Jar, I am calling its function inside Android App Function
but in this case its showing me error "can not resolve the MyPackage", where as it shows me this inside the application scope

Now I could not proceed further in order to include and call jar files function.

Any help is appreciated .

Body:
in your app>build.gradle

dependencies {
    ....
    compile files('libs/mylib.jar')   // add this
}


问:
Aurelia dash in component name not working
I have a basic Aurelia component and it looks like when I use dash in it's name, it doesn't work.

It works when I have it like this:

```<code>import {inject, customElement, bindable} from 'aurelia-framework';

@customElement('helloworld')
@inject(Element)
export class HelloWorldCustomElement {
    constructor(element) {
        console.log ('here')
    }
}
</code>```

```<code><helloworld></helloworld>
</code>```

But it doesn't when is like this:

```<code>import {inject, customElement, bindable} from 'aurelia-framework';

@customElement('hello-world')
@inject(Element)
export class HelloWorldCustomElement {
    constructor(element) {
        console.log ('here')
    }
}
</code>```

```<code><hello-world></hello-world>
</code>```

According to the Aurelia docs, it should work both ways: https://github.com/aurelia/templating/blob/master/doc/article/en-US/templating-custom-elements.md

答:
I managed to find the cause for this. In app.html I had the following line and it appears that there was a naming conflict. Removing it fixed the problem right away.

```<code><require from="hello-world/hello-world.html"></require>
</code>```

Body:
I have a basic Aurelia component and it looks like when I use dash in it's name, it doesn't work.

It works when I have it like this:

import {inject, customElement, bindable} from 'aurelia-framework';

@customElement('helloworld')
@inject(Element)
export class HelloWorldCustomElement {
    constructor(element) {
        console.log ('here')
    }
}

<helloworld></helloworld>

But it doesn't when is like this:

import {inject, customElement, bindable} from 'aurelia-framework';

@customElement('hello-world')
@inject(Element)
export class HelloWorldCustomElement {
    constructor(element) {
        console.log ('here')
    }
}

<hello-world></hello-world>

According to the Aurelia docs, it should work both ways: https://github.com/aurelia/templating/blob/master/doc/article/en-US/templating-custom-elements.md

Body:
I managed to find the cause for this. In app.html I had the following line and it appears that there was a naming conflict. Removing it fixed the problem right away.

<require from="hello-world/hello-world.html"></require>