问:
How do I call an XML-based external rest API from AWS lambda?
I'm trying to call an external API from AWS lambda. I didn't use the node.js http module because I heard it was cumbersome. So I'm trying to use the AWS SDK to accomplish the task. See https://boylesoftware.com/blog/calling-restful-apis-from-inline-aws-lambda-functions/. This code seems to mostly work but I'm not sure because the API should return and XML payload but it does not. No error is thrown but an empty object {} is returned in the data variable.

I'm guessing it has to do with the output spec that I commented out. I don't know the SDK well enough to know how to describe the XML payload. I tried switching it to string to no avail.

I am able to successfully receive an XML payload from this API when I call it via Postman. An example response from the API is included below my lambda code.

'use strict';

// load AWS SDK module, which is always included in the runtime environment
const AWS = require('aws-sdk');
const UTA = {
  token: process.env.uta_api_token
};

// define our target API as a "service"
const svc = new AWS.Service({

    // the API base URL
    endpoint: 'http://api.rideuta.com/SIRI/SIRI.svc',

    // don't parse API responses
    // (this is optional if you want to define shapes of all your endpoint responses)
    convertResponseTypes: false,

    // and now, our API endpoints
    apiConfig: {
        metadata: {
            protocol: 'rest-xml' // API returns XML
        },
        operations: {

            // GetStop stuff
            GetStop: {
                http: {
                    method: 'GET',
                    // note the placeholder in the URI
                    requestUri: 'StopMonitor'
                },
                input: {
                    type: 'structure',
                    required: [ 'auth', 'stopid', 'minutesout' ],
                    members: {
                        'auth': {
                            // send authentication header in the HTTP request header
                            location: 'uri',
                            locationName: 'usertoken',
                            sensitive: true
                        },
                        'stopid': {
                            // all kinds of validators are available
                            type: 'string',
                            // include it in the call URI
                            location: 'uri',
                            // this is the name of the placeholder in the URI
                            locationName: 'stopid'
                        },
                        'minutesout' : {
                            type : 'integer',
                            location : 'uri',
                            locationName : 'minutesout'
                        }
                    }
                },
                /*
                output: {
                    type: 'structure',
                    members:  {
                        'ResponseTimestamp' : {
                            location : 'body',
                            locationName : 'ResponseTimestamp'
                        }
                    }
                }
                */
            }
        }
    }
});

// disable AWS region related login in the SDK
svc.isGlobalEndpoint = true;

// and now we can call our target API!
exports.handler = function(event, context, callback) {

    // note how the methods on our service are defined after the operations
   //ontext.succeed('hello world');
    svc.getStop({
            auth: UTA.token,
            stopid: 'FR301084',
            minutesout : 600,
        }, (err, data) => {

            if (err) {
                console.error('>>> operation error:', err);
                return callback(err);
            }

            console.log('it worked');
            console.log(UTA.token);
            console.log(data);
            callback();
    });
};```
</div>
</div>
</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<Siri version="1.3" xmlns="http://www.siri.org.uk/siri">
    <ResponseTimestamp>2019-02-16T22:37:24.1431014-07:00</ResponseTimestamp>
    <StopMonitoringDelivery version="1.3">
        <ResponseTimestamp>2019-02-16T22:37:24.1431014-07:00</ResponseTimestamp>
        <ValidUntil>2019-02-16T22:37:34.1431014-07:00</ValidUntil>
        <MonitoredStopVisit>
            <RecordedAtTime>2019-02-16T22:37:24.1431014-07:00</RecordedAtTime>
            <MonitoredVehicleJourney>
                <LineRef>750</LineRef>
                <DirectionRef>SOUTHBOUND</DirectionRef>
                <FramedVehicleJourneyRef>
                    <DataFrameRef>2019-02-16T00:00:00-07:00</DataFrameRef>
                    <DatedVehicleJourneyRef>3706978</DatedVehicleJourneyRef>
                </FramedVehicleJourneyRef>
                <PublishedLineName>FRONTRUNNER</PublishedLineName>
                <OriginRef>FR601084</OriginRef>
                <DestinationRef>FR801164</DestinationRef>
                <Monitored>True</Monitored>
                <VehicleLocation>
                    <Longitude>-111.9306</Longitude>
                    <Latitude>41.004124</Latitude>
                </VehicleLocation>
                <ProgressRate>1</ProgressRate>
                <CourseOfJourneyRef>18084</CourseOfJourneyRef>
                <VehicleRef>113</VehicleRef>
                <MonitoredCall>
                    <StopPointRef>FR301084</StopPointRef>
                    <VisitNumber>1</VisitNumber>
                    <VehicleAtStop>false</VehicleAtStop>
                    <Extensions>
                        <EstimatedDepartureTime>136</EstimatedDepartureTime>
                        <Direction>To Provo</Direction>
                        <Distance>9644.7823876475977</Distance>
                    </Extensions>
                </MonitoredCall>
                <Extensions>
                    <LastGPSFix>2019-02-16T22:37:16</LastGPSFix>
                    <Scheduled>False</Scheduled>
                    <Bearing>129.54093468554098</Bearing>
                    <Speed>79.829126894854753</Speed>
                    <DestinationName>Provo</DestinationName>
                </Extensions>
            </MonitoredVehicleJourney>
            <MonitoredVehicleJourney>
                <LineRef>750</LineRef>
                <DirectionRef>NORTHBOUND</DirectionRef>
                <FramedVehicleJourneyRef>
                    <DataFrameRef>2019-02-16T00:00:00-07:00</DataFrameRef>
                    <DatedVehicleJourneyRef>3706927</DatedVehicleJourneyRef>
                </FramedVehicleJourneyRef>
                <PublishedLineName>FRONTRUNNER</PublishedLineName>
                <OriginRef>FR801164</OriginRef>
                <DestinationRef>FR601084</DestinationRef>
                <Monitored>True</Monitored>
                <VehicleLocation>
                    <Longitude>-111.904274</Longitude>
                    <Latitude>40.625053</Latitude>
                </VehicleLocation>
                <ProgressRate>1</ProgressRate>
                <CourseOfJourneyRef>18124</CourseOfJourneyRef>
                <VehicleRef>108</VehicleRef>
                <MonitoredCall>
                    <StopPointRef>FR301081</StopPointRef>
                    <VisitNumber>1</VisitNumber>
                    <VehicleAtStop>false</VehicleAtStop>
                    <Extensions>
                        <EstimatedDepartureTime>2912</EstimatedDepartureTime>
                        <Direction>To Ogden</Direction>
                        <Distance>132285.03109158284</Distance>
                    </Extensions>
                </MonitoredCall>
                <Extensions>
                    <LastGPSFix>2019-02-16T22:37:20</LastGPSFix>
                    <Scheduled>False</Scheduled>
                    <Bearing>10.410927719684226</Bearing>
                    <Speed>79.067224214902424</Speed>
                    <DestinationName>Ogden</DestinationName>
                </Extensions>
            </MonitoredVehicleJourney>
        </MonitoredStopVisit>
        <Extensions>
            <StopName>FARMINGTON STATION</StopName>
            <StopLongitude>-111.903667000</StopLongitude>
            <StopLatitude>40.987266000</StopLatitude>
            <StopLocation>Utah</StopLocation>
        </Extensions>
    </StopMonitoringDelivery>
</Siri>
</code>```

答: convertResponseTypes needs to set to true if you want to process the response.</p>

Body:
I'm trying to call an external API from AWS lambda. I didn't use the node.js http module because I heard it was cumbersome. So I'm trying to use the AWS SDK to accomplish the task. See https://boylesoftware.com/blog/calling-restful-apis-from-inline-aws-lambda-functions/. This code seems to mostly work but I'm not sure because the API should return and XML payload but it does not. No error is thrown but an empty object {} is returned in the data variable.

I'm guessing it has to do with the output spec that I commented out. I don't know the SDK well enough to know how to describe the XML payload. I tried switching it to string to no avail.

I am able to successfully receive an XML payload from this API when I call it via Postman. An example response from the API is included below my lambda code.

'use strict';

// load AWS SDK module, which is always included in the runtime environment
const AWS = require('aws-sdk');
const UTA = {
  token: process.env.uta_api_token
};

// define our target API as a "service"
const svc = new AWS.Service({

    // the API base URL
    endpoint: 'http://api.rideuta.com/SIRI/SIRI.svc',

    // don't parse API responses
    // (this is optional if you want to define shapes of all your endpoint responses)
    convertResponseTypes: false,

    // and now, our API endpoints
    apiConfig: {
        metadata: {
            protocol: 'rest-xml' // API returns XML
        },
        operations: {

            // GetStop stuff
            GetStop: {
                http: {
                    method: 'GET',
                    // note the placeholder in the URI
                    requestUri: 'StopMonitor'
                },
                input: {
                    type: 'structure',
                    required: [ 'auth', 'stopid', 'minutesout' ],
                    members: {
                        'auth': {
                            // send authentication header in the HTTP request header
                            location: 'uri',
                            locationName: 'usertoken',
                            sensitive: true
                        },
                        'stopid': {
                            // all kinds of validators are available
                            type: 'string',
                            // include it in the call URI
                            location: 'uri',
                            // this is the name of the placeholder in the URI
                            locationName: 'stopid'
                        },
                        'minutesout' : {
                            type : 'integer',
                            location : 'uri',
                            locationName : 'minutesout'
                        }
                    }
                },
                /*
                output: {
                    type: 'structure',
                    members:  {
                        'ResponseTimestamp' : {
                            location : 'body',
                            locationName : 'ResponseTimestamp'
                        }
                    }
                }
                */
            }
        }
    }
});

// disable AWS region related login in the SDK
svc.isGlobalEndpoint = true;

// and now we can call our target API!
exports.handler = function(event, context, callback) {

    // note how the methods on our service are defined after the operations
   //ontext.succeed('hello world');
    svc.getStop({
            auth: UTA.token,
            stopid: 'FR301084',
            minutesout : 600,
        }, (err, data) => {

            if (err) {
                console.error('>>> operation error:', err);
                return callback(err);
            }

            console.log('it worked');
            console.log(UTA.token);
            console.log(data);
            callback();
    });
};

<?xml version="1.0" encoding="utf-8"?>
<Siri version="1.3" xmlns="http://www.siri.org.uk/siri">
    <ResponseTimestamp>2019-02-16T22:37:24.1431014-07:00</ResponseTimestamp>
    <StopMonitoringDelivery version="1.3">
        <ResponseTimestamp>2019-02-16T22:37:24.1431014-07:00</ResponseTimestamp>
        <ValidUntil>2019-02-16T22:37:34.1431014-07:00</ValidUntil>
        <MonitoredStopVisit>
            <RecordedAtTime>2019-02-16T22:37:24.1431014-07:00</RecordedAtTime>
            <MonitoredVehicleJourney>
                <LineRef>750</LineRef>
                <DirectionRef>SOUTHBOUND</DirectionRef>
                <FramedVehicleJourneyRef>
                    <DataFrameRef>2019-02-16T00:00:00-07:00</DataFrameRef>
                    <DatedVehicleJourneyRef>3706978</DatedVehicleJourneyRef>
                </FramedVehicleJourneyRef>
                <PublishedLineName>FRONTRUNNER</PublishedLineName>
                <OriginRef>FR601084</OriginRef>
                <DestinationRef>FR801164</DestinationRef>
                <Monitored>True</Monitored>
                <VehicleLocation>
                    <Longitude>-111.9306</Longitude>
                    <Latitude>41.004124</Latitude>
                </VehicleLocation>
                <ProgressRate>1</ProgressRate>
                <CourseOfJourneyRef>18084</CourseOfJourneyRef>
                <VehicleRef>113</VehicleRef>
                <MonitoredCall>
                    <StopPointRef>FR301084</StopPointRef>
                    <VisitNumber>1</VisitNumber>
                    <VehicleAtStop>false</VehicleAtStop>
                    <Extensions>
                        <EstimatedDepartureTime>136</EstimatedDepartureTime>
                        <Direction>To Provo</Direction>
                        <Distance>9644.7823876475977</Distance>
                    </Extensions>
                </MonitoredCall>
                <Extensions>
                    <LastGPSFix>2019-02-16T22:37:16</LastGPSFix>
                    <Scheduled>False</Scheduled>
                    <Bearing>129.54093468554098</Bearing>
                    <Speed>79.829126894854753</Speed>
                    <DestinationName>Provo</DestinationName>
                </Extensions>
            </MonitoredVehicleJourney>
            <MonitoredVehicleJourney>
                <LineRef>750</LineRef>
                <DirectionRef>NORTHBOUND</DirectionRef>
                <FramedVehicleJourneyRef>
                    <DataFrameRef>2019-02-16T00:00:00-07:00</DataFrameRef>
                    <DatedVehicleJourneyRef>3706927</DatedVehicleJourneyRef>
                </FramedVehicleJourneyRef>
                <PublishedLineName>FRONTRUNNER</PublishedLineName>
                <OriginRef>FR801164</OriginRef>
                <DestinationRef>FR601084</DestinationRef>
                <Monitored>True</Monitored>
                <VehicleLocation>
                    <Longitude>-111.904274</Longitude>
                    <Latitude>40.625053</Latitude>
                </VehicleLocation>
                <ProgressRate>1</ProgressRate>
                <CourseOfJourneyRef>18124</CourseOfJourneyRef>
                <VehicleRef>108</VehicleRef>
                <MonitoredCall>
                    <StopPointRef>FR301081</StopPointRef>
                    <VisitNumber>1</VisitNumber>
                    <VehicleAtStop>false</VehicleAtStop>
                    <Extensions>
                        <EstimatedDepartureTime>2912</EstimatedDepartureTime>
                        <Direction>To Ogden</Direction>
                        <Distance>132285.03109158284</Distance>
                    </Extensions>
                </MonitoredCall>
                <Extensions>
                    <LastGPSFix>2019-02-16T22:37:20</LastGPSFix>
                    <Scheduled>False</Scheduled>
                    <Bearing>10.410927719684226</Bearing>
                    <Speed>79.067224214902424</Speed>
                    <DestinationName>Ogden</DestinationName>
                </Extensions>
            </MonitoredVehicleJourney>
        </MonitoredStopVisit>
        <Extensions>
            <StopName>FARMINGTON STATION</StopName>
            <StopLongitude>-111.903667000</StopLongitude>
            <StopLatitude>40.987266000</StopLatitude>
            <StopLocation>Utah</StopLocation>
        </Extensions>
    </StopMonitoringDelivery>
</Siri>


来源: stackexchange

问:
Can you use Microsoft Graph API in JavaScript to get list items?
I'm using the samples for the MSAL and converting them to use MS Graph to read SharePoint but when it comes to reading list items it seems I am getting permissions issues.

To make sure I have my syntax correct, I use the Graph Explorer with my AD account and I am able to read list items and confirm the URI is correct. I am also able to read and get an array of lists. But as soon as I try to get the list items for a list nothing is returned.

The base code is here https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa

Here's the code I converted from the sample. If you update the variables and register in Azure you should be able to run against your SPO site.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quickstart for MSAL JS</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/msal.js"></script>
</head>
<body>
    <h2>Welcome to MSAL.js Quickstart</h2><br />
    <h4 id="WelcomeMessage"></h4>
    <button id="SignIn" onclick="signIn()">Sign In</button><br /><br />
    <button id="btnAllLists" onclick="GetWithEndPoint()">Get All Lists</button><br /><br />
    <button id="btnListItems" onclick="GetWithEndPoint()">Get List Items</button><br /><br />
    <button id="btnListItemsAllFields" onclick="GetWithEndPoint()">Get List Items All Fields</button><br /><br />
    <pre id="json">```

```

<p>Clicking either button that returns list items throws this message which I understand to mean is permissions.</p>

```    {
      "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.list)('myid')/items",
      "value": []
    }
```

My expectation is that I would get the same results from the Graph Explorer. But this indicates I don't have permission. I've tried a few different lists and the results are always the same. I can get a list of all the lists. But trying to get the items from a list fails.

Can we not use the Graph API with JS to get list items?

Here are the Azure delegated permissions from Azure which I think should be all I need to get list items.

答:
But this indicates I don't have permission

That's right, empty results usually indicates one of the following permissions (delegated permissions in your case) are missing for Get Items endpoint:

Sites.Read.All - read items in all site collections

Sites.ReadWrite.All - edit or delete items in all site collections

ContentLicense: CC BY-SA 4.0

Body:
I'm using the samples for the MSAL and converting them to use MS Graph to read SharePoint but when it comes to reading list items it seems I am getting permissions issues.

To make sure I have my syntax correct, I use the Graph Explorer with my AD account and I am able to read list items and confirm the URI is correct. I am also able to read and get an array of lists. But as soon as I try to get the list items for a list nothing is returned.

The base code is here https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa

Here's the code I converted from the sample. If you update the variables and register in Azure you should be able to run against your SPO site.

<!DOCTYPE html>

    <title>Quickstart for MSAL JS</title>

Welcome to MSAL.js Quickstart

    <button id="SignIn" onclick="signIn()">Sign In</button>

    <button id="btnAllLists" onclick="GetWithEndPoint()">Get All Lists</button>

    <button id="btnListItems" onclick="GetWithEndPoint()">Get List Items</button>

    <button id="btnListItemsAllFields" onclick="GetWithEndPoint()">Get List Items All Fields</button>

Clicking either button that returns list items throws this message which I understand to mean is permissions.

    {
      "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.list)('myid')/items",
      "value": []
    }

My expectation is that I would get the same results from the Graph Explorer. But this indicates I don't have permission. I've tried a few different lists and the results are always the same. I can get a list of all the lists. But trying to get the items from a list fails.

Can we not use the Graph API with JS to get list items?

Here are the Azure delegated permissions from Azure which I think should be all I need to get list items.


问:
How to test component which render children elements inside?
I have following component:

```<code>export default function Button({ className, children, ...otherProps }) {
  return (
    <button className={'button} {...otherProps}>
      {children}
    </button>
  );
}
</code>```

and in parent component I passed such props and tag inside:

```<code><Button className={test-button} onClick={this.removeItems} >
    <i className="fa fa-trash-alt" /> Remove all items
</Button>
</code>```

I cannot understand how to properly unit test such components. For example I want to test onClick function to have been called when I click on the component.

I wrote such a test:

```<code>const buttonFunc = jest.fn();
    const props = {
        children: {
        className: "test",
        onClick: buttonFunc,
    }
};

let wrapper;

beforeEach(() => {
    wrapper = shallow(<Button {...props} />);
});

test('click on switch button', () => {
    wrapper.simulate('click');
    expect(buttonFunc).toHaveBeenCalledTimes(1);
    console.log(wrapper.debug())
});
</code>```

but I have an error

Expected mock function to have been called one time, but it was called zero times.

答:
You are passing props wrongly. You don't need to pass children as named property. you can add that in your shallow method.
onClick and className are props, should not be inside children.</p>

```<code>const props = {
    className: "test",
    onClick: buttonFunc,
};

wrapper = shallow(<Button {...props}> Button Text </Button>);
</code>```

Body:
I have following component:

export default function Button({ className, children, ...otherProps }) {
  return (
    <button className={'button} {...otherProps}>
      {children}
    </button>
  );
}

and in parent component I passed such props and tag inside:

<Button className={test-button} onClick={this.removeItems} >
     Remove all items
</Button>

I cannot understand how to properly unit test such components. For example I want to test onClick function to have been called when I click on the component.

I wrote such a test:

const buttonFunc = jest.fn();
    const props = {
        children: {
        className: "test",
        onClick: buttonFunc,
    }
};

let wrapper;

beforeEach(() => {
    wrapper = shallow(<Button {...props} />);
});

test('click on switch button', () => {
    wrapper.simulate('click');
    expect(buttonFunc).toHaveBeenCalledTimes(1);
    console.log(wrapper.debug())
});

but I have an error

Expected mock function to have been called one time, but it was called zero times.

Body:
You are passing props wrongly. You don't need to pass children as named property. you can add that in your shallow method.
onClick and className are props, should not be inside children.

const props = {
    className: "test",
    onClick: buttonFunc,
};

wrapper = shallow(<Button {...props}> Button Text </Button>);


问:
how to get the unique max data
I have below table

```<code>userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          26          1           High School     15          Class 10     26          67                     2           All Subject
60          26          2           Senior Secondry 15          Class 12     26          85                     2           Commerce
60          2010        3           Graduates       4           B.Tech/B.E   2010        54                     1           IT/Computers
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce
</code>```

i wanted to get the unique record of max coursecode, the output should be

```<code>userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce
</code>```

There will be many records of the different userids

答:
I think you want:

```<code>select t.*
from t
where t.coursecode = (select max(t2.coursecode)
                      from t t2
                      where t2.userid = t.userid
                     );
</code>```

You can also do this with window functions, but the correlated subquery is often faster with the right index, which would be on (userid, coursecode).

Title: how to get the unique max data

Body:
I have below table

userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          26          1           High School     15          Class 10     26          67                     2           All Subject
60          26          2           Senior Secondry 15          Class 12     26          85                     2           Commerce
60          2010        3           Graduates       4           B.Tech/B.E   2010        54                     1           IT/Computers
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce

i wanted to get the unique record of max coursecode, the output should be

userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce

There will be many records of the different userids

Body:
I think you want:

select t.*
from t
where t.coursecode = (select max(t2.coursecode)
                      from t t2
                      where t2.userid = t.userid
                     );

You can also do this with window functions, but the correlated subquery is often faster with the right index, which would be on (userid, coursecode).


问:
How to tie radio button with input text fields?
This is a sign up form for an employee. The employee has to check in a radio button if he is temporary or permament. If temporary he should fill the input contract number and if permament the hiring date. How can I bind the radio button with the input so that he cannot "cross-complete" , for example fill the hiring date if he is temporary. I want to enable him to fill out each input only if he has pressed that specific radio button.

php code :

```<code><?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>
<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML
4.0 Transitional//EN"><HTML>
  <HEAD>
      <link rel="stylesheet" type="text/css" href="logintest.css">
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </HEAD>
  <button class="btn" TYPE="submit" name="goback" onclick="window.location.href='login.php'">Go Back </button>

      <?php
      error_reporting(E_ALL); ini_set('display_errors', 1);
      if(isset($_POST['submit']))
      {
        $sql = "INSERT INTO employee (empID,EFirst,ELast,username, passcode)
        VALUES ('".$_POST["empID"]."','".$_POST["EFirst"]."','".$_POST["ELast"]."','".$_POST["username"]."','".$_POST["passcode"]."')";

        $result = mysqli_query($conn,$sql);
        $answer=$_POST['kind'];
        if($answer='permament'){
          $sql1 = "INSERT INTO permament_employee (empID,Hiring_Date) VALUES ('".$_POST["empID"]."','".$_POST["date"]."')";
          $result1 = mysqli_query($conn,$sql1);
        }

        if ($answer='temporary'){
          $sql2= "INSERT INTO temporary_employee(empID) VALUES ('".$_POST["empID"]."')";
          $result2 = mysqli_query($conn,$sql2);
        }
        echo "<script> location.replace('login.php') </script>";
      }
      ?>

    <FORM METHOD="post" ACTION="">
        <div class="input-group">
        <label>id</label>
           <INPUT TYPE="text" name="empID" SIZE="30" required>
        </div>
        <div class="input-group">
           <label>First Name</label>
           <INPUT TYPE="text" name="EFirst" SIZE="30" required>
        </div>
        <div class="input-group">
           <label>Last Name</label>
           <INPUT TYPE="text" name="ELast" SIZE="30" required>
        </div>
        <div class="input-group">
            <label>username</label>
            <INPUT TYPE="text" name="username" SIZE="30" required>
        </div>
        <div class="input-group">
             <label>password</label>
             <INPUT TYPE="password" name="passcode" SIZE="30" required>
        </div>
        <div class="input-group">
          <div class="some-class">
          <label> Permament  <input type="radio" name="kind" value="permament" id="permament" required>  <br>   <input type="date" name="date" value="date" id="date" required>  <br> </label>
          <label> Temporary  <input type="radio" name="kind" value="temporary" id="temporary" required>  <br>  <input type="number" name="ContractNr" value="ContractNr" id="ContractNr" placeholder="Contract Number" required>  <br>     </label>
          </div>
        </div>
        <br>
        <br>
        <br>
        <br>

        <button class="btn" TYPE="submit" name="submit">Submit Info </button>
        <button class="btn" TYPE="reset" name="Reset">Reset </button>
    </FORM>

</HTML>
</code>```

答:
If you are using jQuery you could add the following :

```<code><script>
    $(‘input[name=“kind”]’).change(function(){
        if($(this).val() == ‘temporary’){
            $(‘input[name=“date”]).hide();
            $(‘input[name=“ContractNr”]).show();
        }else{
            $(‘input[name=“date”]).show();
            $(‘input[name=“ContractNr”]).hide();
        }
    });
</script>
</code>```

Or if you just want to disable :

```<code><script>
    $(‘input[name=“kind”]’).change(function(){
        if($(this).val() == ‘temporary’){
            $(‘input[name=“date”]).prop(‘disabled’, true);
            $(‘input[name=“ContractNr”]).prop(‘disabled’, false);
        }else{
            $(‘input[name=“date”]).prop(‘disabled’, false);
            $(‘input[name=“ContractNr”]).prop(‘disabled’, true);
        }
    });
</script>
</code>```

Body:
This is a sign up form for an employee. The employee has to check in a radio button if he is temporary or permament. If temporary he should fill the input contract number and if permament the hiring date. How can I bind the radio button with the input so that he cannot "cross-complete" , for example fill the hiring date if he is temporary. I want to enable him to fill out each input only if he has pressed that specific radio button.

php code :

<?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>
<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML
4.0 Transitional//EN">

      <link rel="stylesheet" type="text/css" href="logintest.css">
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  <button class="btn" TYPE="submit" name="goback" onclick="window.location.href='login.php'">Go Back </button>

      <?php
      error_reporting(E_ALL); ini_set('display_errors', 1);
      if(isset($_POST['submit']))
      {
        $sql = "INSERT INTO employee (empID,EFirst,ELast,username, passcode)
        VALUES ('".$_POST["empID"]."','".$_POST["EFirst"]."','".$_POST["ELast"]."','".$_POST["username"]."','".$_POST["passcode"]."')";

        $result = mysqli_query($conn,$sql);
        $answer=$_POST['kind'];
        if($answer='permament'){
          $sql1 = "INSERT INTO permament_employee (empID,Hiring_Date) VALUES ('".$_POST["empID"]."','".$_POST["date"]."')";
          $result1 = mysqli_query($conn,$sql1);
        }

        if ($answer='temporary'){
          $sql2= "INSERT INTO temporary_employee(empID) VALUES ('".$_POST["empID"]."')";
          $result2 = mysqli_query($conn,$sql2);
        }
        echo "";
      }
      ?>

    <FORM METHOD="post" ACTION="">

        id
           <INPUT TYPE="text" name="empID" SIZE="30" required>

           First Name
           <INPUT TYPE="text" name="EFirst" SIZE="30" required>

           Last Name
           <INPUT TYPE="text" name="ELast" SIZE="30" required>

            username
            <INPUT TYPE="text" name="username" SIZE="30" required>

             password
             <INPUT TYPE="password" name="passcode" SIZE="30" required>

           Permament  <input type="radio" name="kind" value="permament" id="permament" required>
   <input type="date" name="date" value="date" id="date" required>

           Temporary  <input type="radio" name="kind" value="temporary" id="temporary" required>
  <input type="number" name="ContractNr" value="ContractNr" id="ContractNr" placeholder="Contract Number" required>

        <button class="btn" TYPE="submit" name="submit">Submit Info </button>
        <button class="btn" TYPE="reset" name="Reset">Reset </button>
    </FORM>

Body:
If you are using jQuery you could add the following :

<script>
    $(‘input[name=“kind”]’).change(function(){
        if($(this).val() == ‘temporary’){
            $(‘input[name=“date”]).hide();
            $(‘input[name=“ContractNr”]).show();
        }else{
            $(‘input[name=“date”]).show();
            $(‘input[name=“ContractNr”]).hide();
        }
    });
</script>

Or if you just want to disable :

<script>
    $(‘input[name=“kind”]’).change(function(){
        if($(this).val() == ‘temporary’){
            $(‘input[name=“date”]).prop(‘disabled’, true);
            $(‘input[name=“ContractNr”]).prop(‘disabled’, false);
        }else{
            $(‘input[name=“date”]).prop(‘disabled’, false);
            $(‘input[name=“ContractNr”]).prop(‘disabled’, true);
        }
    });
</script>


问:
owl-stage width on mobile (or small devices) view is larger than screen
I'm working on a clients website, implementing owl-carousel, but when going into mobile view in chrome + Firefox, owl-stage width (Which is auto calculated) goes crazy as I resize and go back go normal, widths around 4000px...etc.

P.S. code works fine on normal desktop view, it all goes crazy on 576px and below.

I have googled owl-stage width issue and found many old reports and solutions (including stack-overflow) that did not fix my problem, including setting overflow, removing owl options to debug.

code can be found here:
https://www.fisique.co/v2/

owl-stage width should be normal and not more than screen, which in return will render the h1 above it to be perfectly centered on the screen.

答:
Ok, I spent more than 12 hours to figure out why this weird behavior.
Turns out, if you're using PagePilling.js (or fullPage.js) and trying to mix with Owl.Carousel or any other Carousel plugin, a conflict occurs because of css display property of auto generated divs set to table

The solution for my case was adding table-layout: fixed:

```<code>.pp-section.pp-table {
        display: table;
        table-layout: fixed;
}
</code>```

If you're interested to read more about it:
https://github.com/alvarotrigo/fullPage.js/issues/895

Body:
Ok, I spent more than 12 hours to figure out why this weird behavior.
Turns out, if you're using PagePilling.js (or fullPage.js) and trying to mix with Owl.Carousel or any other Carousel plugin, a conflict occurs because of css display property of auto generated divs set to table

The solution for my case was adding table-layout: fixed:

.pp-section.pp-table {
        display: table;
        table-layout: fixed;
}

If you're interested to read more about it:
https://github.com/alvarotrigo/fullPage.js/issues/895


问:
Do-While won't repeat itself
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

```<code>static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}
</code>```

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

答:
This Works fine:

I removed money > 20000 because this condition will never be fulfilled by current flow

```<code> public static void Main()
        {
            int MyAge = 25;
            int money = 15000;
            do
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.WriteLine("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.WriteLine("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
            while (MyAge < 65);
            Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
        }
</code>```

Title: Do-While won't repeat itself

Body:
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

Body:
This Works fine:

I removed money > 20000 because this condition will never be fulfilled by current flow

 public static void Main()
        {
            int MyAge = 25;
            int money = 15000;
            do
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.WriteLine("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.WriteLine("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
            while (MyAge < 65);
            Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
        }


问:
Need to use Solr dismax handler but i have no q parameter???
Hi
   i am trying to make a solr Query using dismax handler but i have no q parameters because i have to match directly on fields..

```<code>hl.fragsize=200&mm=1&facet=on&facet.mincount=1&qf=text+&wt=json&hl=true&rows=50&fl=*+score&start=0&q=*:*&fq=jSFunT:("Fresher"+OR+"Developer+/+Programmer+/+Coder")&fq=jNMinEx:[2+TO+*]&fq=jNMaxEx:[2+TO+5]&fq=jNMinSal:[-1+TO+*]&fq=jNMaxSal:[-1+TO+-1]&bq=jSFunT:("Developer+/+Programmer+/+Coder")^1&bq=jSkill:(HTML)^2&bq=jCID:(41449)^8&bq=jJT:(Developer+)^8&bq=jLoc:(Mumbai-Thane+)^4&bq=jINDT:("IT(Software,+Dotcom,+Infra.Mgmt.%26+UI+Design)")^1

OR you can better understand it from below..

&mm=1
&qf=text

&wt=json

&hl=true

&rows=50

&fl=*+score

&start=0

&q=*:*

&fq=jSFunT:("Fresher"+OR+"Developer+/+Programmer+/+Coder")

&fq=jNMinEx:[2+TO+*]

&fq=jNMaxEx:[2+TO+5]

&fq=jNMinSal:[-1+TO+*]

&fq=jNMaxSal:[-1+TO+-1]

&bq=jSFunT:("Developer+/+Programmer+/+Coder")^1

&bq=jSkill:(HTML)^2

&bq=jCID:(41449)^8

&bq=jJT:(Java Developer)^8

&bq=jLoc:(Mumbai-Thane)^4

&bq=jINDT:("IT(Software,+Dotcom,+Infra.Mgmt.%26+UI+Design)")^1
</code>```

Here all the "bq" will not work because the qt=dismax is not supplied if i use that then the whole query will fail

can i any one help me out i will be very thankful for this kindness

答:
Have a look at the q.alt parameter, which lets you specify a fall back query:

```<code>q.alt=*:*
</code>```

If you replace your q parameter with that one, dismax should play just fine.

ContentLicense: CC BY-SA 3.0

Body:
Hi
   i am trying to make a solr Query using dismax handler but i have no q parameters because i have to match directly on fields..

hl.fragsize=200&mm=1&facet=on&facet.mincount=1&qf=text+&wt=json&hl=true&rows=50&fl=*+score&start=0&q=*:*&fq=jSFunT:("Fresher"+OR+"Developer+/+Programmer+/+Coder")&fq=jNMinEx:[2+TO+*]&fq=jNMaxEx:[2+TO+5]&fq=jNMinSal:[-1+TO+*]&fq=jNMaxSal:[-1+TO+-1]&bq=jSFunT:("Developer+/+Programmer+/+Coder")^1&bq=jSkill:(HTML)^2&bq=jCID:(41449)^8&bq=jJT:(Developer+)^8&bq=jLoc:(Mumbai-Thane+)^4&bq=jINDT:("IT(Software,+Dotcom,+Infra.Mgmt.%26+UI+Design)")^1

OR you can better understand it from below..

&mm=1
&qf=text

&wt=json

&hl=true

&rows=50

&fl=*+score

&start=0

&q=*:*

&fq=jSFunT:("Fresher"+OR+"Developer+/+Programmer+/+Coder")

&fq=jNMinEx:[2+TO+*]

&fq=jNMaxEx:[2+TO+5]

&fq=jNMinSal:[-1+TO+*]

&fq=jNMaxSal:[-1+TO+-1]

&bq=jSFunT:("Developer+/+Programmer+/+Coder")^1

&bq=jSkill:(HTML)^2

&bq=jCID:(41449)^8

&bq=jJT:(Java Developer)^8

&bq=jLoc:(Mumbai-Thane)^4

&bq=jINDT:("IT(Software,+Dotcom,+Infra.Mgmt.%26+UI+Design)")^1

Here all the "bq" will not work because the qt=dismax is not supplied if i use that then the whole query will fail

can i any one help me out i will be very thankful for this kindness

Body:
Have a look at the q.alt parameter, which lets you specify a fall back query:

q.alt=*:*

If you replace your q parameter with that one, dismax should play just fine.


问:
Calculating column row based on 2 rows in another column
I want to calculate difference between 2 rows in a column to a new column

```<code>(Y(A1)/X(A1))-(Y(A1)/X(A1))/(Y(A1)/X(A1))*100% (3/52-1/41)/(1/41)*100% = 57.72%
</code>```

The attached code is working but the last row is dropped for some reason

```<code>c = c.rename(lambda x: (x)*2+1)
c = c.map('{:,.2f}%'.format)
df['Z']=c
</code>```

Expected result:

```<code>    X   Y   Z
A1  41  1
A2  52  3   57.72%
B1  74  6
B2  74  4   -50.00%
C1  5   0
C2  5   0   nan%
D1  120 7
D2  131 7   -9.17%
</code>```

What I actually get:

```<code>    X   Y   Z
A1  41  1
A2  52  3   57.72%
B1  74  6
B2  74  4   -50.00%
C1  5   0
C2  5   0   nan%
D1  120 7
D2  131 7
</code>```

答:
Use GroupBy.pct_change by groups for each 2 rows created by integer division of 1d array created by numpy.arange:

```<code>print (np.arange(len(df)) // 2)
[0 0 1 1 2 2 3 3]

df['Z1'] = df['X'].div(df['Y']).groupby(np.arange(len(df)) // 2).pct_change().mul(-100)
print (df)

      X  Y        Z         Z1
A1   41  1      NaN        NaN
A2   52  3   57.72%  57.723577
B1   74  6      NaN        NaN
B2   74  4  -50.00% -50.000000
C1    5  0      NaN        NaN
C2    5  0     nan%        NaN
D1  120  7      NaN        NaN
D2  131  7   -9.17%  -9.166667
</code>```

Another solution:

```<code>s1 = df['X'].div(df['Y'])
df['Z1'] = (1-s1[1::2] / s1[::2].values).mul(100)
print (df)

      X  Y        Z         Z1
A1   41  1      NaN        NaN
A2   52  3   57.72%  57.723577
B1   74  6      NaN        NaN
B2   74  4  -50.00% -50.000000
C1    5  0      NaN        NaN
C2    5  0     nan%        NaN
D1  120  7      NaN        NaN
D2  131  7   -9.17%  -9.166667
</code>```

If need missing values for non matched values use map with if-else for avoid convert missing values to strings:

```<code>s = df['X'].div(df['Y']).groupby(np.arange(len(df)) // 2).pct_change().mul(-100)
df['Z1'] = s.map(lambda x: '{:,.2f}%'.format(x) if x == x else np.nan)
print (df)

      X  Y        Z       Z1
A1   41  1      NaN      NaN
A2   52  3   57.72%   57.72%
B1   74  6      NaN      NaN
B2   74  4  -50.00%  -50.00%
C1    5  0      NaN      NaN
C2    5  0     nan%      NaN
D1  120  7      NaN      NaN
D2  131  7   -9.17%   -9.17%
</code>```

Body:
I want to calculate difference between 2 rows in a column to a new column

(Y(A1)/X(A1))-(Y(A1)/X(A1))/(Y(A1)/X(A1))*100% (3/52-1/41)/(1/41)*100% = 57.72%

The attached code is working but the last row is dropped for some reason

c = c.rename(lambda x: (x)*2+1)
c = c.map('{:,.2f}%'.format)
df['Z']=c

Expected result:

    X   Y   Z
A1  41  1
A2  52  3   57.72%
B1  74  6
B2  74  4   -50.00%
C1  5   0
C2  5   0   nan%
D1  120 7
D2  131 7   -9.17%

What I actually get:

    X   Y   Z
A1  41  1
A2  52  3   57.72%
B1  74  6
B2  74  4   -50.00%
C1  5   0
C2  5   0   nan%
D1  120 7
D2  131 7

Body:
Use GroupBy.pct_change by groups for each 2 rows created by integer division of 1d array created by numpy.arange:

print (np.arange(len(df)) // 2)
[0 0 1 1 2 2 3 3]

df['Z1'] = df['X'].div(df['Y']).groupby(np.arange(len(df)) // 2).pct_change().mul(-100)
print (df)

      X  Y        Z         Z1
A1   41  1      NaN        NaN
A2   52  3   57.72%  57.723577
B1   74  6      NaN        NaN
B2   74  4  -50.00% -50.000000
C1    5  0      NaN        NaN
C2    5  0     nan%        NaN
D1  120  7      NaN        NaN
D2  131  7   -9.17%  -9.166667

Another solution:

s1 = df['X'].div(df['Y'])
df['Z1'] = (1-s1[1::2] / s1[::2].values).mul(100)
print (df)

      X  Y        Z         Z1
A1   41  1      NaN        NaN
A2   52  3   57.72%  57.723577
B1   74  6      NaN        NaN
B2   74  4  -50.00% -50.000000
C1    5  0      NaN        NaN
C2    5  0     nan%        NaN
D1  120  7      NaN        NaN
D2  131  7   -9.17%  -9.166667

If need missing values for non matched values use map with if-else for avoid convert missing values to strings:

s = df['X'].div(df['Y']).groupby(np.arange(len(df)) // 2).pct_change().mul(-100)
df['Z1'] = s.map(lambda x: '{:,.2f}%'.format(x) if x == x else np.nan)
print (df)

      X  Y        Z       Z1
A1   41  1      NaN      NaN
A2   52  3   57.72%   57.72%
B1   74  6      NaN      NaN
B2   74  4  -50.00%  -50.00%
C1    5  0      NaN      NaN
C2    5  0     nan%      NaN
D1  120  7      NaN      NaN
D2  131  7   -9.17%   -9.17%


问:
How to trigger ripple effect on Android Lollipop, in specific location within the view, without triggering touches events?
This is a short question:

Suppose I have a View with the RippleDrawable as background.

Is there an easy way to trigger the ripple from a specific position without triggering any touch or click events?

答:
I used the following Kotlin variant of Luke's code to manually show and hide a ripple when swiping cells out of a RecyclerView:</p>

```<code>fun View.showRipple() {
    if (Build.VERSION.SDK_INT >= 21 && background is RippleDrawable) {
        background.state = intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled)
    }
}

fun View.hideRipple() {
    if (Build.VERSION.SDK_INT >= 21 && background is RippleDrawable) {
        background.state = intArrayOf()
    }
}
</code>```

Body:
I used the following Kotlin variant of Luke's code to manually show and hide a ripple when swiping cells out of a RecyclerView:

fun View.showRipple() {
    if (Build.VERSION.SDK_INT >= 21 && background is RippleDrawable) {
        background.state = intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled)
    }
}

fun View.hideRipple() {
    if (Build.VERSION.SDK_INT >= 21 && background is RippleDrawable) {
        background.state = intArrayOf()
    }
}


问:
DLL error when importing tensorflow in anaconda environment
I have installed tensorflow in the anaconda environment. I have installed the latest anaconda and tensorflow by "conda install tensorflow-gpu". When I try to import tensorflow it works in the jupyter notebook. But the same code does run when I try to run from python terminal or when I run by "start debugging" from vs code. This is the error I am getting:

```<code>    Traceback (most recent call last):
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 410, in main
    run()
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 291, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\Projects\SASRec\SASRec Pytorch\main.py", line 7, in <module>
    import tensorflow as tf
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.
</code>```

Can anyone kindly give me a solution and make my life easier. Thanks!

答:
You probably already had some version of python installed (e.g. 3.6.6) before installing Anaconda with Python 3.7 and prepared it to use TensorFlow.
Because Anaconda comes with its own instance of Python you have installed the TensorFlow dependencies into the Anaconda instance of Python.

When you use the console, you most likely use your non-Anaconda-Python instance, which does not have TensorFlow with all its dependencies installed.

You can either install the missing dependencies for your non-Anaconda-Python or start the script with the Anaconda version of Python. You can do the later by calling python using the full path like /path/to/anaconda/bin/python yourscriptusingtensorflow.py or prepending the anaconda binary path to your console's $PATH variable.

Body:
I have installed tensorflow in the anaconda environment. I have installed the latest anaconda and tensorflow by "conda install tensorflow-gpu". When I try to import tensorflow it works in the jupyter notebook. But the same code does run when I try to run from python terminal or when I run by "start debugging" from vs code. This is the error I am getting:

    Traceback (most recent call last):
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 410, in main
    run()
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 291, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\Projects\SASRec\SASRec Pytorch\main.py", line 7, in <module>
    import tensorflow as tf
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Can anyone kindly give me a solution and make my life easier. Thanks!


答:
I didn't get the main reason for your problem. But I noticed one thing, GPU-Util 100%, while there are no processes running behind.

You can try out in the following directions.

sudo nvidia-smi -pm 1

which enables in persistence mode. This might solve your problem. The combination of ECC with non persistence mode can lead to 100% Utilization of GPU.

You can also disable ECC with the command nvidia -smi -e 0

Or best will be restart once again the whole process from the starting i.e reboot the Operating System once again.

Note: I'm not sure whether it will work for you or not. I had faced similar issue earlier so I am just telling based on my experience.
Hope this will help you.

Title: Pytorch: no CUDA-capable device is detected on Linux

Body:
When trying to run some Pytorch code I get this error:

THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=74 error=38 : no CUDA-capable device is detected
Traceback (most recent call last):
File "demo.py", line 173, in test
pca = torch.FloatTensor( np.load('../basics/U_lrw1.npy')[:,:6]).cuda()
RuntimeError: cuda runtime error (38) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:74

I a running a cloud virtual machine using the 'Google Deep Learning VM'
Version: tf-gpu.1-13.m25
Based on: Debian GNU/Linux 9.9 (stretch) (GNU/Linux 4.9.0-9-amd64 x86_64\n)
Linux tf-gpu-interruptible 4.9.0-9-amd64 #1 SMP Debian 4.9.168-1 (2019-04-12) x86_64

Environment info:

$ nvidia-smi
Sun May 26 05:32:33 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 410.72       Driver Version: 410.72       CUDA Version: 10.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           Off  | 00000000:00:04.0 Off |                    0 |
| N/A   42C    P0    74W / 149W |      0MiB / 11441MiB |    100%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

 $ echo $CUDA_PATH

 $ echo $LD_LIBRARY_PATH
/usr/local/cuda/lib64:/usr/local/nccl2/lib:/usr/local/cuda/extras/CUPTI/lib64

$ env | grep CUDA
CUDA_VISIBLE_DEVICES=0

$ pip freeze
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.
7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
audioread==2.1.7
backports.functools-lru-cache==1.5
certifi==2019.3.9
chardet==3.0.4
cloudpickle==1.1.1
cycler==0.10.0
dask==1.2.2
decorator==4.4.0
dlib==19.17.0
enum34==1.1.6
filelock==3.0.12
funcsigs==1.0.2
future==0.17.1
gdown==3.8.1
idna==2.8
joblib==0.13.2
kiwisolver==1.1.0
librosa==0.6.3
llvmlite==0.28.0


问:
How to pass value in input tag?
normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response">```

```

Thanks.

答:
You are trying to set input value using .html(). Which is not supported in jquery. You need to use .val() to set input value. Here is the explanation for the same.

Try this:

<!DOCTYPE html>

    <title>Get browser and ip address </title>

ipdata.co - IP geolocation API

<input type="text" name="country_name" id="country_name" value="">

```

<script>

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.country_name + ", " + response.region);
    $("#country_name").val(response.country_name);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");

</script>

</body>
</html></code>```

Title: How to pass value in input tag?

Body:
normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

<!DOCTYPE html>

    <title>Get browser and ip address </title>

ipdata.co - IP geolocation API

<input type="text" name="country_name" id="country_name" value="">

Thanks.

Body:
You are trying to set input value using .html(). Which is not supported in jquery. You need to use .val() to set input value. Here is the explanation for the same.

Try this:

<!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>

<script>

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#city").html(response.country_name + ", " + response.region);
    $("#country_name").val(response.country_name);
    $("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");

</script>

</body>
</html>


问:
Azure Access Control for Resource Groups
I have a Subscription in my company that is shared for all members of the team (all employees).
We use this subscription for test, dev and also production workloads.
We have only one subscription because it is a sponsored subscription thanks to our MS partnership, so we don't want to create other subscriptions.

I want to restrict the access to a particular resource group that will host production resources where sensible data will be managed.
Because all members of the teams are contributor in the subscription level, they have access to all resource group and I can't remove them from the resource group.
So how can I proceed if I want to revoke their access to the resource group and allow them to use all other resource groups?

答:
So how can I proceed if I want to revoke their access to the resource
  group and allow them to use all other resource groups?

AFAIK, Only way to do so is remove the users role (Contributor) at the subscription level and assign them at each resource group (other than production resource group). If a user has a higher role (say Contributor) at subscription level, then you can't assign a lower role (say Reader) at resource group level.

Essentially with Azure RBAC, when you grant access at a parent scope, those permissions are inherited to the child scopes.

You can read more about Azure RBAC here: https://learn.microsoft.com/en-us/azure/role-based-access-control/overview#how-rbac-works.


问:
Dynamic Navigation bar (with images) with jquery and php - problems with mouseover effects
I'm building a dynamic navigation bar which is controlled by PHP, and I'm using images within my list. And I'm applying jQuery for the 'hover' effects. This is the PHP code:

```<code>$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');
</code>```

And in my navigation list I'm setting 'display:none' and 'display:inline' depending on the return value of $page using a PHP 'if' statement. See code:

```<code><ul id="cssdropdown">
  <li class="headlink">
  <a class="lightNav" href="index.php"  <?php if($page == 'index'){echo "style='display:none !important'";}else{echo "style='display:inline'";}?>><img src="images/navButtons/home.png" /></a>
  <a class="darkNav" href="index.php" <?php if($page == 'index'){echo "style='display:inline !important'";}else{echo "style='display:none'";}?>><img src="images/navButtons/home-dark.png" /></a>
  </li>....
</code>```

This is all working fine, the display of the Nav bar images change depending on what page the user is at. But my problem is now I'm trying to integrate jQuery to get a nice 'mouseover / hover' effect. See jQuery code:

```<code>$("li.headlink").hover(function(){
  $(this).find("a.lightNav").css("display", "none");
  $(this).find("a.darkNav").css("display", "inline");
},function(){
  $(this).find("a.lightNav").css("display", "inline");
  $(this).find("a.darkNav").css("display", "none");
});
</code>```

But this is causing problems. When the user moves the cursor over the image in the Nav bar for the current page (ie the 'dark' image), it removes the display attribute set by PHP (obviously).

So I need a way to check on mouseover if 'darkNav' has display 'inline' or 'none' and tailor my jQuery from there, but for the life of me I cannot figure out how to do, I'm not the worlds greatest javascript/jQuery coder. Is there a way to check if an element has a particular CSS property applied to it, I googled and fiddled with my code for hours, but to no avail.

Thanks in advance everyone.

P.S. I added the CSS !important in my nav bar within the PHP if statement, but this for some strange reason, is only working in Chrome, all other browsers are ignoring this rule.

答:
"So I need a way to check on mouseover if 'darkNav' has display 'inline' or 'none'.."

This is untested but you could try something like...

```<code>
   if ($(this).attr('style') == "display:none") {
     // do something
   }
   else if ($(this).attr('style') == "display:inline") {
     // do something
   }
</code>```

However, you may want to try addClass() and removeClass() instead of changing and/or using inline CSS.

Body:
I'm building a dynamic navigation bar which is controlled by PHP, and I'm using images within my list. And I'm applying jQuery for the 'hover' effects. This is the PHP code:

$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');

And in my navigation list I'm setting 'display:none' and 'display:inline' depending on the return value of $page using a PHP 'if' statement. See code:

  <a class="lightNav" href="index.php"  <?php if($page == 'index'){echo "style='display:none !important'";}else{echo "style='display:inline'";}?>>
  <a class="darkNav" href="index.php" <?php if($page == 'index'){echo "style='display:inline !important'";}else{echo "style='display:none'";}?>>

....

This is all working fine, the display of the Nav bar images change depending on what page the user is at. But my problem is now I'm trying to integrate jQuery to get a nice 'mouseover / hover' effect. See jQuery code:

$("li.headlink").hover(function(){
  $(this).find("a.lightNav").css("display", "none");
  $(this).find("a.darkNav").css("display", "inline");
},function(){
  $(this).find("a.lightNav").css("display", "inline");
  $(this).find("a.darkNav").css("display", "none");
});

But this is causing problems. When the user moves the cursor over the image in the Nav bar for the current page (ie the 'dark' image), it removes the display attribute set by PHP (obviously).

So I need a way to check on mouseover if 'darkNav' has display 'inline' or 'none' and tailor my jQuery from there, but for the life of me I cannot figure out how to do, I'm not the worlds greatest javascript/jQuery coder. Is there a way to check if an element has a particular CSS property applied to it, I googled and fiddled with my code for hours, but to no avail.

Thanks in advance everyone.

P.S. I added the CSS !important in my nav bar within the PHP if statement, but this for some strange reason, is only working in Chrome, all other browsers are ignoring this rule.

Body:
"So I need a way to check on mouseover if 'darkNav' has display 'inline' or 'none'.."

This is untested but you could try something like...

   if ($(this).attr('style') == "display:none") {
     // do something
   }
   else if ($(this).attr('style') == "display:inline") {
     // do something
   }

However, you may want to try addClass() and removeClass() instead of changing and/or using inline CSS.


问:
Understanding data cache locality in mips code
I have been browsing stackoverflow could not really find a example regarding to this one. I understand the concept of Temporal and Spatial locality for data cache:

Temporarl locality: address revisited

Spatial locality: every x times memory access get a hit

But how does it look like in the mips code? Can anyone give concrete examples and show how it works?

答:
Spatial and temporal localities are not related to a specific architecture, mips or another one. It is more a property of programs and on the way they are processed on a computer.

Temporal locality states that if you access a given memory location, it is very likely that the same location will be accessed a few time after.

Difficult to give a specific example, but the idea is that if, for instance, you modify a variable, there is a high probability that this variable will be used a few instructions after in the program. Of course, it is possible to find counter-examples, but most of the time when a computation is done and stored in a variable, it is because we will need later the result of this operation.

The definition that you give of spatial locality is incorrect. Spatial locality states that if an information in some memory location is required, it is very likely that other informations located in a nearby memory location will also be required some time after.

This property is due the fact that many constructs of programming languages correspond to data stored in consecutive memory locations. This includes :

elements of an array

fields of a struct

local variables that are in successive addresses in the stack

parameter of a function that are also close in the stack

Again, it is possible to find counter-examples, but if, for instance, one accesses the firt character of a string, it is probably to do some kind of computation, search or whatever on the string, and most of the time, the other chars of the string will also be accessed.