问:
In Selenium, how to log in website on the popup window with python?
I would like to log in the website using selenium.
This site has link( members login ) and when I click this link, popup window appears.

The website URL is http://affiliates.888.com/

I wrote the code as follows.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

eight88 = webdriver.Chrome()
eight88.get("http://affiliates.888.com/")
assert "Earn Real Money" in eight88.title
loginForm = eight88.find_element_by_class_name("hide-under-480").click()
# so far popup appears.
eight88.switch_to_alert()
eight88.find_element_by_id("userName").send_keys("username")
eight88.find_element_by_id("password").send_keys("password")
</code>```

When I run this script, NoSuchElementException occurs.

```<code>raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"userName"}
  (Session info: chrome=59.0.3071.115)
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64)
</code>```

I don't know how to go to the popup and find element there.

How can I log in this website on popup.

答: The pop up is being generated by a JavaScript. So this is a dynamic page. When you use driver.get() you're reading the first static page source that is generated and obviously the username and password fields are not included. First figure out how the JavaScript is invoking the pop up and then use selenium's exec function to execute that JavaScript and another one to authenticate over the result of the first one.</p>

Body:
I would like to log in the website using selenium.
This site has link( members login ) and when I click this link, popup window appears.

The website URL is http://affiliates.888.com/

I wrote the code as follows.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

eight88 = webdriver.Chrome()
eight88.get("http://affiliates.888.com/")
assert "Earn Real Money" in eight88.title
loginForm = eight88.find_element_by_class_name("hide-under-480").click()
# so far popup appears.
eight88.switch_to_alert()
eight88.find_element_by_id("userName").send_keys("username")
eight88.find_element_by_id("password").send_keys("password")

When I run this script, NoSuchElementException occurs.

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"userName"}
  (Session info: chrome=59.0.3071.115)
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64)

I don't know how to go to the popup and find element there.

How can I log in this website on popup.


来源: stackexchange

问:
cakephp unable to register a user "You are not authorized to access that location"
in cakephp3 i ame unable to register a  user and "You are not authorized to access that location" message is displayed.

In my AppController.php :

```<code>public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login',
            'home'
        ],
    ]);
}

public function isAuthorized($user)
{
     return true;
}

public function beforFilter(Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow(['register', 'confirm', 'login']);
}
</code>```

and in my UsersController.php i have a function register() that i want to call to perform the registration of users.

答:
If you are using beforeFilter() in AppController,then try to use controller name a nd Method,

```<code>public function beforFilter(Event $event) {
    $this->Auth->allow(['Users.register', 'Users.confirm', 'Users.login']);
}
</code>```

Don't forget to use class "use Cake\Event\EventManager"

ContentLicense: CC BY-SA 3.0

Body:
in cakephp3 i ame unable to register a  user and "You are not authorized to access that location" message is displayed.

In my AppController.php :

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login',
            'home'
        ],
    ]);
}

public function isAuthorized($user)
{
     return true;
}

public function beforFilter(Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow(['register', 'confirm', 'login']);
}

and in my UsersController.php i have a function register() that i want to call to perform the registration of users.

Body:
If you are using beforeFilter() in AppController,then try to use controller name a nd Method,

public function beforFilter(Event $event) {
    $this->Auth->allow(['Users.register', 'Users.confirm', 'Users.login']);
}

Don't forget to use class "use Cake\Event\EventManager"


问:
making items blur in recylerview fitted in listview?

This is my app...in this i want that when i click on any of the cardview the background should blur and another should appear on selected one over the blur appearance and when the user clicks any one of buttons the user gets to new activity. i am using this library

Help me to get Started. Thank you

答:
You can use an AlertDailog with custom layout to achieve the same.

Usage and guidance can be found here


问:
Nth-of-type ignored classes
So I have this html

```<code><div>
    <div class="item"></div>
    <div class="item inactive"></div>
    <div class="item inactive"></div>
<div>
</code>```

And this css

```<code> .item.inactive:nth-of-type(1) {
     do stuff for 1st inactive
 }
 .item.inactive:nth-of-type(2) {
     do stuff for 2nd inactive
 }
</code>```

but it's not working as expected.

Instead I see this behavior

```<code> .item.inactive:nth-of-type(2) {
     stuff is happening for 1st inactive
 }
</code>```

so is it just ignoring when I specified .inactive? How would I get the effect I want?

.item {
  color: red;
}

.item.inactive:nth-of-type(2) {
  color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class='item-list'>
  <li class='item'>item 1</li>
  <li class='item inactive'>item 2</li>
  <li class='item inactive'>item 3</li>
<ul></code>```

答:
nth-of-type:-It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

nth-of-type reference

Try this CSS

```<code> .inactive:nth-of-type(2) {
    color:blue;
 }
 .inactive:nth-of-type(3){
    color:red;
 }
</code>```

hope this helps..

Title: Nth-of-type ignored classes

Body:
So I have this html

And this css

 .item.inactive:nth-of-type(1) {
     do stuff for 1st inactive
 }
 .item.inactive:nth-of-type(2) {
     do stuff for 2nd inactive
 }

but it's not working as expected.

Instead I see this behavior

 .item.inactive:nth-of-type(2) {
     stuff is happening for 1st inactive
 }

so is it just ignoring when I specified .inactive? How would I get the effect I want?

.item {
  color: red;
}

.item.inactive:nth-of-type(2) {
  color: green;
}

item 1

item 2

item 3

Body:
nth-of-type:-It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

nth-of-type reference

Try this CSS

 .inactive:nth-of-type(2) {
    color:blue;
 }
 .inactive:nth-of-type(3){
    color:red;
 }

hope this helps..


问:
"Suspected Fraud" status after compeleting the payment in magento?
I have made my custom module in magento, in which I have set discount in dynamically.
I am using following code for this.
But when I have completed the payment procedure, the order status should be 'processing' but instead of this order status become "Suspected Fraud".

Please let me know what I have done wrong. Although discount added successfully in order information.

```<code>$order->setData('base_discount_amount', $discountAmt);

$order->setData('base_discount_canceled', $discountAmt);

$order->setData('base_discount_invoiced', $discountAmt);

$order->setData('base_discount_refunded', $discountAmt);

$order->setData('discount_description', 'Affliate Discount');

$order->setData('discount_amount', $discountAmt);

$order->setData('discount_canceled', $discountAmt);

$order->setData('discount_invoiced', $discountAmt);

$order->setData('discount_refunded', $discountAmt);
</code>```

答:
It takes me a long time to solve this 0.10 error,

So I will share with you what was the problem in my case:

In:

/app/code/core/Mage/Paypal/Model/Cart.php

There is a _validate function in which PayPal checks the difference between $sum and $referenceAmount.

I replace it with:

```<code>if (sprintf('%.4F', $sum) == sprintf('%.4F', $referenceAmount)) {
    $this->_areItemsValid = true;
}
</code>```

I found it in a Magento backup before the upgrade.

Body:
I have made my custom module in magento, in which I have set discount in dynamically.
I am using following code for this.
But when I have completed the payment procedure, the order status should be 'processing' but instead of this order status become "Suspected Fraud".

Please let me know what I have done wrong. Although discount added successfully in order information.

$order->setData('base_discount_amount', $discountAmt);

$order->setData('base_discount_canceled', $discountAmt);

$order->setData('base_discount_invoiced', $discountAmt);

$order->setData('base_discount_refunded', $discountAmt);

$order->setData('discount_description', 'Affliate Discount');

$order->setData('discount_amount', $discountAmt);

$order->setData('discount_canceled', $discountAmt);

$order->setData('discount_invoiced', $discountAmt);

$order->setData('discount_refunded', $discountAmt);

Body:
It takes me a long time to solve this 0.10 error,

So I will share with you what was the problem in my case:

In:

/app/code/core/Mage/Paypal/Model/Cart.php

There is a _validate function in which PayPal checks the difference between $sum and $referenceAmount.

I replace it with:

if (sprintf('%.4F', $sum) == sprintf('%.4F', $referenceAmount)) {
    $this->_areItemsValid = true;
}

I found it in a Magento backup before the upgrade.


问:
java.lang.IllegalArgumentException: Invalid key code
Before installing windows 10 new update and jdk updates if I wanted to type (') with Robot class I just had to use this code:

```<code>public static void main(String[] args) throws IOException, AWTException {
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_QUOTE);
    r.keyRelease(KeyEvent.VK_QUOTE);
}
</code>```

And this had been working for me.
But now after installing windows 10 new update and jdk updates if I use it, I face with this error:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Invalid key
code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at Test.main(Test.java:9)
</code>```

All other keys are working except (VK_QUOTE);
What is wrong with my code?

答:
The keyboard input method(Control Panel\Clock, Language, and Region\Language\Language options) was on 'United States-International Touch keyboard layout'.
and I changed it to 'US' now it works properly.

Body:
Before installing windows 10 new update and jdk updates if I wanted to type (') with Robot class I just had to use this code:

public static void main(String[] args) throws IOException, AWTException {
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_QUOTE);
    r.keyRelease(KeyEvent.VK_QUOTE);
}

And this had been working for me.
But now after installing windows 10 new update and jdk updates if I use it, I face with this error:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid key
code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at Test.main(Test.java:9)

All other keys are working except (VK_QUOTE);
What is wrong with my code?


问:
How to play and pause video playing on Android WebView iframe?
the video which is playing on webview iframe and webview is set on recycler card view. Many videos are their on recyclerview.

I want to pause the playing video when user start scrolling recycler and pause the playing video when user play another video.

see the code

```<code>public void onBindViewHolder(final ViewHolder holder, final int position) {

holder.webView.getSettings().setUseWideViewPort(true);
        holder.webView.getSettings().setLoadWithOverviewMode(true);
        holder.webView.getSettings().setSupportZoom(true);
        holder.webView.getSettings().setBuiltInZoomControls(true);
        holder.webView.getSettings().setDisplayZoomControls(false);
        holder.webView.getSettings().setJavaScriptEnabled(true);
holder.webView.loadData("<iframe src=\"https://www.youtube.com/embed/" + video_id.get(position) + "?rel=0&showinfo=0\" width=\"1280\" height=\"720\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" allowFullScreen=\"true\"></iframe>", "text/html", "utf-8");
}
</code>```

I was trying to use this:

```<code>recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
                        @Override
                        public void onChildViewAttachedToWindow(View view) {
                            visibleWebView.add(webView);
                        }

                        @Override
                        public void onChildViewDetachedFromWindow(View view) {
                            webView.onPause();
                        }
                    });
</code>```

Please help me to solve this problem.
Any help will be appreciated.
Thanks!

答:
for pause video in android studio web view you can use webview.onPause first set onscroll change listener for recycler view and pause web view when recycler view scrolled. But their will be a problem if you place image view over webview for thumbnail then you won't get play event.
So it will be good and very useful if you will customize the webview events. that will be very helpful.
Thank You fr the help. :-)</p>

Body:
the video which is playing on webview iframe and webview is set on recycler card view. Many videos are their on recyclerview.

I want to pause the playing video when user start scrolling recycler and pause the playing video when user play another video.

see the code

public void onBindViewHolder(final ViewHolder holder, final int position) {

holder.webView.getSettings().setUseWideViewPort(true);
        holder.webView.getSettings().setLoadWithOverviewMode(true);
        holder.webView.getSettings().setSupportZoom(true);
        holder.webView.getSettings().setBuiltInZoomControls(true);
        holder.webView.getSettings().setDisplayZoomControls(false);
        holder.webView.getSettings().setJavaScriptEnabled(true);
holder.webView.loadData("", "text/html", "utf-8");
}

I was trying to use this:

recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
                        @Override
                        public void onChildViewAttachedToWindow(View view) {
                            visibleWebView.add(webView);
                        }

                        @Override
                        public void onChildViewDetachedFromWindow(View view) {
                            webView.onPause();
                        }
                    });

Please help me to solve this problem.
Any help will be appreciated.
Thanks!


问:
Maximum 20 cookie per domain - Why?
I've just come across an interesting fact, apparently a website can have up to 20 seperate cookies.

Ok - fair enough.

But why on earth would you store more than say "UserID", and why would you possibly need 20 cookies?

答: Agree with PiedPiper and thejh. If you are storing user info and customizing the behaviour of your site based on users actions, then very soon you will run out of storage limit of single cookie.</p>

ContentLicense: CC BY-SA 2.5

Title: Maximum 20 cookie per domain - Why?


问:
Why this while loop does not work?
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

`

答: CHange your second if to elif.

Title: Why this while loop does not work?

Body:
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

`

Body: CHange your second if to elif.


问:
How can i dynamically call my css file on index.html - angular2
My requirement is i need to call a css url from a variable. Actually i dont want to hard code it. As per the logged in user , the name of the css will be downloaded in local storage and from there i want to load it on index.html, how can i make this possible ?

My index.html

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Wbuilder</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="./assets/files/css/style.css">
  // instead of this i need to call this from a variable

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>
</code>```

答:
This may help someone. Instead adding a file, if there are minimal dynamic css you can include it. A dynamic generated CSS at the controller can be bind to the HTML View using ng-bind-html attribute with in the style tag.

Have a look at http://www.codeexpertz.com/blog/angularjs/adding-dynamic-generated-csscascading-style-sheet-angularjs-view-example for Demo and Sample Code

HTML

```<code>    <style ng-bind-html="myStyle"></style>
    <span>Enter the background colour value:</span>
    <span><input type = "text" ng-keyup="updateChanges()" ng-model = "bgcolour"></span>
    <br/>
    <div class="codeexpertz">
    </div>
</code>```

SCRIPT

```<code>    app.controller("myCtrl", function($scope) {
    $scope.bgcolour = '11acfd';
    $scope.updateChanges = function(){
        $scope.myStyle= '.codeexpertz { background-color: #' + $scope.bgcolour + '; height: 100px; width: 100px; border: 1px #000 solid}';
    }
    $scope.updateChanges();
</code>```

Body:
My requirement is i need to call a css url from a variable. Actually i dont want to hard code it. As per the logged in user , the name of the css will be downloaded in local storage and from there i want to load it on index.html, how can i make this possible ?

My index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Wbuilder</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="./assets/files/css/style.css">
  // instead of this i need to call this from a variable

  <app-root>Loading...</app-root>

Body:
This may help someone. Instead adding a file, if there are minimal dynamic css you can include it. A dynamic generated CSS at the controller can be bind to the HTML View using ng-bind-html attribute with in the style tag.

Have a look at http://www.codeexpertz.com/blog/angularjs/adding-dynamic-generated-csscascading-style-sheet-angularjs-view-example for Demo and Sample Code

HTML

    <style ng-bind-html="myStyle"></style>
    <span>Enter the background colour value:</span>
    <span><input type = "text" ng-keyup="updateChanges()" ng-model = "bgcolour"></span>
    <br/>
    <div class="codeexpertz">
    </div>

SCRIPT

    app.controller("myCtrl", function($scope) {
    $scope.bgcolour = '11acfd';
    $scope.updateChanges = function(){
        $scope.myStyle= '.codeexpertz { background-color: #' + $scope.bgcolour + '; height: 100px; width: 100px; border: 1px #000 solid}';
    }
    $scope.updateChanges();


问:
Grouping and summarizing by keeping other columns in R
I have a dataframe which I am grouping using the group_by function, and summarizing it with using the summarize function in R.

```<code>MM_group<-group_by(SYC,Method,Maturity)
</code>```

My dataset looks like this,

```<code> Year           Group  County Seed.Brand Seed.Variety Seed.Maturity
1 2014 Group 0 No-till Yankton     Asgrow       AG0832           0.8
2 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
3 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
4 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
5 2014 Group 0 No-till   Brown    Pioneer        90Y90           0.9
6 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9

Yield  Method Maturity digits
1 73.23 No-till        0      0
2 65.14 No-till        0      0
3 63.63 No-till        0      0
4 61.57 No-till        0      0
5 60.20 No-till        0      0
</code>```

I am grouping by Method & Maturity. I am trying to get County and Year for maximum yield for the Method & Maturity combination.

I have done the following:

```<code>summarize(MM_group,Max_Yield=max(Yield))

       Method Maturity Max_Yield
           <chr>    <chr>     <dbl>
1      Irrigated        0    69.600
2      Irrigated        1    86.013
3      Irrigated        2    88.750
4      Irrigated        3    79.650
5        No-till        0    79.470
6        No-till        1    79.856
7        No-till        2    85.860
8        No-till        3    68.530
9  Non-irrigated        0    83.210
10 Non-irrigated        1    81.916
11 Non-irrigated        2   103.740
12 Non-irrigated        3    94.410
</code>```

But, this doesn't give me the county name and year. I know I can use cbind or joins to get that data but wondering if there is another easier way of doing this.

Expected Output:

```<code>          Method Maturity Max_Yield  Year                  Group
           <chr>    <chr>     <dbl> <int>                 <fctr>
1      Irrigated        0    69.600  2012 Group 0 or 1 Irrigated
2      Irrigated        1    86.013  2012 Group 0 or 1 Irrigated
3      Irrigated        2    88.750  2013 Group 2 or 3 Irrigated
4      Irrigated        3    79.650  2013 Group 2 or 3 Irrigated
5        No-till        0    79.470  2013        Group 0 No-till
6        No-till        1    79.856  2012        Group 1 No-till
7        No-till        2    85.860  2013        Group 2 No-till
8        No-till        3    68.530  2014        Group 3 No-till
9  Non-irrigated        0    83.210  2013  Group 0 Non-irrigated
10 Non-irrigated        1    81.916  2012  Group 1 Non-irrigated
11 Non-irrigated        2   103.740  2014  Group 2 Non-irrigated
12 Non-irrigated        3    94.410  2014  Group 3 Non-irrigated
</code>```

答:
Try </p>

```<code>summarize(MM_group,
          rank = which.max(Yield),
          Year_rank = Year[rank],
          County_rank = County[rank])
</code>```

Body:
I have a dataframe which I am grouping using the group_by function, and summarizing it with using the summarize function in R.

MM_group<-group_by(SYC,Method,Maturity)

My dataset looks like this,

 Year           Group  County Seed.Brand Seed.Variety Seed.Maturity
1 2014 Group 0 No-till Yankton     Asgrow       AG0832           0.8
2 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
3 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
4 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
5 2014 Group 0 No-till   Brown    Pioneer        90Y90           0.9
6 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9

Yield  Method Maturity digits
1 73.23 No-till        0      0
2 65.14 No-till        0      0
3 63.63 No-till        0      0
4 61.57 No-till        0      0
5 60.20 No-till        0      0

I am grouping by Method & Maturity. I am trying to get County and Year for maximum yield for the Method & Maturity combination.

I have done the following:

summarize(MM_group,Max_Yield=max(Yield))

       Method Maturity Max_Yield
           <chr>    <chr>     <dbl>
1      Irrigated        0    69.600
2      Irrigated        1    86.013
3      Irrigated        2    88.750
4      Irrigated        3    79.650
5        No-till        0    79.470
6        No-till        1    79.856
7        No-till        2    85.860
8        No-till        3    68.530
9  Non-irrigated        0    83.210
10 Non-irrigated        1    81.916
11 Non-irrigated        2   103.740
12 Non-irrigated        3    94.410

But, this doesn't give me the county name and year. I know I can use cbind or joins to get that data but wondering if there is another easier way of doing this.

Expected Output:

          Method Maturity Max_Yield  Year                  Group
           <chr>    <chr>     <dbl> <int>                 <fctr>
1      Irrigated        0    69.600  2012 Group 0 or 1 Irrigated
2      Irrigated        1    86.013  2012 Group 0 or 1 Irrigated
3      Irrigated        2    88.750  2013 Group 2 or 3 Irrigated
4      Irrigated        3    79.650  2013 Group 2 or 3 Irrigated
5        No-till        0    79.470  2013        Group 0 No-till
6        No-till        1    79.856  2012        Group 1 No-till
7        No-till        2    85.860  2013        Group 2 No-till
8        No-till        3    68.530  2014        Group 3 No-till
9  Non-irrigated        0    83.210  2013  Group 0 Non-irrigated
10 Non-irrigated        1    81.916  2012  Group 1 Non-irrigated
11 Non-irrigated        2   103.740  2014  Group 2 Non-irrigated
12 Non-irrigated        3    94.410  2014  Group 3 Non-irrigated

Body:
Try

summarize(MM_group,
          rank = which.max(Yield),
          Year_rank = Year[rank],
          County_rank = County[rank])


问:
How do for statements work in jQuery?
I am currently using this code for my project but I can help but to feel a for statement could be used instead.

```<code>$("#login-1").text($("#" + iconId).data("login1"));
$("#login-1").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"</br>";
   send += $("#" + iconId).data("login1")+"</br>";
   send += $("#" + iconId).data("username1")+"</br>";
   send += $("#" + iconId).data("password1")+"</br>";
   $("#post").html(send);
   cancel();
});

$("#login-2").text($("#" + iconId).data("login2"));
$("#login-2").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"</br>";
   send += $("#" + iconId).data("login2")+"</br>";
   send += $("#" + iconId).data("username2")+"</br>";
   send += $("#" + iconId).data("password2")+"</br>";
   $("#post").html(send);
   cancel();
});

$("#login-3").text($("#" + iconId).data("login3"));
$("#login-3").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"</br>";
   send += $("#" + iconId).data("login3")+"</br>";
   send += $("#" + iconId).data("username3")+"</br>";
   send += $("#" + iconId).data("password3")+"</br>";
   $("#post").html(send);
   cancel();
});
</code>```

The only thing changing in between most of the lines of code are the number on login# username# password#

答:
Here is how you can optimize by creating a function and passing the necessary arguments:

```<code>function doChanges(number, iconId) {
  $("#login-" + number).text($("#" + iconId).data("login" + number));
  $("#login-" + number).click(function() {
    var send = '';
    send += $("#" + iconId).data("name") + "</br>";
    send += $("#" + iconId).data("login" + number) + "</br>";
    send += $("#" + iconId).data("username" + number) + "</br>";
    send += $("#" + iconId).data("password" + number) + "</br>";
    $("#post").html(send);
    cancel();
  });
}
</code>```

Example:

```<code>doChanges(1, iconId);
doChanges(2, iconId);
doChanges(3, iconId);
</code>```

I am not sure, if iconId is same or changes. If its same, you can remove that from function argument, it will get more simplified.

Title: How do for statements work in jQuery?

Body:
I am currently using this code for my project but I can help but to feel a for statement could be used instead.

$("#login-1").text($("#" + iconId).data("login1"));
$("#login-1").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"
";
   send += $("#" + iconId).data("login1")+"
";
   send += $("#" + iconId).data("username1")+"
";
   send += $("#" + iconId).data("password1")+"
";
   $("#post").html(send);
   cancel();
});

$("#login-2").text($("#" + iconId).data("login2"));
$("#login-2").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"
";
   send += $("#" + iconId).data("login2")+"
";
   send += $("#" + iconId).data("username2")+"
";
   send += $("#" + iconId).data("password2")+"
";
   $("#post").html(send);
   cancel();
});

$("#login-3").text($("#" + iconId).data("login3"));
$("#login-3").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"
";
   send += $("#" + iconId).data("login3")+"
";
   send += $("#" + iconId).data("username3")+"
";
   send += $("#" + iconId).data("password3")+"
";
   $("#post").html(send);
   cancel();
});

The only thing changing in between most of the lines of code are the number on login# username# password#

Body:
Here is how you can optimize by creating a function and passing the necessary arguments:

function doChanges(number, iconId) {
  $("#login-" + number).text($("#" + iconId).data("login" + number));
  $("#login-" + number).click(function() {
    var send = '';
    send += $("#" + iconId).data("name") + "</br>";
    send += $("#" + iconId).data("login" + number) + "</br>";
    send += $("#" + iconId).data("username" + number) + "</br>";
    send += $("#" + iconId).data("password" + number) + "</br>";
    $("#post").html(send);
    cancel();
  });
}

Example:

doChanges(1, iconId);
doChanges(2, iconId);
doChanges(3, iconId);

I am not sure, if iconId is same or changes. If its same, you can remove that from function argument, it will get more simplified.


问:
how to display images in tensorboard when data fomat is "NCHW"?
In tensorflow, using function tf.summary.image, we can display images in tensorboard.

```<code>image( name, tensor, max_outputs=3, collections=None )
</code>```

The data format of variable tensor is "NHWC", as [batch_size, height, width, channels].

but when I use "NCHW" ([batch_size, channels ,height, width]), how to display images in tensorboard ?

答:
The image summary does not handle multiple memory layout, as some other tensorflow functions do. So currently, your only option is to transpose your images.

As tf.transpose is a somewhat heavy operation, you can limit the transposition to the number of images that are summarized only, say summary_img_num:

```<code>summary_imgs = tf.transpose(imgs[:summary_img_num], perm=[0,3,1,2])
tf.summary.image('images', summary_imgs, max_outputs=summary_img_num)
</code>```

If you stick to tf.summary.image's default max_outputs=3,

```<code>summary_imgs = tf.transpose(imgs[:3], perm=[0,3,1,2])
tf.summary.image('images', summary_imgs)
</code>```

Body:
In tensorflow, using function tf.summary.image, we can display images in tensorboard.

image( name, tensor, max_outputs=3, collections=None )

The data format of variable tensor is "NHWC", as [batch_size, height, width, channels].

but when I use "NCHW" ([batch_size, channels ,height, width]), how to display images in tensorboard ?

Body:
The image summary does not handle multiple memory layout, as some other tensorflow functions do. So currently, your only option is to transpose your images.

As tf.transpose is a somewhat heavy operation, you can limit the transposition to the number of images that are summarized only, say summary_img_num:

summary_imgs = tf.transpose(imgs[:summary_img_num], perm=[0,3,1,2])
tf.summary.image('images', summary_imgs, max_outputs=summary_img_num)

If you stick to tf.summary.image's default max_outputs=3,

summary_imgs = tf.transpose(imgs[:3], perm=[0,3,1,2])
tf.summary.image('images', summary_imgs)

ContentLicense: CC BY-SA 4.0


问:
Writing a simple python scrapy crawler with mongodb
I have started writing a simple scrapy module for mongodb to use. I am new to python and I have been a problem with the code I wrote:

congress.py

```<code>import scrapy

from scrapy.selector import Selector
from scrapy.loader import ItemLoader
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.http import HtmlResponse
from congress.items import CongressItem

class CongressSpider(CrawlSpider):
    name = "congres"
    allowed_domains = ["www.congress.gov"]
    start_urls = [
            'https://www.congress.gov/members',
        ]
    #creating a rule for my crawler. I only want it to continue to the next page, don't follow any other links.
    rules = (Rule(LinkExtractor(allow=(),restrict_xpaths=("//a[@class='next']",)), callback="parse_page", follow=True),)

    def parse_page(self, response):
        for search in response.selector.xpath(".//li[@class='compact']"):
            yield {'member' : ' '.join(search.xpath("normalize-space(span/a/text())").extract()).strip(),
               'state' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item']/span/text())").extract()).strip(),
                'District' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item'][2]/span/text())").extract()).strip(),
                'party' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item'][3]/span/text())").extract()).strip(),
                'Served' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item'][4]/span//li/text())").extract()).strip(),
            }
</code>```

items.py

```<code>import scrapy
class CongressItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()

    member = scrapy.Field()
    state = scrapy.Field()
    District = scrapy.Field()
    party = scrapy.Field()
    served = scrapy.Field()
</code>```

pipelines.py

```<code>from pymongo import MongoClient
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log

class CongressPipeline(object):
    collection_name= 'members'
    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )
    def open_spider(self,spider):
            self.client = pymongo.MongoClient(self.mongo_uri)
            self.db = self.client[self.mongo_db]
    def close_spider(self, spider):
        self.client.close()
    def process_item(self, item, spider):
        self.db[self.collection_name].insert(dict(item))
        return item
</code>```

settings.py

```<code>BOT_NAME = 'congres'

SPIDER_MODULES = ['congres.spiders']
NEWSPIDER_MODULE = 'congres.spiders'

MONGO_URI = 'mongodb://localhost:27017'
MONGO_DATABASE = 'congres'
ROBOTSTXT_OBEY = True
DOWNLOAD_DELAY = 3
ITEM_PIPELINES = {
   'congress.pipelines.CongresPipeline': 300,
}
</code>```

The error it is showing is

```<code>Unhandled error in Deferred:
2017-07-09 11:15:33 [twisted] CRITICAL: Unhandled error in Deferred:

2017-07-09 11:15:34 [twisted] CRITICAL:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\twisted\internet\defer.py", line 1386,
in _inlineCallbacks
result = g.send(result)
File "c:\python27\lib\site-packages\scrapy\crawler.py", line 95, in crawl
six.reraise(*exc_info)
File "c:\python27\lib\site-packages\scrapy\crawler.py", line 79, in crawl
yield self.engine.open_spider(self.spider, start_requests)
NameError: global name 'pymongo' is not defined
</code>```

答:
You are importing just MongoClient in pipelines.py

```<code>from pymongo import MongoClient
</code>```

while in open_spider method, you are using it this way

```<code>self.client = pymongo.MongoClient(self.mongo_uri)
</code>```

You are getting the error because pymongo is not imported. Change the last line to

```<code>self.client = MongoClient(self.mongo_uri)
</code>```

Body:
I have started writing a simple scrapy module for mongodb to use. I am new to python and I have been a problem with the code I wrote:

congress.py

import scrapy

from scrapy.selector import Selector
from scrapy.loader import ItemLoader
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.http import HtmlResponse
from congress.items import CongressItem

class CongressSpider(CrawlSpider):
    name = "congres"
    allowed_domains = ["www.congress.gov"]
    start_urls = [
            'https://www.congress.gov/members',
        ]
    #creating a rule for my crawler. I only want it to continue to the next page, don't follow any other links.
    rules = (Rule(LinkExtractor(allow=(),restrict_xpaths=("//a[@class='next']",)), callback="parse_page", follow=True),)

    def parse_page(self, response):
        for search in response.selector.xpath(".//li[@class='compact']"):
            yield {'member' : ' '.join(search.xpath("normalize-space(span/a/text())").extract()).strip(),
               'state' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item']/span/text())").extract()).strip(),
                'District' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item'][2]/span/text())").extract()).strip(),
                'party' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item'][3]/span/text())").extract()).strip(),
                'Served' : ' '.join(search.xpath("normalize-space(div[@class='quick-search-member']//span[@class='result-item'][4]/span//li/text())").extract()).strip(),
            }

items.py

import scrapy
class CongressItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()

    member = scrapy.Field()
    state = scrapy.Field()
    District = scrapy.Field()
    party = scrapy.Field()
    served = scrapy.Field()

pipelines.py

from pymongo import MongoClient
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log

class CongressPipeline(object):
    collection_name= 'members'
    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )
    def open_spider(self,spider):
            self.client = pymongo.MongoClient(self.mongo_uri)
            self.db = self.client[self.mongo_db]
    def close_spider(self, spider):
        self.client.close()
    def process_item(self, item, spider):
        self.db[self.collection_name].insert(dict(item))
        return item

settings.py

BOT_NAME = 'congres'

SPIDER_MODULES = ['congres.spiders']
NEWSPIDER_MODULE = 'congres.spiders'

MONGO_URI = 'mongodb://localhost:27017'
MONGO_DATABASE = 'congres'
ROBOTSTXT_OBEY = True
DOWNLOAD_DELAY = 3
ITEM_PIPELINES = {
   'congress.pipelines.CongresPipeline': 300,
}

The error it is showing is

Unhandled error in Deferred:
2017-07-09 11:15:33 [twisted] CRITICAL: Unhandled error in Deferred:

2017-07-09 11:15:34 [twisted] CRITICAL:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\twisted\internet\defer.py", line 1386,
in _inlineCallbacks
result = g.send(result)
File "c:\python27\lib\site-packages\scrapy\crawler.py", line 95, in crawl
six.reraise(*exc_info)
File "c:\python27\lib\site-packages\scrapy\crawler.py", line 79, in crawl
yield self.engine.open_spider(self.spider, start_requests)
NameError: global name 'pymongo' is not defined

Body:
You are importing just MongoClient in pipelines.py

from pymongo import MongoClient

while in open_spider method, you are using it this way

self.client = pymongo.MongoClient(self.mongo_uri)

You are getting the error because pymongo is not imported. Change the last line to

self.client = MongoClient(self.mongo_uri)


问:
Designing a generic unstructured data store
The project I have been given is to store and retrieve unstructured data from a third-party. This could be HR information – User, Pictures, CV, Voice mail etc or factory related stuff – Work items, parts lists, time sheets etc. Basically almost any type of data.

Some of these items may be linked so a User many have a picture for example. I don’t need to examine the content of the data as my storage solution will receive the data as XML and send it out as XML. It’s down to the recipient to convert the XML back into a picture or sound file etc. The recipient may request all Users so I need to be able to find User records and their related “child” items such as pictures etc, or the recipient may just want pictures etc.

My database is MS SQL and I have to stick with that. My question is, are there any patterns or existing solutions for handling unstructured data in this way.

I’ve done a bit of Googling and have found some sites that talk about this kind of problem but they are more interested in drilling into the data to allow searches on their content. I don’t need to know the content just what type it is (picture, User, Job Sheet etc).

To those who have given their comments:

The problem I face is the linking of objects together. A User object may be added to the data store then at a later date the users picture may be added. When the User is requested I will need to return the both the User object and it associated Picture. The user may update their picture so you can see I need to keep relationships between objects. That is what I was trying to get across in the second paragraph. The problem I have is that my solution must be very generic as I should be able to store anything and link these objects by the end users requirements. EG: User, Pictures and emails or Work items, Parts list etc. I see that Microsoft has developed ZEntity which looks like it may be useful but  I don’t need to drill into the data contents so it’s probably over kill for what I need.

答: So am I right if I say that all you need to store is a blob of xml with whatever binary information contained within? Why can't you have a users table and then a linked(foreign key) table with userobjects in, linked by userId?</p>


问:
Spring 4 with 2 jdbc connections
How do I configure 2 jdbc connections using Spring4 java config classes ?

Should 2 transaction managers be configure for those two connections ?

Thx

Edit:

I'm want to use just JdbcTemplate no JPA, Spring Data.

答:
Example configuration might looks something like the following. I also pushed a full sample to GitHub which can be found here</p>

```<code>@Configuration
public class DataSourceConfiguration {

    @Bean
    public PlatformTransactionManager firstDataSourceTransactionManager() {
        return new DataSourceTransactionManager(firstDataSource());
    }

    @Bean(destroyMethod = "shutdown")
    @Primary
    public DataSource firstDataSource() {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .generateUniqueName(true)
                .build();
    }

    @Bean
    public JdbcTemplate firstJdbcTemplate() {
        return new JdbcTemplate(firstDataSource());
    }

    @Bean
    public PlatformTransactionManager secondDataSourceTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource());
    }

    @Bean(destroyMethod = "shutdown")
    public DataSource secondDataSource() {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .generateUniqueName(true)
                .build();
    }

    @Bean
    public JdbcTemplate secondJdbcTemplate() {
        return new JdbcTemplate(secondDataSource());
    }

}
</code>```

Title: Spring 4 with 2 jdbc connections

Body:
Example configuration might looks something like the following. I also pushed a full sample to GitHub which can be found here

@Configuration
public class DataSourceConfiguration {

    @Bean
    public PlatformTransactionManager firstDataSourceTransactionManager() {
        return new DataSourceTransactionManager(firstDataSource());
    }

    @Bean(destroyMethod = "shutdown")
    @Primary
    public DataSource firstDataSource() {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .generateUniqueName(true)
                .build();
    }

    @Bean
    public JdbcTemplate firstJdbcTemplate() {
        return new JdbcTemplate(firstDataSource());
    }

    @Bean
    public PlatformTransactionManager secondDataSourceTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource());
    }

    @Bean(destroyMethod = "shutdown")
    public DataSource secondDataSource() {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .generateUniqueName(true)
                .build();
    }

    @Bean
    public JdbcTemplate secondJdbcTemplate() {
        return new JdbcTemplate(secondDataSource());
    }

}


问:
Spring boot, The file can not be read, Use jar package when starting
Spring boot, The file can not be read, Use jar package when starting.
When I use the .war start the way everything is normal

This is war maven pom.xml

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>xls</nonFilteredFileExtension>
            <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
            <nonFilteredFileExtension>p12</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>
</code>```

But use java -jar

I want to start with java -jar, Now what do I need to do?
spring boot version 1.4.4

```<code>public void generater(HttpServletResponse response, boolean testMode) {
        ExcelTemplateEnum excelTemplate = this.exportTemplate();
        FileInputStream is = null;
        Workbook workbook = null;
        try {
            String templateFilePath = this.getTemplateFilePath(excelTemplate);
            URL url = ExeclExportHandler.class.getClassLoader().getResource(templateFilePath);
            is = new FileInputStream(url.getFile());
            ExcelTransformer transformer = this.getExcelTransformer();
            // 渲染导出数据
            if (isMultipleBeans()) {
                List<Map<String, Object>> data = this.renderDataList();
                this.checkExportParam(data);
                workbook = transformer.transform(is, getTemplateSheetNamesList(), getSheetNamesList(), data);
            } else {
                Map<String, Object> data = this.renderData();
                this.checkExportParam(data);
                workbook = transformer.transform(is, data);
            }
            if (testMode) {
                ...
            } else {
                ExcelHelper.setExcelHeader(response, excelTemplate.outname());
                workbook.write(response.getOutputStream());
                response.flushBuffer();
            }
        } catch (Exception e) {
            ...
        } finally {
            IOUtils.closeQuietly(is, workbook);
        }
    }
</code>```

error line 75

```<code>    is = new FileInputStream(url.getFile());
</code>```

答:
You have to access the resource by Class.getResourceAsStream(), since you can't access files packed in a jar:

```<code>is = this.getClass().getResourceAsStream(templateFilePath)
</code>```

If it works with a war it is just luck, since your servlet/J2EE-container seems to unpack your war... which is not the case with all containers (due to the spec it is up to the container whether it will unpack the the war or not). Means with a different container you will get also get this Exception with the war.

Body:
Spring boot, The file can not be read, Use jar package when starting.
When I use the .war start the way everything is normal

This is war maven pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>xls</nonFilteredFileExtension>
            <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
            <nonFilteredFileExtension>p12</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>

But use java -jar

I want to start with java -jar, Now what do I need to do?
spring boot version 1.4.4

public void generater(HttpServletResponse response, boolean testMode) {
        ExcelTemplateEnum excelTemplate = this.exportTemplate();
        FileInputStream is = null;
        Workbook workbook = null;
        try {
            String templateFilePath = this.getTemplateFilePath(excelTemplate);
            URL url = ExeclExportHandler.class.getClassLoader().getResource(templateFilePath);
            is = new FileInputStream(url.getFile());
            ExcelTransformer transformer = this.getExcelTransformer();
            // 渲染导出数据
            if (isMultipleBeans()) {
                List<Map<String, Object>> data = this.renderDataList();
                this.checkExportParam(data);
                workbook = transformer.transform(is, getTemplateSheetNamesList(), getSheetNamesList(), data);
            } else {
                Map<String, Object> data = this.renderData();
                this.checkExportParam(data);
                workbook = transformer.transform(is, data);
            }
            if (testMode) {
                ...
            } else {
                ExcelHelper.setExcelHeader(response, excelTemplate.outname());
                workbook.write(response.getOutputStream());
                response.flushBuffer();
            }
        } catch (Exception e) {
            ...
        } finally {
            IOUtils.closeQuietly(is, workbook);
        }
    }

error line 75

    is = new FileInputStream(url.getFile());

Body:
You have to access the resource by Class.getResourceAsStream(), since you can't access files packed in a jar:

is = this.getClass().getResourceAsStream(templateFilePath)

If it works with a war it is just luck, since your servlet/J2EE-container seems to unpack your war... which is not the case with all containers (due to the spec it is up to the container whether it will unpack the the war or not). Means with a different container you will get also get this Exception with the war.


问:
Powershell Invoke-WebRequest prepare XML for POST
Apologies in advance for the lack of understanding here and the possibility this question has been asked before. Having thought I got it sorted by moving to Powershell v5.1 it turns out to be more complicated than I thought so I'll update the question.

We have been developing scripts on PS version 4.0 for the explicit reason that our customers have Windows 2012 R2 servers on which PS v4.0 is standard. However, this script doesn't run properly on v4.x as shown below

Here is my code with a correctly formed xml snippet

```<code>$NETXNUA = "https://gate.sonile.com/ModSoap";
$ContentType = "text/xml";

# tried this and it this doesn't do anything
# [System.Net.ServicePointManager]::Expect100Continue = $false

$RequestBody = @"
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">
    <SOAP-ENV:Body>
        <sendMessage
        xmlns="http://gate.sonile.com/ModSoap" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <application xsi:type="xsd:string">RuFus</application>
        <password xsi:type="xsd:string">PingPong</password>
        <content xsi:type="xsd:string">Tiddles</content>
        <class xsi:type="xsd:string">mt_bubbles</class>
        </sendMessage>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"@

try {
    $what = Invoke-WebRequest -Uri $NETXNUA -Method Post -Body $RequestBody -ContentType $ContentType -UseBasicParsing;
    }
catch {
    If ($_.Exception.Response.StatusCode.value__) {
    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output "crap $crap";
    }

    If  ($_.Exception.Response.StatusDescription) {
    $crapdescription = ($_.Exception.Response.StatusDescription).ToString().Trim();
    Write-Output "crapdesc $crapdescription";
    }

    If  ($_.Exception.Message) {
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output "crapmsg $crapMessage";
    }

    If  ($_.ErrorDetails.Message) {
    $ResponseBody = ($_.ErrorDetails.Message).ToString().Trim();
    $ResponseBody = $ResponseBody -replace "\s+", " ";
    }

    Write-Output "default $ResponseBody";
}
</code>```

This is what happens when I run this script on Windows 8.1 Pro and standard Powershell

```<code>Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2
</code>```

Below is the result, note that "$_.Exception.Message" is the only item with any value in it

```<code>crapmsg '"utf-8"' is not a supported encoding name. For information on
defining a custom encoding, see the documentation for the Encoding.Regi
sterProvider method.
Parameter name: name
</code>```

In other words, a miserable failure, except believe it or not, the Host processed the post data

Now run this exact same script on a Windows Server 2008 R2 with updated v5.1 Powershell

```<code>Name                           Value
----                           -----
PSVersion                      5.1.14409.1005
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1005
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

and here is the result below from "$_.Exception.Message"

```<code>crapmsg Value cannot be null.
Parameter name: name
</code>```

Woah, that's different, what's going on here..?

Right then, let's try this exact same script again on a Windows Server 2012 R2 Azure VM with a Powershell v5.1 update

```<code>Name                           Value
----                           -----
PSVersion                      5.1.14409.1005
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1005
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

Well now, same result as on the 2008 R2 server with only "$_.Exception.Message" returning anything. At least that's consistent, which figures because the PS versions are the same.

```<code>crapmsg Value cannot be null.
Parameter name: name
</code>```

What about I try this script on the ragamuffin of the Windows collection  Windows 10 Home edition with standard installed Powershell v5.1

```<code>Name                           Value
----                           -----
PSVersion                      5.1.14393.1358
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.1358
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

OMG, I don't believe it... a miracle! It works perfectly with a 200 response returned in $what plus the Host response in xml that I can process.

```<code>StatusCode        : 200
StatusDescription : OK
Content           : <?xml version="1.0" encoding="UTF-8"?>
                    <tns1:Envelope
xmlns:tns1="http://schemas.xmlsoap.org/soap/envelope/">...etc
RawContent        : HTTP/1.1 200 OK
                    Keep-Alive: timeout=15, max=100
                    Connection: Keep-Alive
                    Content-Length: 411
                    Content-Type: text/xml; charset="utf-8"
                    Date: Thu, 06 Jul 2017 04:02:15 GMT
                    Server: Apache
                    Via: 1.1 ga...
Forms             :
Headers           : {[Keep-Alive, timeout=15, max=100], [Connection, Keep-
Alive], [Content...etc
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        :
RawContentLength  : 411
</code>```

Everything would be totally sorted, if only my customers would throw out those pesky Windows Servers they favour and use Windows 10 instead..!

Breaking News! Just tried Windows Server 2016 Azure VM and that works fine too.

```<code>Name                           Value
----                           -----
PSVersion                      5.1.14393.479
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.479
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

Is there some secret parameter that would enable this script to work properly on various platforms and versions of Powershell...?

Every other script I've created using Invoke-WebRequest has worked just fine on PS v4 & v5 it's just this one that is causing problems.

Any tips at all gratefully accepted

Previously I tried using a file input for the xml and reading with -InFile like this...

```<code>Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2
</code>```0

That worked fine, but it isn't suitable for my application

答:
Having toiled on this script all week for countless hours... bizarrely, it only ever bombed out on a successful 200 status return, errors were returned just fine!

Turns out that Invoke-WebRequest has an insurmountable problem acknowledged as posted by @vane in April 2016 Why is Invoke-WebRequest and Invoke-RestMethod failing and succeeding at the same time?

Therefore, please correct me if I'm wrong, the only known solution is to revert to a standard http WebRequest call something like this (wrap it with your own error handling);

```<code>    $encodedContent = [System.Text.Encoding]::UTF8.GetBytes($RequestBody)

    $webRequest = [System.Net.WebRequest]::Create($NETXNUA)

    $webRequest.Method = "Post"
    $webRequest.ContentType = $ContentType
    $webRequest.ContentLength = $encodedContent.length

    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($encodedContent, 0, $encodedContent.length)
    $requestStream.Close()

    [System.Net.WebResponse] $response = $webRequest.GetResponse();
</code>```

I have verified this older style mechanism works perfectly on the following platforms;

```<code>Win 8.1 Pro with PS v4.0
Server 2008 R2 with PS 5.1
Server 2012 R2 with PS 5.1 (Azure VM)
Server 2012 R2 with PS v4.0 (Azure VM)
Win 10 Home with PS 5.1
Server 2016 with PS v5.1 (Azure VM)
</code>```

I acknowledge that Invoke-WebRequest script worked flawlessly on Win 10 and Server 2016, so eventually the problem will just go away!

TWO YEARS LATER, NOVEMBER 2019: BIZARRE DISCOVERY..!

Updated a device to Windows 10 version 1903 and set about getting scripts going.

Immediately discovered any script using Invoke-WebRequest didn't work.

Error was caused by install of Internet Explorer not being completed.

Installed IE, Invoke-WebRequest runs fine.

MORAL: You can never quite escape IE completely

Body:
Apologies in advance for the lack of understanding here and the possibility this question has been asked before. Having thought I got it sorted by moving to Powershell v5.1 it turns out to be more complicated than I thought so I'll update the question.

We have been developing scripts on PS version 4.0 for the explicit reason that our customers have Windows 2012 R2 servers on which PS v4.0 is standard. However, this script doesn't run properly on v4.x as shown below

Here is my code with a correctly formed xml snippet

$NETXNUA = "https://gate.sonile.com/ModSoap";
$ContentType = "text/xml";

# tried this and it this doesn't do anything
# [System.Net.ServicePointManager]::Expect100Continue = $false

$RequestBody = @"
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">
    <SOAP-ENV:Body>
        <sendMessage
        xmlns="http://gate.sonile.com/ModSoap" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <application xsi:type="xsd:string">RuFus</application>
        <password xsi:type="xsd:string">PingPong</password>
        <content xsi:type="xsd:string">Tiddles</content>
        <class xsi:type="xsd:string">mt_bubbles</class>
        </sendMessage>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"@

try {
    $what = Invoke-WebRequest -Uri $NETXNUA -Method Post -Body $RequestBody -ContentType $ContentType -UseBasicParsing;
    }
catch {
    If ($_.Exception.Response.StatusCode.value__) {
    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output "crap $crap";
    }

    If  ($_.Exception.Response.StatusDescription) {
    $crapdescription = ($_.Exception.Response.StatusDescription).ToString().Trim();
    Write-Output "crapdesc $crapdescription";
    }

    If  ($_.Exception.Message) {
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output "crapmsg $crapMessage";
    }

    If  ($_.ErrorDetails.Message) {
    $ResponseBody = ($_.ErrorDetails.Message).ToString().Trim();
    $ResponseBody = $ResponseBody -replace "\s+", " ";
    }

    Write-Output "default $ResponseBody";
}

This is what happens when I run this script on Windows 8.1 Pro and standard Powershell

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.42000
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Below is the result, note that "$_.Exception.Message" is the only item with any value in it

crapmsg '"utf-8"' is not a supported encoding name. For information on
defining a custom encoding, see the documentation for the Encoding.Regi
sterProvider method.
Parameter name: name

In other words, a miserable failure, except believe it or not, the Host processed the post data

Now run this exact same script on a Windows Server 2008 R2 with updated v5.1 Powershell

Name                           Value
----                           -----
PSVersion                      5.1.14409.1005
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1005
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

and here is the result below from "$_.Exception.Message"

crapmsg Value cannot be null.
Parameter name: name

Woah, that's different, what's going on here..?

Right then, let's try this exact same script again on a Windows Server 2012 R2 Azure VM with a Powershell v5.1 update

Name                           Value
----                           -----
PSVersion                      5.1.14409.1005
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1005
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Well now, same result as on the 2008 R2 server with only "$_.Exception.Message" returning anything. At least that's consistent, which figures because the PS versions are the same.

crapmsg Value cannot be null.
Parameter name: name

What about I try this script on the ragamuffin of the Windows collection  Windows 10 Home edition with standard installed Powershell v5.1

Name                           Value
----                           -----
PSVersion                      5.1.14393.1358
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.1358
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

OMG, I don't believe it... a miracle! It works perfectly with a 200 response returned in $what plus the Host response in xml that I can process.

StatusCode        : 200
StatusDescription : OK
Content           : <?xml version="1.0" encoding="UTF-8"?>
                    <tns1:Envelope
xmlns:tns1="http://schemas.xmlsoap.org/soap/envelope/">...etc
RawContent        : HTTP/1.1 200 OK
                    Keep-Alive: timeout=15, max=100
                    Connection: Keep-Alive
                    Content-Length: 411
                    Content-Type: text/xml; charset="utf-8"
                    Date: Thu, 06 Jul 2017 04:02:15 GMT
                    Server: Apache
                    Via: 1.1 ga...
Forms             :
Headers           : {[Keep-Alive, timeout=15, max=100], [Connection, Keep-
Alive], [Content...etc
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        :
RawContentLength  : 411

Everything would be totally sorted, if only my customers would throw out those pesky Windows Servers they favour and use Windows 10 instead..!

Breaking News! Just tried Windows Server 2016 Azure VM and that works fine too.

Name                           Value
----                           -----
PSVersion                      5.1.14393.479
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.479
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Is there some secret parameter that would enable this script to work properly on various platforms and versions of Powershell...?

Every other script I've created using Invoke-WebRequest has worked just fine on PS v4 & v5 it's just this one that is causing problems.

Any tips at all gratefully accepted

Previously I tried using a file input for the xml and reading with -InFile like this...

Invoke-WebRequest "https://gateway.mobil.com/MSoap" -Method Post -ContentType "text/xml" -InFile "C:\Scripts\mobil.xml" -OutFile "C:\PWScripts\mobil_out.xml"

That worked fine, but it isn't suitable for my application

Body:
Having toiled on this script all week for countless hours... bizarrely, it only ever bombed out on a successful 200 status return, errors were returned just fine!

Turns out that Invoke-WebRequest has an insurmountable problem acknowledged as posted by @vane in April 2016 Why is Invoke-WebRequest and Invoke-RestMethod failing and succeeding at the same time?

Therefore, please correct me if I'm wrong, the only known solution is to revert to a standard http WebRequest call something like this (wrap it with your own error handling);

    $encodedContent = [System.Text.Encoding]::UTF8.GetBytes($RequestBody)

    $webRequest = [System.Net.WebRequest]::Create($NETXNUA)

    $webRequest.Method = "Post"
    $webRequest.ContentType = $ContentType
    $webRequest.ContentLength = $encodedContent.length

    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($encodedContent, 0, $encodedContent.length)
    $requestStream.Close()

    [System.Net.WebResponse] $response = $webRequest.GetResponse();

I have verified this older style mechanism works perfectly on the following platforms;

Win 8.1 Pro with PS v4.0
Server 2008 R2 with PS 5.1
Server 2012 R2 with PS 5.1 (Azure VM)
Server 2012 R2 with PS v4.0 (Azure VM)
Win 10 Home with PS 5.1
Server 2016 with PS v5.1 (Azure VM)

I acknowledge that Invoke-WebRequest script worked flawlessly on Win 10 and Server 2016, so eventually the problem will just go away!

TWO YEARS LATER, NOVEMBER 2019: BIZARRE DISCOVERY..!

Updated a device to Windows 10 version 1903 and set about getting scripts going.

Immediately discovered any script using Invoke-WebRequest didn't work.

Error was caused by install of Internet Explorer not being completed.

Installed IE, Invoke-WebRequest runs fine.

MORAL: You can never quite escape IE completely


问:
composer create-project not installing Laravel 5.3
I have been trying to no avail to install Laravel 5.3 but keep getting 5.2 installed. Here's what i have done.

```<code>composer create-project laravel/laravel laravel53
</code>```

This should pull in the latest version of laravel which is 5.3 right? Well, i thought so but i keep getting 5.2 installed

Then i felt it may be a problem with composer so i ran composer self-update

```<code>composer self-update
</code>```

And still get 5.2 installed when i run create-project

I'm pretty sure i am getting something wrong because i ran this same command on a friend's laptop and 5.3 got installed

I am using a mac book pro BTW

Any ideas why this is so and how it can be solved?

Much thanks

答: I already had PHP 5.6 but it was not able to write .env file so I was required to run the command using sudo.</p>

Body:
I have been trying to no avail to install Laravel 5.3 but keep getting 5.2 installed. Here's what i have done.

composer create-project laravel/laravel laravel53

This should pull in the latest version of laravel which is 5.3 right? Well, i thought so but i keep getting 5.2 installed

Then i felt it may be a problem with composer so i ran composer self-update

composer self-update

And still get 5.2 installed when i run create-project

I'm pretty sure i am getting something wrong because i ran this same command on a friend's laptop and 5.3 got installed

I am using a mac book pro BTW

Any ideas why this is so and how it can be solved?

Much thanks


问:
Move bonobo git server repositories to another drive
I use Bonobo Git Server, I want to move my repositories to another drive.

currently the repositories are in C:\inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories. How can I move them to D:\ drive?

答:
If you have administrative privileges on that machine, you can see if making a directory symlink.

Move your C:\inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories folder first (so App_Data\ has no longer the Repositories folder).

Then:

```<code># In an Administrtor CMD shell:
mklink /D D:\path\top\Repositories C:\inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories
</code>```

That way, all the current Bonobo/IIS settings remain the same.

Body:
If you have administrative privileges on that machine, you can see if making a directory symlink.

Move your C:\inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories folder first (so App_Data\ has no longer the Repositories folder).

Then:

# In an Administrtor CMD shell:
mklink /D D:\path\top\Repositories C:\inetpub\wwwroot\Bonobo.Git.Server\App_Data\Repositories

That way, all the current Bonobo/IIS settings remain the same.


问:
FFMEPG permission problem, is there any alternative solution instead of FFMPEG?
We have some kind of permenant permission problem on FFMPEG.exe to write JPEG file on to HDD.
We are using IIS and try all permission methods to ffmepg.exe, its including folder,folders, cmd.exe and any executable file, related folder, file. Also we tried many many command examples. But never went beyond the "permission denied" error messages.
We give up.
Do you know another alternative solution to pick images from flv, f4v movie files? Or %100 quaranteed method to achive this permission control on IIS?
Thank you.
---last code we try
  variables etc. aren't shown here.</p>

```<code>jpegYapKomutu = videoEditorKlasoru &"\ffmpeg.exe -i " & videoEditorKlasoru & "\deneme.flv" &" -s 480×360 -ss 00:00:"&saniyesi&" -vframes 1 -f mjpeg "&  "C:\Webhome\normworks\caglarorhan\deneme.jpg"
        WScript.Run "%COMSPEC% /C dir" & jpegYapKomutu
</code>```

答:
Most likely IIS is running under an anonymous account.  Try setting the Application Pool to run as a specific user account that has permission to execute ffmpeg.

There's some info here

Body:
We have some kind of permenant permission problem on FFMPEG.exe to write JPEG file on to HDD.
We are using IIS and try all permission methods to ffmepg.exe, its including folder,folders, cmd.exe and any executable file, related folder, file. Also we tried many many command examples. But never went beyond the "permission denied" error messages.
We give up.
Do you know another alternative solution to pick images from flv, f4v movie files? Or %100 quaranteed method to achive this permission control on IIS?
Thank you.
---last code we try
  variables etc. aren't shown here.

jpegYapKomutu = videoEditorKlasoru &"\ffmpeg.exe -i " & videoEditorKlasoru & "\deneme.flv" &" -s 480×360 -ss 00:00:"&saniyesi&" -vframes 1 -f mjpeg "&  "C:\Webhome\normworks\caglarorhan\deneme.jpg"
        WScript.Run "%COMSPEC% /C dir" & jpegYapKomutu


答:
You can use the arrange and slice method as follows:

```<code>library(dplyr)
df %>%
  arrange(Method, Maturity, desc(Yield)) %>%
  group_by(Method, Maturity) %>%
  slice(1) %>%
  ungroup %>%
  select(Method, Maturity, Yield, Year, Group) %>%
  rename(Max_Yield = Yield)
</code>```

Title: Grouping and summarizing by keeping other columns in R

Body:
You can use the arrange and slice method as follows:

library(dplyr)
df %>%
  arrange(Method, Maturity, desc(Yield)) %>%
  group_by(Method, Maturity) %>%
  slice(1) %>%
  ungroup %>%
  select(Method, Maturity, Yield, Year, Group) %>%
  rename(Max_Yield = Yield)


问:
How to fetch JSON file in Angular 2
as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.

My code is like below

Index.html

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/styles.css">

    <my-app>Loading...</my-app>

```
</div>
</div>
</p>

<p>app.component.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
          <div id="main">
            Main Div
               <div id = "header"></div>
               <div id = "content">
                  <ul class="games">
                      <li>

                      </li>
                  </ul>
               </div>
          </div>
     `
})
export class AppComponent {
 }</code>```

games.json

{
 "games":[
  {
   "title":"Primary Operations",
   "enabled":true
  },
  {
   "title":"Curated Games",
   "enabled":false
  }
 ]
}```

I want to fetch all games from games.json into li at app.component.ts
Please advise in detail.

答:
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

```<code>return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}
</code>```

Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.

Title: How to fetch JSON file in Angular 2

Body:
as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.

My code is like below

Index.html

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/styles.css">

    <my-app>Loading...</my-app>

app.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  template: `

            Main Div

     `
})
export class AppComponent {
 }

games.json

{
 "games":[
  {
   "title":"Primary Operations",
   "enabled":true
  },
  {
   "title":"Curated Games",
   "enabled":false
  }
 ]
}

I want to fetch all games from games.json into li at app.component.ts
Please advise in detail.

Body:
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}

Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.


问:
Create this shape in css
Please take a look at this image:

I apologise for my useless paint ability :-)

How can I draw that sort of shape in css, like a ) without the use of text in a div, just pure css.

I have tried to make it curved like in the example, but I don't know how to curve it like that from the center.

What must I do to make this kind of shape in css?

Thanks.

答:
Your example appears to resemble a chevron shape, forgive me if that's not the case, but if it is you are in luck because you can make a chevron shape using pure CSS.

.chevron {
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 60px;
  width: 200px;
}

.chevron:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: black;
  transform: skew(0deg, 6deg);
}
.chevron:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: black;
  transform: skew(0deg, -6deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="chevron"></div></code>```

You can find the original example and some other shapes here

Title: Create this shape in css

Body:
Your example appears to resemble a chevron shape, forgive me if that's not the case, but if it is you are in luck because you can make a chevron shape using pure CSS.

.chevron {
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 60px;
  width: 200px;
}

.chevron:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: black;
  transform: skew(0deg, 6deg);
}
.chevron:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: black;
  transform: skew(0deg, -6deg);
}

<div class="chevron"></div>

You can find the original example and some other shapes here


问:
Create alert using materialize css
I want to create an alert using materialize css. I don't know how. Please help. I just want to create a simple html that will display an alert error without using javascript. Thanks.</p>

答:
You can use Matdialog.js to create different types of dialogboxes.

check it out at - MatDialog.js website

Title: Create alert using materialize css


问:
In WM_RBUTTONUP, does MK_RBUTTON really mean the SHIFT key is down? what?
The documentation says that MK_RBUTTON, and not MK_SHIFT, indicates the Shift key state.

Is this correct or is this a typo? It differs from the behavior in WM_LBUTTONUP.

答: Yeah, it's a typo. Spy++ shows MK_SHIFT and not MK_RBUTTON.


问:
access the element in list of dictionary in python
hi every one i have list of dictionary all of the dictionaries like this:

```<code> dict1 = {Label:----,Chapter:----,Section:----,Massage:----}
 dict2 = {Label:----,Chapter:----,Section:----,Massage:----}
 dict3 = {Label:----,Chapter:----,Section:----,Massage:----}
 List = [dict1 , dict2 , dict3]
</code>```

i want first the all  dictionaries of list if the my label is equal with label in dictionary print the massage of that dictionary.

i use this method but it get nothing.

```<code>def printMassage(List , mylabel):
    for dicts in List:
        if (Label.value == mylabel):
            print( Massage.value)
</code>```

please help me!!

答:
When accessing values in dictionaries, you need to use the key as the lookup:

```<code>def printMassage(List , mylabel):
    for d in List:
        if d['Label'] == mylabel:
            print(d['Massage'])
</code>```

A one-liner:

```<code>def printMassage(List , mylabel):
    print([d['Massage'] for d in List if d[Label] == mylabel])
</code>```

Body:
hi every one i have list of dictionary all of the dictionaries like this:

 dict1 = {Label:----,Chapter:----,Section:----,Massage:----}
 dict2 = {Label:----,Chapter:----,Section:----,Massage:----}
 dict3 = {Label:----,Chapter:----,Section:----,Massage:----}
 List = [dict1 , dict2 , dict3]

i want first the all  dictionaries of list if the my label is equal with label in dictionary print the massage of that dictionary.

i use this method but it get nothing.

def printMassage(List , mylabel):
    for dicts in List:
        if (Label.value == mylabel):
            print( Massage.value)

please help me!!

Body:
When accessing values in dictionaries, you need to use the key as the lookup:

def printMassage(List , mylabel):
    for d in List:
        if d['Label'] == mylabel:
            print(d['Massage'])

A one-liner:

def printMassage(List , mylabel):
    print([d['Massage'] for d in List if d[Label] == mylabel])


问:
How do I find a node.js websocket message's connection?
I was writing the following code for a node.js websocket chat server, and was wondering what the variable lifetime issues around conn are.

```<code>// chat-server.js
// Joshua Marshall Moore
// 12/20/2010

var ws = require("../../lib/ws/server");
var server = ws.createServer();

conns = [];
server.addListener("connection", function(conn){
    function runHandler(msg){
        server.broadcast(JSON.stringify({"who": conns[conn], "when": Date.now(), "what": msg}));
    }

    function setupHandler(msg){
        if(conns.indexOf(msg)==-1 && msg!="Server"){
            // name has not been taken yet
            conns[conn] = msg;
            conn.send("name ok");

            server.broadcast(JSON.stringify({
                "who": "Server",
                "when": Date.now(),
                "what": msg + " has joined us"
            }));

            conn.removeListener("message": setupHandler);
            conn.addListener("message": runHandler);
            return;
        }

        conn.send("name taken");
    }

    conn.addListener("message", setupHandler);
});

server.addListener("close", function(conn){
    server.broadcast(JSON.stringify({
        "who": "Server",
        "when": Date.now(),
        "what": conns[conn] + " has left us."
    }));

    delete conns[conn];
});

server.listen(16007);
</code>```

The code above will run. A server connects, submits a name until the server says it's ok. any message sent from client to server is relayed to all clients.

I was trying to use the connection as a key to later retrieve the name submitted by the client earlier.
However, when a second client connects, all messages are displayed as being from the last person to connect.

I was hoping someone here had some insight as the conn variable's scope throughout its life.
From the looks of it, conn is local to the anonymous function registered for the server connection event. Therefore the functions defined inside of that anonymous function have themselves access to conn.

My more specific question is this: the anonymous function is called each time a new connection is made. Does that mean that each time that happens, the functions setupHandler and runHandler use the copy of conn corresponding to the new connection they were called for, or is there chance for them to mix each other up?

答:
You can't use objects as keys in JavaScript, all that [conn] does is to call toString() on conn. And hardly anyone out there overwrites toString() to return something useful.

So what does toString() return by default? Well for Objects it returns [object Object].

conn should have a id property, that will give you a unique value to use as a key.

Body:
I was writing the following code for a node.js websocket chat server, and was wondering what the variable lifetime issues around conn are.

// chat-server.js
// Joshua Marshall Moore
// 12/20/2010

var ws = require("../../lib/ws/server");
var server = ws.createServer();

conns = [];
server.addListener("connection", function(conn){
    function runHandler(msg){
        server.broadcast(JSON.stringify({"who": conns[conn], "when": Date.now(), "what": msg}));
    }

    function setupHandler(msg){
        if(conns.indexOf(msg)==-1 && msg!="Server"){
            // name has not been taken yet
            conns[conn] = msg;
            conn.send("name ok");

            server.broadcast(JSON.stringify({
                "who": "Server",
                "when": Date.now(),
                "what": msg + " has joined us"
            }));

            conn.removeListener("message": setupHandler);
            conn.addListener("message": runHandler);
            return;
        }

        conn.send("name taken");
    }

    conn.addListener("message", setupHandler);
});

server.addListener("close", function(conn){
    server.broadcast(JSON.stringify({
        "who": "Server",
        "when": Date.now(),
        "what": conns[conn] + " has left us."
    }));

    delete conns[conn];
});

server.listen(16007);

The code above will run. A server connects, submits a name until the server says it's ok. any message sent from client to server is relayed to all clients.

I was trying to use the connection as a key to later retrieve the name submitted by the client earlier.
However, when a second client connects, all messages are displayed as being from the last person to connect.

I was hoping someone here had some insight as the conn variable's scope throughout its life.
From the looks of it, conn is local to the anonymous function registered for the server connection event. Therefore the functions defined inside of that anonymous function have themselves access to conn.

My more specific question is this: the anonymous function is called each time a new connection is made. Does that mean that each time that happens, the functions setupHandler and runHandler use the copy of conn corresponding to the new connection they were called for, or is there chance for them to mix each other up?


答:
How dictionary in python works

```<code>value = dictionary[key]  # get the `value` of `key` in `dictionary`.
dictionary[key] = newvalue  # change the content of `key` in `dictionary` to `newvalue`.
</code>```

Your example

```<code>def printMassage(List , mylabel):
    for dict in List:
        if (dict["Label"] == mylabel):
            print(dict["Massage"])
</code>```

Title: access the element in list of dictionary in python

Body:
How dictionary in python works

value = dictionary[key]  # get the `value` of `key` in `dictionary`.
dictionary[key] = newvalue  # change the content of `key` in `dictionary` to `newvalue`.

Your example

def printMassage(List , mylabel):
    for dict in List:
        if (dict["Label"] == mylabel):
            print(dict["Massage"])


答:
```<code>function looping(length) {
  for(var i=1;i<=length;i++) {
    $("#login-"+i).text($("#" + iconId).data("login"+1));
    $("#login-"+i).click(function() {
       var send='';
       send += $("#" + iconId).data("name")+"</br>";
       send += $("#" + iconId).data("login"+i)+"</br>";
       send += $("#" + iconId).data("username"+i)+"</br>";
       send += $("#" + iconId).data("password"+i)+"</br>";
       $("#post").html(send);
       cancel();
    });
  }
}
looping(3);
</code>```

I think this is what you are expecting.
A '+' operator will concatenate the variable i which is the number in the loop.
$("#login-"+i) Here for first time it will appear as ("#login1") then for i=2 it will be ("#login2") and so on.

Title: How do for statements work in jQuery?

Body:
I am currently using this code for my project but I can help but to feel a for statement could be used instead.

$("#login-1").text($("#" + iconId).data("login1"));
$("#login-1").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"
";
   send += $("#" + iconId).data("login1")+"
";
   send += $("#" + iconId).data("username1")+"
";
   send += $("#" + iconId).data("password1")+"
";
   $("#post").html(send);
   cancel();
});

$("#login-2").text($("#" + iconId).data("login2"));
$("#login-2").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"
";
   send += $("#" + iconId).data("login2")+"
";
   send += $("#" + iconId).data("username2")+"
";
   send += $("#" + iconId).data("password2")+"
";
   $("#post").html(send);
   cancel();
});

$("#login-3").text($("#" + iconId).data("login3"));
$("#login-3").click(function() {
   var send='';
   send += $("#" + iconId).data("name")+"
";
   send += $("#" + iconId).data("login3")+"
";
   send += $("#" + iconId).data("username3")+"
";
   send += $("#" + iconId).data("password3")+"
";
   $("#post").html(send);
   cancel();
});

The only thing changing in between most of the lines of code are the number on login# username# password#

Body:
function looping(length) {
  for(var i=1;i<=length;i++) {
    $("#login-"+i).text($("#" + iconId).data("login"+1));
    $("#login-"+i).click(function() {
       var send='';
       send += $("#" + iconId).data("name")+"</br>";
       send += $("#" + iconId).data("login"+i)+"</br>";
       send += $("#" + iconId).data("username"+i)+"</br>";
       send += $("#" + iconId).data("password"+i)+"</br>";
       $("#post").html(send);
       cancel();
    });
  }
}
looping(3);

I think this is what you are expecting.
A '+' operator will concatenate the variable i which is the number in the loop.
$("#login-"+i) Here for first time it will appear as ("#login1") then for i=2 it will be ("#login2") and so on.


问:
A summary of all Google Apps Script triggers in my account
Is there any place where I can see the summary of all the Apps Script timed triggers installed for all my documents on Google Drive?</p>

答:
Changes :

Go to the script editor, choose "Edit" and you'll get a result as illustrated below :


问:
How do I get the next pagination 'href'?
So I am having trouble obtaining the href link for the next pages of the url. I got up to obtaining all the text and what not that the tag contains but I can't seem to wrap my head around to removing the text that I don't need and just obtaining the href and navigating through the pages.

Here is my code:

```<code>import requests
from bs4 import BeautifulSoup
import webbrowser
import time

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)
base_url = 'https://ca.indeed.com/'

r = requests.get(url)
rcontent = r.content
prettify = BeautifulSoup(rcontent, "html.parser")

filter_words = ['engineering', 'instrumentation', 'QA']
all_job_url = []
nextpages = []
filtered_job_links = []
http_flinks = []
flinks = []

def all_next_pages():
    pages = prettify.find_all('div', {'class':'pagination'})
    for next_page in pages:
        next_page.find_all('a')
        nextpages.append(next_page)
        print(next_page)

all_next_pages()
</code>```

答:
Here is a way to get the links of the search result items. Find row  result class and then find a tag, it contains all the information you need.

```<code>import requests
from bs4 import BeautifulSoup
import webbrowser
import time

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)
base_url = 'https://ca.indeed.com/'

r = requests.get(url)
rcontent = r.text
prettify = BeautifulSoup(rcontent, "lxml")

filter_words = ['engineering', 'instrumentation', 'QA']
all_job_url = []
nextpages = []
filtered_job_links = []
http_flinks = []
flinks = []

def all_next_pages():
    pages = prettify.find_all('div', {'class':'  row  result'})
    for next_page in pages:
        info = next_page.find('a')
        url = info.get('href')
        title = info.get('title')
        print(title,url)

all_next_pages()
</code>```

Body:
So I am having trouble obtaining the href link for the next pages of the url. I got up to obtaining all the text and what not that the tag contains but I can't seem to wrap my head around to removing the text that I don't need and just obtaining the href and navigating through the pages.

Here is my code:

import requests
from bs4 import BeautifulSoup
import webbrowser
import time

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)
base_url = 'https://ca.indeed.com/'

r = requests.get(url)
rcontent = r.content
prettify = BeautifulSoup(rcontent, "html.parser")

filter_words = ['engineering', 'instrumentation', 'QA']
all_job_url = []
nextpages = []
filtered_job_links = []
http_flinks = []
flinks = []

def all_next_pages():
    pages = prettify.find_all('div', {'class':'pagination'})
    for next_page in pages:
        next_page.find_all('a')
        nextpages.append(next_page)
        print(next_page)

all_next_pages()

Body:
Here is a way to get the links of the search result items. Find row  result class and then find a tag, it contains all the information you need.

import requests
from bs4 import BeautifulSoup
import webbrowser
import time

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)
base_url = 'https://ca.indeed.com/'

r = requests.get(url)
rcontent = r.text
prettify = BeautifulSoup(rcontent, "lxml")

filter_words = ['engineering', 'instrumentation', 'QA']
all_job_url = []
nextpages = []
filtered_job_links = []
http_flinks = []
flinks = []

def all_next_pages():
    pages = prettify.find_all('div', {'class':'  row  result'})
    for next_page in pages:
        info = next_page.find('a')
        url = info.get('href')
        title = info.get('title')
        print(title,url)

all_next_pages()


问:
Better way to Check for values
Is there a more elegant way to do this?

```<code>if(response && response.body && response.body.data) {
  const users = response.body.data
  dispatch(UserActions.usersReceived(users))
}
</code>```

Meaning the response && response.body && response.body.data ?

答:
Php has something called isset(), but Js does not seem to have that function. Here is one of my favorites that I found on stack overflow a while back. </p>

```<code>user = {
  loc: {
        lat: 50,
        long: 9
  }
}

user2 = null;

has = function(obj, key) {
return key.split(".").every(function(x) {
    if(typeof obj != "object" || obj === null || !( x in obj)) {
        return false;
    }
    obj = obj[x];
    return true;
});
}

console.log(has(user, 'loc.lat')); //true
console.log(has(user, 'loc')); //true
console.log(has(user, 'loc.lat.ll')); // false
console.log(has(user2, 'd')); //false
</code>```

Title: Better way to Check for values

Body:
Is there a more elegant way to do this?

if(response && response.body && response.body.data) {
  const users = response.body.data
  dispatch(UserActions.usersReceived(users))
}

Meaning the response && response.body && response.body.data ?

Body:
Php has something called isset(), but Js does not seem to have that function. Here is one of my favorites that I found on stack overflow a while back.

user = {
  loc: {
        lat: 50,
        long: 9
  }
}

user2 = null;

has = function(obj, key) {
return key.split(".").every(function(x) {
    if(typeof obj != "object" || obj === null || !( x in obj)) {
        return false;
    }
    obj = obj[x];
    return true;
});
}

console.log(has(user, 'loc.lat')); //true
console.log(has(user, 'loc')); //true
console.log(has(user, 'loc.lat.ll')); // false
console.log(has(user2, 'd')); //false