问:
correcting the select options in html using Angularjs
HTML page

```<code><!DOCTYPE html>
<html lang="en" ng-app="confusionApp">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ristorante Con Fusion: Contact Us</title>
    <!-- Bootstrap -->
    <!-- build:css styles/main.css -->
    <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-social.css" rel="stylesheet">
    <link href="styles/mystyles.css" rel="stylesheet">
    <!-- endbuild -->
</head>

<body>

    <div class="container" ng-controller="ContactController">
        <div class="row">
            <div class="col-xs-12">
                <ul class="breadcrumb">
                    <li>
                        <a href="#">Home</a>
                    </li>
                    <li class="active">Contact Us</li>
                </ul>
            </div>
            <div class="col-xs-12">
                <h3>Contact Us</h3>
                <hr>
            </div>
        </div>

        <div class="row row-content">
            <div class="col-xs-12">
                <h3>Location Information</h3>
            </div>
            <div class="col-xs-12 col-sm-4 col-sm-offset-1">
                <h5>Our Address</h5>
                <address style="font-size: 100%">
                    121, Clear Water Bay Road
                    <br> Clear Water Bay, Kowloon
                    <br> HONG KONG
                    <br>
                    <i class="fa fa-phone"></i>: +852 1234 5678
                    <br>
                    <i class="fa fa-fax"></i>: +852 8765 4321
                    <br>
                    <i class="fa fa-envelope"></i>:
                    <a href="mailto:confusion@food.net">confusion@food.net</a>
                </address>
            </div>
            <div class="col-xs-12 col-sm-6 col-sm-offset-1">
                <h5>Map of our Location</h5>
            </div>
            <div class="col-xs-12 col-sm-11 col-sm-offset-1">
                <div class="btn-group" role="group" aria-label="...">
                    <a type="button" class="btn btn-primary" href="tel:+85212345678">
                        <i class="fa fa-phone"></i> Call</a>
                    <a type="button" class="btn btn-info">
                        <i class="fa fa-skype"></i> Skype</a>
                    <a type="button" class="btn btn-success" href="mailto:confusion@food.net">
                        <i class="fa fa-envelope-o"></i> Email</a>
                </div>
            </div>
        </div>

        <div class="row row-content">
            <div class="col-xs-12">
                <h3>Send us your Feedback</h3>
            </div>
            <div class="col-xs-12 col-sm-9" ng-controller="FeedbackController">
                <form class="form-horizontal" name="feedbackForm" ng-submit="sendFeedback()" novalidate>
                    <div class="form-group" ng-class="{ 'has-error' : feedbackForm.firstname.$error.required && !feedbackForm.firstname.$pristine }">
                        <label for="firstname" class="col-sm-2 control-label">First Name</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="firstname" name="firstname" placeholder="Enter First Name" ng-model="feedback.firstName"
                                required>
                            <span ng-show="feedbackForm.firstname.$error.required && !feedbackForm.firstname.$pristine" class="help-block">Your First name is required.</span>
                        </div>
                    </div>
                    <div class="form-group" ng-class="{ 'has-error' : feedbackForm.lastname.$error.required && !feedbackForm.lastname.$pristine }">
                        <label for="lastname" class="col-sm-2 control-label">Last Name</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Enter Last Name" ng-model="feedback.lastName"
                                required>
                            <span ng-show="feedbackForm.lastname.$error.required && !feedbackForm.lastname.$pristine" class="help-block">Your Last name is required.</span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="telnum" class="col-sm-2 control-label">Contact Tel.</label>
                        <div class="col-xs-5 col-sm-4 col-md-3">
                            <div class="input-group">
                                <div class="input-group-addon">(</div>
                                <input type="tel" class="form-control" placeholder="Area code" ng-model="feedback.tel.areaCode">
                                <div class="input-group-addon">)</div>
                            </div>
                        </div>
                        <div class="col-xs-7 col-sm-6 col-md-7">
                            <input type="tel" class="form-control" id="telnum" name="telnum" placeholder="Tel. number" ng-model="feedback.tel.number">
                        </div>
                    </div>
                    <div class="form-group" ng-class="{ 'has-error has-feedback' : feedbackForm.emailid.$invalid && !feedbackForm.emailid.$pristine }">
                        <label for="emailid" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                            <input type="email" class="form-control" id="emailid" name="emailid" placeholder="Email" ng-model="feedback.email" required>
                            <span ng-show="feedbackForm.emailid.$invalid && !feedbackForm.emailid.$pristine" class="glyphicon glyphicon-remove form-control-feedback"
                                aria-hidden="true"></span>
                            <span ng-show="(feedbackForm.emailid.$invalid ||
                                            feedbackForm.emailid.$error.required) &&
                                            !feedbackForm.emailid.$pristine" class="help-block">Enter a valid email address.</span>
                        </div>
                    </div>
                    <div class="form-group" ng-class="{ 'has-error' : invalidChannelSelection }">
                        <div class="checkbox col-sm-5 col-sm-offset-2">
                            <label class="checkbox-inline">
                                <input type="checkbox" ng-model="feedback.agree">
                                <strong>May we contact you?</strong>
                            </label>
                        </div>
                        <div class="col-sm-3 col-sm-offset-1" ng-show="feedback.agree">
                            <select class="form-control" ng-model="feedback.mychannel" ng-options="channel.value as channel.label for channel in channels">
                                <option value="">Tel. or Email?</option>
                            </select>
                            <span ng-show="invalidChannelSelection" class="help-block">Select an option.</span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="feedback" class="col-sm-2 control-label">Your Feedback</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" rows="12" ng-model="feedback.comments">
                            </textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary" ng-disabled="feedbackForm.$invalid">Send Feedback</button>
                        </div>
                    </div>
                </form>
            </div>

            <div class="col-xs-12 col-sm-3">
                <h3>Your Current Feedback:</h3>
                <p>{{feedback.firstName}} {{feedback.lastName | uppercase }}</p>
                <p>Contact Tel.: ({{feedback.tel.areaCode}}) {{feedback.tel.number}}</p>
                <p>Contact Email: {{feedback.email}}</p>
                <p ng-show="feedback.agree">Contact by: {{feedback.mychannel}}</p>
                <p>Comments: {{feedback.comments}}</p>
            </div>

        </div>

    </div>

    <!-- build:js scripts/main.js -->
    <script src="../bower_components/angular/angular.min.js"></script>
    <script src="scripts/app.js"></script>
    <!-- endbuild -->

</body>

</html>
</code>```

app.js file

```<code>'use strict';
angular.module('confusionApp', [])
    .controller('MenuController', ['$scope', function ($scope) {
        $scope.tab = 1;
        $scope.filtText = '';
        $scope.showDetails = false;

        $scope.dishes = [{
                name: 'Uthapizza',
                image: 'images/uthapizza.png',
                category: 'mains',
                label: 'Hot',
                price: '4.99',
                description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                comment: ''
            },

            {
                name: 'Zucchipakoda',
                image: 'images/zucchipakoda.png',
                category: 'appetizer',
                label: '',
                price: '1.99',
                description: 'Deep fried Zucchini coated with mildly spiced Chickpea flour batter accompanied with a sweet-tangy tamarind sauce',
                comment: ''
            },

            {
                name: 'Vadonut',
                image: 'images/vadonut.png',
                category: 'appetizer',
                label: 'New',
                price: '1.99',
                description: 'A quintessential ConFusion experience, is it a vada or is it a donut?',
                comment: ''
            },

            {
                name: 'ElaiCheese Cake',
                image: 'images/elaicheesecake.png',
                category: 'dessert',
                label: '',
                price: '2.99',
                description: 'A delectable, semi-sweet New York Style Cheese Cake, with Graham cracker crust and spiced with Indian cardamoms',
                comment: ''
            }
        ];

        $scope.select = function (setTab) {
            $scope.tab = setTab;

            if (setTab === 2) {
                $scope.filtText = "appetizer";
            } else if (setTab === 3) {
                $scope.filtText = "mains";
            } else if (setTab === 4) {
                $scope.filtText = "dessert";
            } else {
                $scope.filtText = "";
            }
        };

        $scope.isSelected = function (checkTab) {
            return ($scope.tab === checkTab);
        };
        $scope.toggleDetails = function () {
            $scope.showDetails = !$scope.showDetails;
        };
    }])
    .controller('ContactController', ['$scope', function ($scope) {

        $scope.feedback = {
            mychannel: "",
            firstName: "",
            lastName: "",
            agree: false,
            email: ""
        };
        var channels = [{
            value: "tel",
            label: "Tel."
        }, {
            value: "Email",
            label: "Email"
        }];
        $scope.channels = channels;
        $scope.invalidChannelSelection = false;
    }])

    .controller('FeedbackController', ['$scope', function ($scope) {
        $scope.sendFeedback = function () {
            console.log($scope.feedback);
            if ($scope.feedback.agree && ($scope.feedback.mychannel === "") && !$scope.feedback.mychannel) {
                $scope.invalidChannelSelection = true;
                console.log('incorrect');
            } else {
                $scope.invalidChannelSelection = false;
                $scope.feedback = {
                    mychannel: "",
                    firstName: "",
                    lastName: "",
                    agree: false,
                    email: ""
                };
                $scope.feedback.mychannel = "";

                $scope.feedbackForm.$setPristine();
                console.log($scope.feedback);
            }
        };

    }]);
</code>```

Please help with the code correction. I see an extra empty option in the HTML web application when I check the checkbox "may we contact you?". Instead, I need to get only 3 options without the first option which is empty. Please solve the issue. Thank you in advance.

This is the output which I got
This should be the actual output

答:
Change

```<code> <select class="form-control" ng-model="feedback.mychannel" ng-options="channel.value as channel.label for channel in channels">
                                <option value="">Tel. or Email?</option>
                            </select>
</code>```

To

```<code> <select class="form-control" ng-model="feedback.mychannel" ng-options="channel.value as channel.label for channel in channels" ng-init="feedback.mychannel =channels[0].value">
                            </select>
</code>```

and set channels like

```<code> $scope.channels = [{
            value: "",
            label: "Tel. or Email"
        },{
            value: "tel",
            label: "Tel."
        }, {
            value: "Email",
            label: "Email"
        }];
</code>```

Check this fiddle

Body:
HTML page

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ristorante Con Fusion: Contact Us</title>

    <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-social.css" rel="stylesheet">
    <link href="styles/mystyles.css" rel="stylesheet">

                        Home

Contact Us

Contact Us

Location Information

Our Address

                <address style="font-size: 100%">
                    121, Clear Water Bay Road

 Clear Water Bay, Kowloon

 HONG KONG

                    : +852 1234 5678

                    : +852 8765 4321

                    :
                    confusion@food.net
                </address>

Map of our Location

                         Call

                         Skype

                         Email

Send us your Feedback

                <form class="form-horizontal" name="feedbackForm" ng-submit="sendFeedback()" novalidate>

                        First Name

                            <input type="text" class="form-control" id="firstname" name="firstname" placeholder="Enter First Name" ng-model="feedback.firstName"
                                required>
                            Your First name is required.

                        Last Name

                            <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Enter Last Name" ng-model="feedback.lastName"
                                required>
                            Your Last name is required.

                        Contact Tel.

(

                                <input type="tel" class="form-control" placeholder="Area code" ng-model="feedback.tel.areaCode">

)

                            <input type="tel" class="form-control" id="telnum" name="telnum" placeholder="Tel. number" ng-model="feedback.tel.number">

                        Email

                            <input type="email" class="form-control" id="emailid" name="emailid" placeholder="Email" ng-model="feedback.email" required>

                            Enter a valid email address.

                                <input type="checkbox" ng-model="feedback.agree">
                                May we contact you?

                            <select class="form-control" ng-model="feedback.mychannel" ng-options="channel.value as channel.label for channel in channels">
                                <option value="">Tel. or Email?</option>
                            </select>
                            Select an option.

                        Your Feedback

                            <textarea class="form-control" rows="12" ng-model="feedback.comments">
                            </textarea>

                            <button type="submit" class="btn btn-primary" ng-disabled="feedbackForm.$invalid">Send Feedback</button>

                </form>

Your Current Feedback:

{{feedback.firstName}} {{feedback.lastName | uppercase }}

Contact Tel.: ({{feedback.tel.areaCode}}) {{feedback.tel.number}}

Contact Email: {{feedback.email}}

Contact by: {{feedback.mychannel}}

Comments: {{feedback.comments}}

app.js file

'use strict';
angular.module('confusionApp', [])
    .controller('MenuController', ['$scope', function ($scope) {
        $scope.tab = 1;
        $scope.filtText = '';
        $scope.showDetails = false;

        $scope.dishes = [{
                name: 'Uthapizza',
                image: 'images/uthapizza.png',
                category: 'mains',
                label: 'Hot',
                price: '4.99',
                description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                comment: ''
            },

            {
                name: 'Zucchipakoda',
                image: 'images/zucchipakoda.png',
                category: 'appetizer',
                label: '',
                price: '1.99',
                description: 'Deep fried Zucchini coated with mildly spiced Chickpea flour batter accompanied with a sweet-tangy tamarind sauce',
                comment: ''
            },

            {
                name: 'Vadonut',
                image: 'images/vadonut.png',
                category: 'appetizer',
                label: 'New',
                price: '1.99',
                description: 'A quintessential ConFusion experience, is it a vada or is it a donut?',
                comment: ''
            },

            {
                name: 'ElaiCheese Cake',
                image: 'images/elaicheesecake.png',
                category: 'dessert',
                label: '',
                price: '2.99',
                description: 'A delectable, semi-sweet New York Style Cheese Cake, with Graham cracker crust and spiced with Indian cardamoms',
                comment: ''
            }
        ];

        $scope.select = function (setTab) {
            $scope.tab = setTab;

            if (setTab === 2) {
                $scope.filtText = "appetizer";
            } else if (setTab === 3) {
                $scope.filtText = "mains";
            } else if (setTab === 4) {
                $scope.filtText = "dessert";
            } else {
                $scope.filtText = "";
            }
        };

        $scope.isSelected = function (checkTab) {
            return ($scope.tab === checkTab);
        };
        $scope.toggleDetails = function () {
            $scope.showDetails = !$scope.showDetails;
        };
    }])
    .controller('ContactController', ['$scope', function ($scope) {

        $scope.feedback = {
            mychannel: "",
            firstName: "",
            lastName: "",
            agree: false,
            email: ""
        };
        var channels = [{
            value: "tel",
            label: "Tel."
        }, {
            value: "Email",
            label: "Email"
        }];
        $scope.channels = channels;
        $scope.invalidChannelSelection = false;
    }])

    .controller('FeedbackController', ['$scope', function ($scope) {
        $scope.sendFeedback = function () {
            console.log($scope.feedback);
            if ($scope.feedback.agree && ($scope.feedback.mychannel === "") && !$scope.feedback.mychannel) {
                $scope.invalidChannelSelection = true;
                console.log('incorrect');
            } else {
                $scope.invalidChannelSelection = false;
                $scope.feedback = {
                    mychannel: "",
                    firstName: "",
                    lastName: "",
                    agree: false,
                    email: ""
                };
                $scope.feedback.mychannel = "";

                $scope.feedbackForm.$setPristine();
                console.log($scope.feedback);
            }
        };

    }]);

Please help with the code correction. I see an extra empty option in the HTML web application when I check the checkbox "may we contact you?". Instead, I need to get only 3 options without the first option which is empty. Please solve the issue. Thank you in advance.

This is the output which I got
This should be the actual output

Body:
Change

 <select class="form-control" ng-model="feedback.mychannel" ng-options="channel.value as channel.label for channel in channels">
                                <option value="">Tel. or Email?</option>
                            </select>

To

 <select class="form-control" ng-model="feedback.mychannel" ng-options="channel.value as channel.label for channel in channels" ng-init="feedback.mychannel =channels[0].value">
                            </select>

and set channels like

 $scope.channels = [{
            value: "",
            label: "Tel. or Email"
        },{
            value: "tel",
            label: "Tel."
        }, {
            value: "Email",
            label: "Email"
        }];

Check this fiddle


来源: stackexchange

问:
Upload file using HTML  control without file selection dialog
I want upload the file using HTML file control but without selection dialog since i have to upload file which has fixed path "c:\finsts\finstmt.xml".

Scenario 1:

I have tried to upload file using HTML control . In which it shows browse button and on click you have to select file from file chooser dialog box. It works. Its upload file to server fine. Server side code is correct and works fine.

Scenario 2:

But when I hide the file chooser control, with following HTML code:

```<code> <div name="filediv" style="display:none">
  <html type="file" id="uploadfile" value="c:\finsts\finstmt.xml">
 </div>
</code>```

As file path is fixed and I don't want to user select file. When I tried with this scenario it doesn't work while first works fine. I don't understood how file control works.

Anyone here knows any work around to work the second scenario?

Thanks.

答:
This is not possible for security reasons. There is no workaround.

It used to be possible using a Flash-based uploader, but even Flash requires an explicit user file selection now for the same reasons.

You may have a chance using a Java applet or a proprietary VBScript that works in Internet Explorer only (and requires the site to be in the trusted zone), but it's going to be complex.

ContentLicense: CC BY-SA 2.5

Title: Upload file using HTML <html type="file" id="uploadfile"> control without file selection dialog

Body:
I want upload the file using HTML file control but without selection dialog since i have to upload file which has fixed path "c:\finsts\finstmt.xml".

Scenario 1:

I have tried to upload file using HTML control . In which it shows browse button and on click you have to select file from file chooser dialog box. It works. Its upload file to server fine. Server side code is correct and works fine.

Scenario 2:

But when I hide the file chooser control, with following HTML code:

As file path is fixed and I don't want to user select file. When I tried with this scenario it doesn't work while first works fine. I don't understood how file control works.

Anyone here knows any work around to work the second scenario?

Thanks.


问:
Regex Generation Assistance
I need some hopefully easy and quick help. I am getting a string of data from a barcode and I need to splice it to obtain three different values - Account Number, Date, and Invoice Number.

The regex has to be written for .Net Framework.

An example of what the barcode will return looks like this –

```<code>000295934009000306511302017001
</code>```

The first 9 digits is the Account Number. I’ve got that figured out by using this - ^\d{9}

The next 10 digits is the Invoice Number. I am not sure what regex expression would give me that.

Then, the 8 digits following the Invoice Number is the date (in this example it is 11302017). I need to pull that and put it into a MM/DD/YYYY format.

I will be creating a named group pattern for this too.

```<code>(?<account>^\d{9})(?<date>XXXXXXX)(?<invoice>XXXXXXX) - the X's are what I need to figure out.
</code>```

Any help is greatly appreciated!

答:
This is the regex:

```<code>(\d{9})(\d{10})(\d{8})
</code>```

Self explanatory: group 1 9 digits, group 2 10 digits and group 3 8 digits.

You can use it like this:

```<code>string pattern = @"(\d{9})(\d{10})(\d{8})";
string input = @"000295934009000306511302017001";
var match = Regex.Match(input, pattern);
var accountNumber = match.Groups[1].Value;
var invoiceNumber = match.Groups[2].Value;
var date = match.Groups[3].Value;
</code>```

To get the DateTime object, use ParseExact:

```<code>DateTime.ParseExact(date, "MMddyyyy",  CultureInfo.InvariantCulture)
</code>```

Remember to add using directives for System.Text.RegularExpressions and System.Globalization!

ContentLicense: CC BY-SA 3.0

Title: Regex Generation Assistance

Body:
I need some hopefully easy and quick help. I am getting a string of data from a barcode and I need to splice it to obtain three different values - Account Number, Date, and Invoice Number.

The regex has to be written for .Net Framework.

An example of what the barcode will return looks like this –

000295934009000306511302017001

The first 9 digits is the Account Number. I’ve got that figured out by using this - ^\d{9}

The next 10 digits is the Invoice Number. I am not sure what regex expression would give me that.

Then, the 8 digits following the Invoice Number is the date (in this example it is 11302017). I need to pull that and put it into a MM/DD/YYYY format.

I will be creating a named group pattern for this too.

(?<account>^\d{9})(?<date>XXXXXXX)(?<invoice>XXXXXXX) - the X's are what I need to figure out.

Any help is greatly appreciated!

Body:
This is the regex:

(\d{9})(\d{10})(\d{8})

Self explanatory: group 1 9 digits, group 2 10 digits and group 3 8 digits.

You can use it like this:

string pattern = @"(\d{9})(\d{10})(\d{8})";
string input = @"000295934009000306511302017001";
var match = Regex.Match(input, pattern);
var accountNumber = match.Groups[1].Value;
var invoiceNumber = match.Groups[2].Value;
var date = match.Groups[3].Value;

To get the DateTime object, use ParseExact:

DateTime.ParseExact(date, "MMddyyyy",  CultureInfo.InvariantCulture)

Remember to add using directives for System.Text.RegularExpressions and System.Globalization!


问:
Python asyncio/aiohttp: ValueError: too many file descriptors in select() on Windows

Note: Future readers be aware, this question was old, formatted and programmed in a rush. The answer given may be useful, but the question and code probably not.

Hello everyone,

I'm having trouble understanding asyncio and aiohttp and making both work together. Because I don't understand what I'm doing I've run into a problem that I have no idea how to solve.

I'm using Windows 10 64 bits.

The following code returns a list of pages that do not contain "html" in the Content-Type header. It's implemented using asyncio.

```<code>import asyncio
import aiohttp

MAXitems = 30

async def getHeaders(url, session, sema):
    async with session:
        async with sema:
            try:
                async with session.head(url) as response:
                    try:
                        if "html" in response.headers["Content-Type"]:
                            return url, True
                        else:
                            return url, False
                    except:
                        return url, False
            except:
                return url, False

def check_urls_without_html(list_of_urls):
    headers_without_html = set()
    while(len(list_of_urls) != 0):
        blockurls = []
        print(len(list_of_urls))
        items = 0
        for num in range(0, len(list_of_urls)):
            if num < MAXitems:
                blockurls.append(list_of_urls[num - items])
                list_of_urls.remove(list_of_urls[num - items])
                items += 1
        loop = asyncio.get_event_loop()
        semaphoreHeaders = asyncio.Semaphore(50)
        session = aiohttp.ClientSession()
        data = loop.run_until_complete(asyncio.gather(*(getHeaders(url, session, semaphoreHeaders) for url in blockurls)))
        for header in data:
            if not header[1]:
                headers_without_html.add(header)
    return headers_without_html

list_of_urls= ['http://www.google.com', 'http://www.reddit.com']
headers_without_html =  check_urls_without_html(list_of_urls)

for header in headers_without_html:
    print(header[0])
</code>```

When I run it with too many URLs (ie 2000) sometimes it returns an error like like this one:

```<code>data = loop.run_until_complete(asyncio.gather(*(getHeaders(url, session, semaphoreHeaders) for url in blockurls)))
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 454, in run_until_complete
    self.run_forever()
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 421, in run_forever
    self._run_once()
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 1390, in _run_once
    event_list = self._selector.select(timeout)
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\selectors.py", line 323, in select
    r, w, _ = self._select(self._readers, self._writers, [], timeout)
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\selectors.py", line 314, in _select
    r, w, x = select.select(r, w, w, timeout)
ValueError: too many file descriptors in select()
</code>```

I've read that problem arises from a Windows' restriction. I've also read there is not much that can be done about it, other than trying to use less file descriptors.

I've seen people push thousands of requests with asyncio and aiohttp but even with my chuncking I can't push 30-50 without getting this error.

Is there something fundamentally wrong with my code or is it an inherent problem with Windows? Can it be fixed? Can one increase the limit on the maximum number of allowed file descriptors in select?

答:
By default Windows can use only 64 sockets in asyncio loop. This is a limitation of underlying select() API call.

To increase the limit please use ProactorEventLoop, you can use the code below. See the full docs here here.

```<code>if sys.platform == 'win32':
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)
</code>```

Another solution is to limit the overall concurrency using a sempahore, see the answer provided here. For example, when doing 2000 API calls you might want not want too many parallel open requests (they might timeout / more difficult to see the individual calling times). This will give you

```<code>await gather_with_concurrency(100, *my_coroutines)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Note: Future readers be aware, this question was old, formatted and programmed in a rush. The answer given may be useful, but the question and code probably not.

Hello everyone,

I'm having trouble understanding asyncio and aiohttp and making both work together. Because I don't understand what I'm doing I've run into a problem that I have no idea how to solve.

I'm using Windows 10 64 bits.

The following code returns a list of pages that do not contain "html" in the Content-Type header. It's implemented using asyncio.

import asyncio
import aiohttp

MAXitems = 30

async def getHeaders(url, session, sema):
    async with session:
        async with sema:
            try:
                async with session.head(url) as response:
                    try:
                        if "html" in response.headers["Content-Type"]:
                            return url, True
                        else:
                            return url, False
                    except:
                        return url, False
            except:
                return url, False

def check_urls_without_html(list_of_urls):
    headers_without_html = set()
    while(len(list_of_urls) != 0):
        blockurls = []
        print(len(list_of_urls))
        items = 0
        for num in range(0, len(list_of_urls)):
            if num < MAXitems:
                blockurls.append(list_of_urls[num - items])
                list_of_urls.remove(list_of_urls[num - items])
                items += 1
        loop = asyncio.get_event_loop()
        semaphoreHeaders = asyncio.Semaphore(50)
        session = aiohttp.ClientSession()
        data = loop.run_until_complete(asyncio.gather(*(getHeaders(url, session, semaphoreHeaders) for url in blockurls)))
        for header in data:
            if not header[1]:
                headers_without_html.add(header)
    return headers_without_html

list_of_urls= ['http://www.google.com', 'http://www.reddit.com']
headers_without_html =  check_urls_without_html(list_of_urls)

for header in headers_without_html:
    print(header[0])

When I run it with too many URLs (ie 2000) sometimes it returns an error like like this one:

data = loop.run_until_complete(asyncio.gather(*(getHeaders(url, session, semaphoreHeaders) for url in blockurls)))
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 454, in run_until_complete
    self.run_forever()
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 421, in run_forever
    self._run_once()
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 1390, in _run_once
    event_list = self._selector.select(timeout)
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\selectors.py", line 323, in select
    r, w, _ = self._select(self._readers, self._writers, [], timeout)
  File "USER\AppData\Local\Programs\Python\Python36-32\lib\selectors.py", line 314, in _select
    r, w, x = select.select(r, w, w, timeout)
ValueError: too many file descriptors in select()

I've read that problem arises from a Windows' restriction. I've also read there is not much that can be done about it, other than trying to use less file descriptors.

I've seen people push thousands of requests with asyncio and aiohttp but even with my chuncking I can't push 30-50 without getting this error.

Is there something fundamentally wrong with my code or is it an inherent problem with Windows? Can it be fixed? Can one increase the limit on the maximum number of allowed file descriptors in select?

Body:
By default Windows can use only 64 sockets in asyncio loop. This is a limitation of underlying select() API call.

To increase the limit please use ProactorEventLoop, you can use the code below. See the full docs here here.

if sys.platform == 'win32':
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)

Another solution is to limit the overall concurrency using a sempahore, see the answer provided here. For example, when doing 2000 API calls you might want not want too many parallel open requests (they might timeout / more difficult to see the individual calling times). This will give you

await gather_with_concurrency(100, *my_coroutines)


问:
Arabic font not working in IE 11?
i am facing issue for arabic font its working proper Mozilla and chrome nut not working proper in IE 11 my code is below anyone can you help me please.</p>

```<code><!DOCTYPE html>
    <html>
    <head>
        <style type="text/css">
        @font-face {
           font-family: 'ArabicTwo_Bold';
           src: url('DroidKufi-Regular.eot?#iefix') format('embedded-opentype'),

                url('ArabicSans_Bold.ttf')  format('truetype'),
                url('DroidKufi-Regular.woff') format('woff'),
                 url('DroidKufi-Regular.svg#ArabicTwo_Bold') format('svg');
        }

        div , input {
         font-family: ArabicTwo_Bold;
        }

        </style>
    </head>
    <body>
        <input type='text' value='account 1 2 3' />
        <div> account  1 2 3 </div>
    </body>
    </html>
</code>```

答:
Css

```<code>@font-face {
    font-family: 'arabicsansbold';
    src: url('arabicsans_bold-webfont.eot');
    src: url('arabicsans_bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('arabicsans_bold-webfont.woff2') format('woff2'),
         url('arabicsans_bold-webfont.woff') format('woff'),
         url('arabicsans_bold-webfont.ttf') format('truetype'),
         url('arabicsans_bold-webfont.svg#arabicsansbold') format('svg');
    font-weight: normal;
    font-style: normal;

}
</code>```

html

```<code><!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" />
    <style type="text/css">
                    body{
                font-family: 'arabicsansbold';
                        }
        </style>
</head>

<body>
<div id="container">
    <div id="header">ArabicSans Bold     123456</div>

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

Title: Arabic font not working in IE 11?

Body:
i am facing issue for arabic font its working proper Mozilla and chrome nut not working proper in IE 11 my code is below anyone can you help me please.

<!DOCTYPE html>

        <input type='text' value='account 1 2 3' />

 account  1 2 3

Body:
Css

@font-face {
    font-family: 'arabicsansbold';
    src: url('arabicsans_bold-webfont.eot');
    src: url('arabicsans_bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('arabicsans_bold-webfont.woff2') format('woff2'),
         url('arabicsans_bold-webfont.woff') format('woff'),
         url('arabicsans_bold-webfont.ttf') format('truetype'),
         url('arabicsans_bold-webfont.svg#arabicsansbold') format('svg');
    font-weight: normal;
    font-style: normal;

}

html

<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" />
    <style type="text/css">
                    body{
                font-family: 'arabicsansbold';
                        }
        </style>
</head>

<body>
<div id="container">
    <div id="header">ArabicSans Bold     123456</div>

</div>
</body>
</html>


问:
How to replace two characters at the same time with js?
Below is my code.

```<code> var str = 'test//123_456';
 var new_str = str .replace(/\//g, '').replace(/_/g, '');
 console.log(new_str);
</code>```

It will print test123456 on the screen.

My question is how to do it in same regular express? not replace string twice.

Thanks.

答:
Use the regex to match the list of character by using regex character class.</p>

```<code>var str = "test//123_456";
var nstr = str.replace(/[\/_]/g, '');
</code>```

Body:
Below is my code.

 var str = 'test//123_456';
 var new_str = str .replace(/\//g, '').replace(/_/g, '');
 console.log(new_str);

It will print test123456 on the screen.

My question is how to do it in same regular express? not replace string twice.

Thanks.

Body:
Use the regex to match the list of character by using regex character class.

var str = "test//123_456";
var nstr = str.replace(/[\/_]/g, '');


问:
how to create git branch in remote repository without checking out using jgit
Can we create a remote branch in git using jgit without checking out. For example I want to create a branch named foo from branch named bar in my remote repository without checking out branch bar locally.

答:
I was able to create a remote branch using the rest api curl command

/rest/branch-utils/1.0/projects/{projectKey}/repos/{repositorySlug}/branches

Rest api and curl command


问:
eclipse.buildScript Complete Example Script for headless build
I am trying to generate a build script for a plugin outside the IDE

Below is mybuild.xml

```<code><project name="com.foo.poo"  xmlns='antlib:org.apache.tools.ant'>
<target name="build.plugin">
<antcall target="generateBuildScript" />
<ant dir="${workspace.dir}/${project.name}"
antfile="build.xml"
target="build.update.jar" />
<copy todir="${eclipse.dir}/plugins">
<fileset dir="${workspace.dir}/${project.name}">
<include name="*.jar"/>
</fileset>
</copy>
</target>
<target name="generateBuildScript">
<eclipse.buildScript elements="plugin@${project.name}"
buildDirectory="${workspace.dir}"
baseLocation="${eclipse.dir}"
configInfo="linux,gtk,win32,win32,x86"/>
</target>
</project>
</code>```

Expecting build.xml to be generated Please Guide me

When I run above script

```<code>$java -jar {$Eclipse.Dir}/plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar -application org.eclipse.ant.core.antRunner -buildfile <Project_path>\mybuild.xml
</code>```

I nothing is happening on build success.

答:
Here i have found the answer may help some new bees like me..

```<code><project name="com.foo.poo"  xmlns='antlib:org.apache.tools.ant'>
...
</project>
</code>```

As there is no default set, it is not generating the required jar file so
modified only the first line as

```<code><project name="com.foo.poo" default="build.plugin" xmlns='antlib:org.apache.tools.ant'>
...
</project>
</code>```

now the required jar is generated under plugin folder and even copied to plugin folder of eclipse.
baseLocation : Target Plugins Directory absolute path.
buildDirectory: Absolute path to the plugin folder in which the Plugin Project is  present.

Body:
I am trying to generate a build script for a plugin outside the IDE

Below is mybuild.xml

<project name="com.foo.poo"  xmlns='antlib:org.apache.tools.ant'>
<target name="build.plugin">
<antcall target="generateBuildScript" />
<ant dir="${workspace.dir}/${project.name}"
antfile="build.xml"
target="build.update.jar" />
<copy todir="${eclipse.dir}/plugins">
<fileset dir="${workspace.dir}/${project.name}">
<include name="*.jar"/>
</fileset>
</copy>
</target>
<target name="generateBuildScript">
<eclipse.buildScript elements="plugin@${project.name}"
buildDirectory="${workspace.dir}"
baseLocation="${eclipse.dir}"
configInfo="linux,gtk,win32,win32,x86"/>
</target>
</project>

Expecting build.xml to be generated Please Guide me

When I run above script

$java -jar {$Eclipse.Dir}/plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar -application org.eclipse.ant.core.antRunner -buildfile <Project_path>\mybuild.xml

I nothing is happening on build success.

Body:
Here i have found the answer may help some new bees like me..

<project name="com.foo.poo"  xmlns='antlib:org.apache.tools.ant'>
...
</project>

As there is no default set, it is not generating the required jar file so
modified only the first line as

<project name="com.foo.poo" default="build.plugin" xmlns='antlib:org.apache.tools.ant'>
...
</project>

now the required jar is generated under plugin folder and even copied to plugin folder of eclipse.
baseLocation : Target Plugins Directory absolute path.
buildDirectory: Absolute path to the plugin folder in which the Plugin Project is  present.


问:
What is the relationship between workers, worker instances, and executors?
In Spark Standalone mode, there are master and worker nodes.

Here are few questions:

Does 2 worker instance mean one worker node with 2 worker processes?

Does every worker instance hold an executor for specific application (which manages storage, task) or one worker node holds one executor?

Is there a flow chart explaining how spark works on runtime, such as word count?

答:
Extending to other great answers, I would like to describe with few images.

In Spark Standalone mode, there are master node and worker nodes.

If we represent both master and workers(each worker can have multiple executors if CPU and memory are available) at one place for standalone mode.

If you are curious about how Spark works with YARN? check this post Spark on YARN

1. Does two worker instance mean one worker node with two worker processes?

In general, we call worker instance as a slave as it's a process to execute spark tasks/jobs. Suggested mapping for a node(a physical or virtual machine) and a worker is,

```<code>1 Node = 1 Worker process
</code>```

2. Does every worker instance hold an executor for the specific application (which manages storage, task) or one worker node holds one executor?

Yes, A worker node can be holding multiple executors (processes) if it has sufficient CPU, Memory and Storage.

Check the Worker node in the given image.

BTW, the Number of executors in a worker node at a given point of time entirely depends on workload on the cluster and capability of the node to run how many executors.

3. Is there a flow chart explaining how spark runtime?

If we look at the execution from Spark perspective over any resource manager for a program, which join two rdds and do some reduce operation then filter

HIH

Body:
Extending to other great answers, I would like to describe with few images.

In Spark Standalone mode, there are master node and worker nodes.

If we represent both master and workers(each worker can have multiple executors if CPU and memory are available) at one place for standalone mode.

If you are curious about how Spark works with YARN? check this post Spark on YARN

1. Does two worker instance mean one worker node with two worker processes?

In general, we call worker instance as a slave as it's a process to execute spark tasks/jobs. Suggested mapping for a node(a physical or virtual machine) and a worker is,

1 Node = 1 Worker process

2. Does every worker instance hold an executor for the specific application (which manages storage, task) or one worker node holds one executor?

Yes, A worker node can be holding multiple executors (processes) if it has sufficient CPU, Memory and Storage.

Check the Worker node in the given image.

BTW, the Number of executors in a worker node at a given point of time entirely depends on workload on the cluster and capability of the node to run how many executors.

3. Is there a flow chart explaining how spark runtime?

If we look at the execution from Spark perspective over any resource manager for a program, which join two rdds and do some reduce operation then filter

HIH


问:
Order of items in classes: Fields, Properties, Constructors, Methods
Is there an official C# guideline for the order of items in terms of class structure?

Does it go:

Public Fields

Private Fields

Properties

Constructors

Methods

?

I'm curious if there is a hard and fast rule about the order of items? I'm kind of all over the place. I want to stick with a particular standard so I can do it everywhere.

The real problem is my more complex properties end up looking a lot like methods and they feel out of place at the top before the constructor.

Any tips/suggestions?

答:
I know this is old but my order is as follows:

in order of public, protected, private, internal, abstract

Constants

Static Variables

Fields

Events

Constructor(s)

Methods

Properties

Delegates

I also like to write out properties like this (instead of the shorthand approach)

```<code>// Some where in the fields section
private int someVariable;

// I also refrain from
// declaring variables outside of the constructor

// and some where in the properties section I do
public int SomeVariable
{
    get { return someVariable; }
    set { someVariable = value; }
}
</code>```

OwnerDisplayName: Simucal

LastEditorDisplayName: Simucal

Body:
I know this is old but my order is as follows:

in order of public, protected, private, internal, abstract

Constants

Static Variables

Fields

Events

Constructor(s)

Methods

Properties

Delegates

I also like to write out properties like this (instead of the shorthand approach)

// Some where in the fields section
private int someVariable;

// I also refrain from
// declaring variables outside of the constructor

// and some where in the properties section I do
public int SomeVariable
{
    get { return someVariable; }
    set { someVariable = value; }
}


问:
objective c social/social.h not found
```<code>//
//  Social.h
//  Social
//
//  Copyright (c) 2012 Apple Inc. All rights reserved.
//

#import <Social/SLServiceTypes.h>
#import <Social/SLRequest.h>
#if TARGET_OS_IPHONE
#import <Social/SLComposeViewController.h>
#endif
</code>```

I am trying to compile a simple app for iOS-6 in Xcode 5, and calling the basic     Social framework provided by apple.  I am getting an error of SLComposeViewController - file not found.  This is a new error that just decided to show up at build time this afternoon.  I have the rest of the social framework.  Any ideas?

答: Sometime in the old version of Xcode this type of problem occure.For this problem goto link framework and library section , click on plus button and add "AdSupport.framework".then make a clean and build your project.</p>

Title: objective c social/social.h not found

Body:
//
//  Social.h
//  Social
//
//  Copyright (c) 2012 Apple Inc. All rights reserved.
//

#import <Social/SLServiceTypes.h>
#import <Social/SLRequest.h>
#if TARGET_OS_IPHONE
#import <Social/SLComposeViewController.h>
#endif

I am trying to compile a simple app for iOS-6 in Xcode 5, and calling the basic     Social framework provided by apple.  I am getting an error of SLComposeViewController - file not found.  This is a new error that just decided to show up at build time this afternoon.  I have the rest of the social framework.  Any ideas?


问:
Laravel Eloquent : with query parameters
I've finally worked out how to put together a complex query to get related models.

This is what my query currently looks like...

```<code>    $campaign = Campaign::find($campaign_id);
    $buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q){
        $q->where('campaign_id', '13');
    }])->get();
</code>```

The complex part is I'm trying to get entries from emails that have both a matching buyer_id & campaign_id. This query achieves exactly what I'm after in a pretty efficient way...

BUT... I can't work out how to pass in parameters to the with closure. At the moment I've hard coded the id 13 into the where query in the closure but I want it to be equal to $campaign_id passed in to the original function.

How do I do this?

答:
TRY With This

```<code>$mainQuery=StockTransactionLog::with(['supplier','customer','warehouse','stockInDetails'=>function($query) use ($productId){
            $query->with(['product'])->where('product_stock_in_details.product_id',$productId);
        },'stockOutDetails'=>function($query) use ($productId){
            $query->with(['product'])->where('product_stock_out_details.product_id',$productId);
        },'stockDamage'=>function($query) use ($productId){
            $query->with(['product'])->where('product_damage_details.product_id',$productId);
        },'stockReturn'=>function($query) use ($productId){
            $query->select('id','return_id','product_id');
            $query->with(['product'])->where('product_return_details.product_id',$productId);
        }]);
</code>```

Body:
I've finally worked out how to put together a complex query to get related models.

This is what my query currently looks like...

    $campaign = Campaign::find($campaign_id);
    $buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q){
        $q->where('campaign_id', '13');
    }])->get();

The complex part is I'm trying to get entries from emails that have both a matching buyer_id & campaign_id. This query achieves exactly what I'm after in a pretty efficient way...

BUT... I can't work out how to pass in parameters to the with closure. At the moment I've hard coded the id 13 into the where query in the closure but I want it to be equal to $campaign_id passed in to the original function.

How do I do this?

Body:
TRY With This

$mainQuery=StockTransactionLog::with(['supplier','customer','warehouse','stockInDetails'=>function($query) use ($productId){
            $query->with(['product'])->where('product_stock_in_details.product_id',$productId);
        },'stockOutDetails'=>function($query) use ($productId){
            $query->with(['product'])->where('product_stock_out_details.product_id',$productId);
        },'stockDamage'=>function($query) use ($productId){
            $query->with(['product'])->where('product_damage_details.product_id',$productId);
        },'stockReturn'=>function($query) use ($productId){
            $query->select('id','return_id','product_id');
            $query->with(['product'])->where('product_return_details.product_id',$productId);
        }]);


问:
How to emulate the same behaviour in kotlin
How to emulate the same behaviour using lambdas kotlin.

Java Code:

```<code>   public interface OnClickListener{
    public void onClick();
    }

    public class Sample {

            OnclickListener mOnclickListener;

            public void setOnclickListener(OnclickListener l){

                if(l!=null)
                mOnclickListener =l;
            }

            public void performClick()
            {
                mOnclickListener.onClick(5);
            }

        }

  public class SampleImpl{

     Sample sample=new Sample();
      sample.setOnClickListener(new OnClickListner(){ onClick{}});

     sample.performClick();

}
</code>```

As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...

Kotlin code :

```<code>var sample= Sample();

    sample.setOnClickListener({Int ->  println("action performed") })
    sample.performClick(); //will call this method whenever needed.

    class Sample {

         var click=null;

        fun setOnClickListener(onClick : (Int)->Unit){

           click= onClick // trying to assign and want to use it in another
                              funciton. I know it is wrong, how to achieve
                             this.
        }

      fun performClick()
       {
           click(5)
       }
    }
</code>```

Is there any alternative to achieve this?

答:
Alterantively you can try this:

```<code>interface OnClickListener {
        fun onClick()
    }

    inner class Sample {

        internal var mOnclickListener: OnClickListener

        fun setOnclickListener(l: OnClickListener?) {

            if (l != null)
                mOnclickListener = l
        }

        fun performClick() {
            mOnclickListener.onClick(5)
        }

    }

    inner class SampleImpl internal constructor() {

        internal var sample = Sample()

        init {
            onClick
            run { }
        }

    }
</code>```

Body:
How to emulate the same behaviour using lambdas kotlin.

Java Code:

   public interface OnClickListener{
    public void onClick();
    }

    public class Sample {

            OnclickListener mOnclickListener;

            public void setOnclickListener(OnclickListener l){

                if(l!=null)
                mOnclickListener =l;
            }

            public void performClick()
            {
                mOnclickListener.onClick(5);
            }

        }

  public class SampleImpl{

     Sample sample=new Sample();
      sample.setOnClickListener(new OnClickListner(){ onClick{}});

     sample.performClick();

}

As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...

Kotlin code :

var sample= Sample();

    sample.setOnClickListener({Int ->  println("action performed") })
    sample.performClick(); //will call this method whenever needed.

    class Sample {

         var click=null;

        fun setOnClickListener(onClick : (Int)->Unit){

           click= onClick // trying to assign and want to use it in another
                              funciton. I know it is wrong, how to achieve
                             this.
        }

      fun performClick()
       {
           click(5)
       }
    }

Is there any alternative to achieve this?

Body:
Alterantively you can try this:

interface OnClickListener {
        fun onClick()
    }

    inner class Sample {

        internal var mOnclickListener: OnClickListener

        fun setOnclickListener(l: OnClickListener?) {

            if (l != null)
                mOnclickListener = l
        }

        fun performClick() {
            mOnclickListener.onClick(5)
        }

    }

    inner class SampleImpl internal constructor() {

        internal var sample = Sample()

        init {
            onClick
            run { }
        }

    }


问:
Getting ERROR 1452: Cannot add or update a child row: a foreign key constraint fails when using 1 our 4 insert statements
I am trying to insert data into my DB and I keep getting the "ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails" on 1 insert command. I believe it has to do with the FKs I used when I created the table. But I am not sure how to fix it. Any suggestions would be awesome.

Original Create table commands:
REATE TABLE Donut
  (DonutID int,
  DonutName VARCHAR(25) not null,
  Description VARCHAR(25) not null,
  UnitPrice decimal(4,2) not null,
  PRIMARY KEY (DonutID) ) ;

CREATE TABLE Customer
  ( CustomerID INT not null,
   FirstName VARCHAR(20) not null,
   LastName VARCHAR(20) not null,
   StreetAddress VARCHAR(20) not null,
   Apt VARCHAR(20),
   City VARCHAR(20) not null,
   State VARCHAR(2) not null,
   ZipCode VARCHAR(5) not null,
   HomePhone VARCHAR(10) not null,
   MobilePhone VARCHAR(10) not null,
   OtherPhone VARCHAR(10),
    PRIMARY KEY(CustomerID) ) ;

CREATE TABLE Orders
  ( OrderID int not null,
   CustomerID int,
   OrderDate Date not null,
   Notes VARCHAR(100),
    PRIMARY KEY (OrderID),
    FOREIGN KEY (CustomerID)
        REFERENCES Customer (CustomerID) ) ;

CREATE TABLE OrderItem
  ( OrderID INT,
   DonutID INT,
   Qty SMALLINT not null,
   PRIMARY KEY(OrderID, DonutID),
   FOREIGN KEY (OrderID)
        REFERENCES Orders (CustomerID),
   FOREIGN KEY (DonutID)
        REFERENCES Donut (DonutID) ) ;

Insert command that is failing:
INSERT INTO OrderItem
    (OrderID,DonutID,Qty) VALUES
    (991,1,12),
    (992,2,500),
    (993,3,6);

答:
This error is probably happening because one or both of your inserted records refer to records in the Orders and/or Donut tables which do not exist.

Try running the following queries:

```<code>SELECT *
FROM Orders
WHERE CustomerID IN (991, 992);
</code>```

and this one:

```<code>SELECT *
FROM Donut
WHERE DonutID IN (1, 2);
</code>```

If you don't see four parent records from the two above queries, then you have the answer to your problem.  The solution of course is to not refer to records which do not exist.

Body:
This error is probably happening because one or both of your inserted records refer to records in the Orders and/or Donut tables which do not exist.

Try running the following queries:

SELECT *
FROM Orders
WHERE CustomerID IN (991, 992);

and this one:

SELECT *
FROM Donut
WHERE DonutID IN (1, 2);

If you don't see four parent records from the two above queries, then you have the answer to your problem.  The solution of course is to not refer to records which do not exist.


问:
angular cli change default environment when running ng serve
When I run ng serve it uses default environment as dev. Is there a way to update angular cli to use a different environment file?

Update

Sorry, Should have been more clear in my question. I know we can use --env switch to specify the environment file to use, but was wondering if there is a way to change the default environment file selection when no env is specified. Currently we have environment.local.ts file, I am trying to update angular cli configuration to use environment.local.ts when no environment is specified.

答:
It may be issue with the @angular/cli version, please remove/uninstall the current version of your @angular/cli by using the following command.

```<code>"npm remove @angular/cli" --save-dev
</code>```

and then install the latest version like :

```<code>"npm install @angular/cli@1.3.0" --save-dev
</code>```

I hope default environment issue will be solve.

Body:
It may be issue with the @angular/cli version, please remove/uninstall the current version of your @angular/cli by using the following command.

"npm remove @angular/cli" --save-dev

and then install the latest version like :

"npm install @angular/cli@1.3.0" --save-dev

I hope default environment issue will be solve.


问:
safety of passing boost::shared_ptr reference
my question is, how fail-safe is the following code snippet which is part of my resource manager:

```<code> bool Load(std::string name, boost::shared_ptr<Asset::Model>& newModel)
 {
  std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;

  seeker = models.find(name);
  if (seeker == models.end())
   return false;

  newModel = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
  return true;
 }

private:
 std::map< std::string, boost::scoped_ptr<Asset::Model> >  models;
</code>```

because passing boost's shared_ptr by reference is actually not part of the shared_ptr concept, if i only use it in this scope, could i run into trouble?

答:
I guess you want to do something like this:

```<code>boost::shared_ptr<Asset::Model> ptr;
if(Load("stuff", ptr))
{
     doSomething with ptr
}
</code>```

In this case you should be fine.

However you don't need to use a reference here. Just return a shared_ptr and set it to 0 if no element was found:

```<code> boost::shared_ptr<Asset::Model> Load(std::string name)
 {
  std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;
  boost::shared_ptr<Asset::Model> retPtr;

  seeker = models.find(name);
  if (seeker == models.end())
   return retPtr;

  retPtr = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
  return retPtr;
 }
</code>```

However I noticed you are using scoped_ptr in a standard container - which AFAIK is not possible.

Body:
my question is, how fail-safe is the following code snippet which is part of my resource manager:

 bool Load(std::string name, boost::shared_ptr<Asset::Model>& newModel)
 {
  std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;

  seeker = models.find(name);
  if (seeker == models.end())
   return false;

  newModel = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
  return true;
 }

private:
 std::map< std::string, boost::scoped_ptr<Asset::Model> >  models;

because passing boost's shared_ptr by reference is actually not part of the shared_ptr concept, if i only use it in this scope, could i run into trouble?

Body:
I guess you want to do something like this:

boost::shared_ptr<Asset::Model> ptr;
if(Load("stuff", ptr))
{
     doSomething with ptr
}

In this case you should be fine.

However you don't need to use a reference here. Just return a shared_ptr and set it to 0 if no element was found:

 boost::shared_ptr<Asset::Model> Load(std::string name)
 {
  std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;
  boost::shared_ptr<Asset::Model> retPtr;

  seeker = models.find(name);
  if (seeker == models.end())
   return retPtr;

  retPtr = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
  return retPtr;
 }

However I noticed you are using scoped_ptr in a standard container - which AFAIK is not possible.


问:
Display specific length of div element pagination
I would like to know how to display specific length of an item by pagination.
with the element code below shows 20 items of div elements.

```<code><div class="group-of-element">
<div class="items">item1</div>
<div class="items">item2</div>
<div class="items">item3</div>
<div class="items">item4</div>
<div class="items">item5</div>
<div class="items">item6</div>
<div class="items">item7</div>
<div class="items">item8</div>
<div class="items">item9</div>
<div class="items">item10</div>
<div class="items">item12</div>
<div class="items">item13</div>
<div class="items">item14</div>
<div class="items">item15</div>
<div class="items">item16</div>
<div class="items">item17</div>
<div class="items">item18</div>
<div class="items">item19</div>
<div class="items">item20</div>
</div>
</code>```

As a result It would be something like this

The first 9 of div items would be displayed and when the button "Display Next 9 items" would be clicked it would display the next set of 9 items. And also when the "Display all items" would be clicked, all results should be displayed.

*Updated Also all the old items would need to hide when the "next 9 items" should be clicked

Any help would be greatly appreciated

答:
Please refer below link for client-side paging, include Jquery pagination.js

Code for Pagination

Body:
I would like to know how to display specific length of an item by pagination.
with the element code below shows 20 items of div elements.

item1

item2

item3

item4

item5

item6

item7

item8

item9

item10

item12

item13

item14

item15

item16

item17

item18

item19

item20

As a result It would be something like this

The first 9 of div items would be displayed and when the button "Display Next 9 items" would be clicked it would display the next set of 9 items. And also when the "Display all items" would be clicked, all results should be displayed.

*Updated Also all the old items would need to hide when the "next 9 items" should be clicked

Any help would be greatly appreciated


问:
Communication between client and server in Angular 2+
I am using NodeMailer for mail service. I have to get an email address from a field in client side and send that value to app.js where my nodemailer code resides.

client side

```<code>ngOnInit() {
  this.forgotForm = this.formBuilder.group({
    email: this.email,
  });
}

sendmail() {
}
</code>```

app.js, Nodemailer code (I have to get email id for to address here)

```<code>let mailOptions = {
    from: 'xyz@gmail.com',
    to: '',
    subject: 'Test Mailer',
    text: 'I am testing Nodemailer to send email.',
};
</code>```

答:
You Should Consider Looking/ Learning Angular and then going into forms . and then into http modules which will help you post data to services

This is a gist not the actual answer

There are a lots of ways to get this done , using normal inputs and getting data from that input using button control or using Forms[the best approach] as you might have other details to send as well.

There are two kind of froms in Angular Template Driven or Reactive Forms.

After getting the details in your form you will need to post it to a Rest service i am guessing. For that you will need to look at Angular Http Client Module

Please look at those links for more detailed Info on them.

Body:
I am using NodeMailer for mail service. I have to get an email address from a field in client side and send that value to app.js where my nodemailer code resides.

client side

ngOnInit() {
  this.forgotForm = this.formBuilder.group({
    email: this.email,
  });
}

sendmail() {
}

app.js, Nodemailer code (I have to get email id for to address here)

let mailOptions = {
    from: 'xyz@gmail.com',
    to: '',
    subject: 'Test Mailer',
    text: 'I am testing Nodemailer to send email.',
};


问:
Recover sass files from map and css
I'm just thinking if there is any way to recover some *.scss files if we have only css and its map. Ex.: someday someone removed your scss files :) Is it possible? I know that map helps us to debug our css code and show where it is located in scss. It's a lot of information. But is it enought? Any way to do this?

Picture above shows that example: sass folder doesn't exist. But browser know what and where is from source map.

答: I've used this site before to convert css output back to scss formatting. http://css2sass.herokuapp.com/ Not perfect but its a start. </p>

Title: Recover sass files from map and css


问:
Python trying to enable application folder/file navigation - import error no module named 'nav'

What is a basic solution, or basic alternative solutions, to eliminate  import error no module named 'nav' in the context shown below?

Package (directory) and module (file) structure of application:

```<code>root\code\
    __init__.py
    nav.py
    resource.txt

root\code\mkts\goog\
    __init__.py
    update_goog.py

root\code\mkts\yhoo\
    __init__.py
    update_yhoo.py

root\mkts\goog\data\
    DJIA.csv

root\mkts\yhoo\data\
    DJIA.csv

root\mkts\goog\human\
    DJIA.txt

root\mkts\yhoo\human\
    DJIA.txt
</code>```

Nav.py (some relevant code)

```<code>import os

this_path = os.path.abspath(__file__)
code = os.path.split(this_path)[0] # DO NOT put os.sep here!
root = os.path.split(code)[0] + os.sep
code = os.path.join(root,'code' + os.sep)

mkts = os.path.join(root,'mkts' + os.sep)

mkts_goog = os.path.join(mkts,'goog' + os.sep)
mkts_goog_data = os.path.join(mkts_goog,'data' + os.sep)
mkts_goog_human = os.path.join(mkts_goog,'human' + os.sep)

if __name__ == '__main__':
    # print(test())
</code>```

update_goog.py (relevant import test code)

```<code>import nav

print(nav.mkts_goog_data)
</code>```

When I run "python update_goog.py" from the command line I expect to see a print of the directory root\mkts\goog\data\ instead Python 3.6 throws the ImportError no module named 'nav'. I have read a bunch of related posts but cannot determine the best basic options for solving my particular problem. I may be missing something simple and don't want to cook up an overly complicated solution.

答:
The module nav is several levels above the module goog (nav is its "grandfather").  As such, you'll need to set up some official packaging structure using Python's methods for doing that.  That will likely involve something like a local pip install or a python setup or something similar.

Check out PyPA's Packaging and Distributing Projects.  You can ignore the "distributing" part, but the rest of it will be relevant.

I know I'm really just giving a link, which is a no-no, but the answer is fairly long and involved, and is captured very well in that and similar pages.

Body:
What is a basic solution, or basic alternative solutions, to eliminate  import error no module named 'nav' in the context shown below?

Package (directory) and module (file) structure of application:

root\code\
    __init__.py
    nav.py
    resource.txt

root\code\mkts\goog\
    __init__.py
    update_goog.py

root\code\mkts\yhoo\
    __init__.py
    update_yhoo.py

root\mkts\goog\data\
    DJIA.csv

root\mkts\yhoo\data\
    DJIA.csv

root\mkts\goog\human\
    DJIA.txt

root\mkts\yhoo\human\
    DJIA.txt

Nav.py (some relevant code)

import os

this_path = os.path.abspath(__file__)
code = os.path.split(this_path)[0] # DO NOT put os.sep here!
root = os.path.split(code)[0] + os.sep
code = os.path.join(root,'code' + os.sep)

mkts = os.path.join(root,'mkts' + os.sep)

mkts_goog = os.path.join(mkts,'goog' + os.sep)
mkts_goog_data = os.path.join(mkts_goog,'data' + os.sep)
mkts_goog_human = os.path.join(mkts_goog,'human' + os.sep)

if __name__ == '__main__':
    # print(test())

update_goog.py (relevant import test code)

import nav

print(nav.mkts_goog_data)

When I run "python update_goog.py" from the command line I expect to see a print of the directory root\mkts\goog\data\ instead Python 3.6 throws the ImportError no module named 'nav'. I have read a bunch of related posts but cannot determine the best basic options for solving my particular problem. I may be missing something simple and don't want to cook up an overly complicated solution.


问:
How to continue looping after invalid data type input?
I'm trying to do one check for invalid input data type. If the the input data type is of type char, I want the re-loop over the menu options. But my program terminates instead.

```<code>int menu()
{
    int choice = 15;
    while ((choice > 14) || ( choice < 0))
    {
        cout << "Enter 0 to quit\n";
        cout << "Enter 1 for Addition\n";
        cout << "Enter 2 for Subtraction\n";
        cout << "Enter 3 for Multiplication\n";
        cout << "Enter 4 for Division of two integers\n";
        cout << "Enter 5 for Real Division of two integers\n";
        cout << "Enter 6 for Quotient of a division\n";
        cout << "Enter 7 for Remainder of a division\n";
        cout << "Enter 8 for Factorial of an integer\n";
        cout << "Enter 9 for Exponential of two integers\n";
        cout << "Enter 10 for Finding if number is even or odd\n";
        cout << "Enter 11 for Area of a Square\n";
        cout << "Enter 12 for Area of a Circle\n";
        cout << "Enter 13 for Area of an Isoceles Triangle\n";
        cout << "Enter 14 for Converting Decimal to binary or hexadecimal\n";
        cin >> choice;

        if((choice > 14) || (choice < 0))
        {
            cout << "Invalid entry: Try again" << endl << endl;
        }
        else if ( !choice )
        {
            return choice;
        }
        else if (choice)
        {
            return choice;
        }
    }

    return choice;
}
</code>```

Output after entering char 'f' as cin

答:
Remove space line and then run the code again.</p>

```<code>if((choice > 14) || (choice < 0))
    cout << "Invalid entry: Try again" << endl << endl;

else if ( !choice )
{
 return choice;
}
////// remove the empty space line below///////////
else if (choice)
    return choice;
///////////////////////////////////////////////////
</code>```

Body:
I'm trying to do one check for invalid input data type. If the the input data type is of type char, I want the re-loop over the menu options. But my program terminates instead.

int menu()
{
    int choice = 15;
    while ((choice > 14) || ( choice < 0))
    {
        cout << "Enter 0 to quit\n";
        cout << "Enter 1 for Addition\n";
        cout << "Enter 2 for Subtraction\n";
        cout << "Enter 3 for Multiplication\n";
        cout << "Enter 4 for Division of two integers\n";
        cout << "Enter 5 for Real Division of two integers\n";
        cout << "Enter 6 for Quotient of a division\n";
        cout << "Enter 7 for Remainder of a division\n";
        cout << "Enter 8 for Factorial of an integer\n";
        cout << "Enter 9 for Exponential of two integers\n";
        cout << "Enter 10 for Finding if number is even or odd\n";
        cout << "Enter 11 for Area of a Square\n";
        cout << "Enter 12 for Area of a Circle\n";
        cout << "Enter 13 for Area of an Isoceles Triangle\n";
        cout << "Enter 14 for Converting Decimal to binary or hexadecimal\n";
        cin >> choice;

        if((choice > 14) || (choice < 0))
        {
            cout << "Invalid entry: Try again" << endl << endl;
        }
        else if ( !choice )
        {
            return choice;
        }
        else if (choice)
        {
            return choice;
        }
    }

    return choice;
}

Output after entering char 'f' as cin

Body:
Remove space line and then run the code again.

if((choice > 14) || (choice < 0))
    cout << "Invalid entry: Try again" << endl << endl;

else if ( !choice )
{
 return choice;
}
////// remove the empty space line below///////////
else if (choice)
    return choice;
///////////////////////////////////////////////////


问:
How to convert an existing PHP library file so it can be used in a CakePHP framework?
I have this library in PHP non-Cake format, the usual PHP scripting which currently works like a charm. I need to use this in a Cake framework. The library file is as follow: (example extracted)

```<code><?php

// REST API functions

function sendAction($itemurl, $itemimageurl, $sessionid, $userid, $rating=""){

    global $someapiwebsiteURL, $apiKey, $tenantId;
    $somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.
                                                                 .....
                ................
    }

    //Codes extract

?>
</code>```

I've come across a few ways of doing it. Currently confused, how am I going to place this library file into my Cake framework?

App::import()

Datasource

The functions in the library file above (I supposed it'd be used in one of my Controllers to render the data outputting through the view).

Currently working in a non-Cake framework structure, the view page is such as: (example extracted)

```<code><?php
// my view page

$viewResponse = sendAction($itemdescription ,$itemurl , $itemimageurl,$sessionid,$userid);

//sample code only
?>
</code>```

Both the files are working fine. The logic of putting it in a CakePHP framework is the problem here. Anyone may suggest "the" way of doing this without over-strenuously working on a data source? If we have to use a data source in App/models/datasources/, how exactly is the structure of it? Like, e.g., in datasource file, do we include the library functions? or is it some generic ReST datasource file which can be found here: CakePHP ReST datasource . I've gone through the cookbook chapter on datasource and understand we have to define the datasource in our database.php, but if someone is certain about their way of accomplishing it either using datasource or app::import() method, please share with more details?

UPDATE:

Hi Lionel!, thanks for filling up. Well, actually users will click on view action: function view (){} in my foods_controller. I'm appending some scripts here to include my view function in my foods_controller so maybe it may help you to help out easier. Thanks..

```<code>function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid food', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('food', $this->Food->read(null, $id));
    }
</code>```

The view action triggers the send_action function, (each time a user clicks on view page on foods controller). So each time, a user clicks on view action, his (dynamic variables): userid, sessionid, that page's itemid, url, itemdescription; (timerange value is a static string value "ALL"), and if any (etc.), so far only these values are available: Will be used as the "parameters" in the Send Action function. What you wrote is close to what the codes can do. You're right. Except we should include the Send Action function inside the view() in foods controller?

If we look at dynamically filling in the variables mentioned in the point above, could you modify your second code (the code from your product_controller, e.g.) so it also works to receive the variables dynamically? (as you asked in the last update: how to get the parameters..)

Just to make it clear.

A user views the page. The send action collects data and send to the API. (as we've already done by calling the function in the library the (ACME.php). *just waiting for your update if possible, thanks.

In the function view() of the foods controller: there's also an additional calling. The (2)second calling which is this:

$recommendResponse = getRecommendations("otherusersviewed", $itemId, $userId);

The second calling calls the ACME.php library file in which there consists the (2)second function that retrieves data, here it is: (it's in working order, but just needs to be changed into a public static function like you did for the (1)first function. Could you help to modify this code too, please?:

```<code>function getRecommendations($recommendationType, $itemId, $userId){

    // sample code similar to the first one.
}
</code>```

That's all to it. It seems quite simple in the normal PHP format, and it works easily, but getting  it on an MVC framweork is a bit challenging for some, a lot for me. Thanks for helping out, Lionel. :-)

P.S. Hi Lionel, I notice something missing in the library after changes? Look originally we have this:

$somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.

Look, the variables for $SomeWebsiteAPI and $SomeApiWebsiteURL are different. Did I miss out something? or you have modified so it is more efficient ? I see that the variable named $SomeWebsiteAPI is modified to become variable called $link ? and variable $SomeApiWebsiteURL is changed to the named variable, $url, am I right ? .. thanks.

Thanks, best regards. John Maxim

答:
To me, if I have this piece of code, I would first wrap it into a static (or normal) class, and named it ACME, then I will move the acme.php into /apps/libs/acme.php. Then in the controller, I will use App::import('Lib', 'acme'). This action do nothing but just requiring the file, so you can just use it instantly by calling ACME::sendAction(...).

And regarding the global thing, you might just need to declare a static (or normal) class, then define the shared variables as part of the class properties, so you can share them among all the functions in the class.

For example, this is the /app/libs/acme.php

```<code>class ACME {

    private static $someapiwebsiteURL = "http://thewebsite/api/1.0/";
    private static $apiKey = "0010KIUMLA0PLQA665JJ";
    private static $tenantId = "THE_TENANT_NAME";

    /**
     * Simple builder to build links from array of $params
     *
     * @param string $url The api url
     * @param array $params The given parameters
     * @return string built url
     */
    private static function BuildLink($url="", $params=array()) {

        $link = $url;
        foreach($params as $k=>$v) {
            $link .= "&$k=$v";
        }

        //Replace the first & to ?
        $link = preg_replace("/&/", "?", $link, 1);

        //Not sure if we need URL encode here, please uncomment this
        //if the API could not work.
        //$link = urlencode($link);

        return $link;
    }

    public static function SendAction($action, $itemId, $itemdescription, $itemurl, $itemimageurl, $sessionid, $userid, $rating="") {

        $somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$action, array(
            "apikey"=>self::$apiKey,
            "sessionid"=>$sessionid,
            "userid"=>$userid,
            "tenantid"=>self::$tenantId,
            "itemid"=>$itemId,
            "itemdescription"=>$itemdescription,
            "itemurl"=>$itemurl,
            "itemimageurl"=>$itemimageurl,

            /**
             * Assuming your API smart enough to only use this value when
             * the action is "rate"
             */
            "ratingvalue"=>$rating
        ));

        $xml = simplexml_load_file($somewebsiteAPI);
        return $xml;
    }

    public static function GetRecommendations($recommendationType, $itemId, $userId) {
        $somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$recommendationType, array(
            'apikey'=>self::$apiKey,
            'tenantid'=>self::$tenantId,
            'itemid'=>$itemId,
            'userid'=>$userId
        ));

        $xml = simplexml_load_file($somewebsiteAPI);
        return $xml;
    }
}
</code>```

And in your controller

```<code>App::import('Lib', 'acme');

class FoodController extends AppController {

    //Food is plural already I assume? You can just use
    //food, should be ok I think, else it will be weird
    //to use /foods/view/?
    var $name = "Food";
    var $uses = array("Item", "Food");

    function view($id="") {
        //We accepts only valid $id and $id > 0.
        //Take notes that this $id will be a string, not int.
        if (ctype_digit($id) && $id > 0) {

            //I don't know how you would gather the information, but I assume you
            //have a database with the information ready.

            //I assumed you have an `items` table
            $item = $this->Item->findById($id);

            $sessionid = "00988PPLO899223NHQQFA069F5434DB7EC2E34"; //$this->Session->...?
            $timeRange = "ALL";
            $userid = "24EH1725550099LLAOP3"; //$this->Auth->user('id')?

            if (!empty($item)) {
                $desc = $item['Item']['description'];
                $url = "/foods/view/".$id;
                $img = $item['Item']['img'];

                $viewResponse = ACME::SendAction("view", $id, $desc ,$url, $img, $sessionid, $userid);
                $this->set('food', $this->Food->read(null, $id));
            }else{
                $this->Session->setFlash(__('Invalid food', true));
                $this->redirect(array('action' => 'index'));
            }
        }else{
            $this->Session->setFlash(__('Invalid food', true));
            $this->redirect(array('action' => 'index'));
        }

    }

}
</code>```

Edit

The code has been filled up, and of course, without any warranty :). I personally don't really like to have long arguments in a function (like SendAction, error prune), rather use shorter one like the $params in ACME::BuildLink. But just to respect your code, I didn't modify much on the SendAction method.

Then I'm not too sure how you would make use of this code, so I assumed you have a ProductsController, and somehow the user trigger url like /products/send_action/. If you can provide more information, then we would be able to help out.

Edit Again

I have modified the ACME class, as well as the controller. Yea I do miss out some variables, but I had added them back to the updated code.

Not too sure if it would work (perhaps typo), you can just modify the code if it doesn't work for you.

And for personal conventions, I usually capitalize methods which are static, like ACME:GetRecommendations or ACME::SendAction.

Oh yea, I better stick back to the variables you used. Sorry for modifying them, just I don't like long names :)

And btw, the RoadRunner's ACME Corporation? Lol!

Cheers
Lionel

Body:
I have this library in PHP non-Cake format, the usual PHP scripting which currently works like a charm. I need to use this in a Cake framework. The library file is as follow: (example extracted)

<?php

// REST API functions

function sendAction($itemurl, $itemimageurl, $sessionid, $userid, $rating=""){

    global $someapiwebsiteURL, $apiKey, $tenantId;
    $somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.
                                                                 .....
                ................
    }

    //Codes extract

?>

I've come across a few ways of doing it. Currently confused, how am I going to place this library file into my Cake framework?

App::import()

Datasource

The functions in the library file above (I supposed it'd be used in one of my Controllers to render the data outputting through the view).

Currently working in a non-Cake framework structure, the view page is such as: (example extracted)

<?php
// my view page

$viewResponse = sendAction($itemdescription ,$itemurl , $itemimageurl,$sessionid,$userid);

//sample code only
?>

Both the files are working fine. The logic of putting it in a CakePHP framework is the problem here. Anyone may suggest "the" way of doing this without over-strenuously working on a data source? If we have to use a data source in App/models/datasources/, how exactly is the structure of it? Like, e.g., in datasource file, do we include the library functions? or is it some generic ReST datasource file which can be found here: CakePHP ReST datasource . I've gone through the cookbook chapter on datasource and understand we have to define the datasource in our database.php, but if someone is certain about their way of accomplishing it either using datasource or app::import() method, please share with more details?

UPDATE:

Hi Lionel!, thanks for filling up. Well, actually users will click on view action: function view (){} in my foods_controller. I'm appending some scripts here to include my view function in my foods_controller so maybe it may help you to help out easier. Thanks..

function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid food', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('food', $this->Food->read(null, $id));
    }

The view action triggers the send_action function, (each time a user clicks on view page on foods controller). So each time, a user clicks on view action, his (dynamic variables): userid, sessionid, that page's itemid, url, itemdescription; (timerange value is a static string value "ALL"), and if any (etc.), so far only these values are available: Will be used as the "parameters" in the Send Action function. What you wrote is close to what the codes can do. You're right. Except we should include the Send Action function inside the view() in foods controller?

If we look at dynamically filling in the variables mentioned in the point above, could you modify your second code (the code from your product_controller, e.g.) so it also works to receive the variables dynamically? (as you asked in the last update: how to get the parameters..)

Just to make it clear.

A user views the page. The send action collects data and send to the API. (as we've already done by calling the function in the library the (ACME.php). *just waiting for your update if possible, thanks.

In the function view() of the foods controller: there's also an additional calling. The (2)second calling which is this:

$recommendResponse = getRecommendations("otherusersviewed", $itemId, $userId);

The second calling calls the ACME.php library file in which there consists the (2)second function that retrieves data, here it is: (it's in working order, but just needs to be changed into a public static function like you did for the (1)first function. Could you help to modify this code too, please?:

function getRecommendations($recommendationType, $itemId, $userId){

    // sample code similar to the first one.
}

That's all to it. It seems quite simple in the normal PHP format, and it works easily, but getting  it on an MVC framweork is a bit challenging for some, a lot for me. Thanks for helping out, Lionel. :-)

P.S. Hi Lionel, I notice something missing in the library after changes? Look originally we have this:

$somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.

Look, the variables for $SomeWebsiteAPI and $SomeApiWebsiteURL are different. Did I miss out something? or you have modified so it is more efficient ? I see that the variable named $SomeWebsiteAPI is modified to become variable called $link ? and variable $SomeApiWebsiteURL is changed to the named variable, $url, am I right ? .. thanks.

Thanks, best regards. John Maxim

Body:
To me, if I have this piece of code, I would first wrap it into a static (or normal) class, and named it ACME, then I will move the acme.php into /apps/libs/acme.php. Then in the controller, I will use App::import('Lib', 'acme'). This action do nothing but just requiring the file, so you can just use it instantly by calling ACME::sendAction(...).

And regarding the global thing, you might just need to declare a static (or normal) class, then define the shared variables as part of the class properties, so you can share them among all the functions in the class.

For example, this is the /app/libs/acme.php

class ACME {

    private static $someapiwebsiteURL = "http://thewebsite/api/1.0/";
    private static $apiKey = "0010KIUMLA0PLQA665JJ";
    private static $tenantId = "THE_TENANT_NAME";

    /**
     * Simple builder to build links from array of $params
     *
     * @param string $url The api url
     * @param array $params The given parameters
     * @return string built url
     */
    private static function BuildLink($url="", $params=array()) {

        $link = $url;
        foreach($params as $k=>$v) {
            $link .= "&$k=$v";
        }

        //Replace the first & to ?
        $link = preg_replace("/&/", "?", $link, 1);

        //Not sure if we need URL encode here, please uncomment this
        //if the API could not work.
        //$link = urlencode($link);

        return $link;
    }

    public static function SendAction($action, $itemId, $itemdescription, $itemurl, $itemimageurl, $sessionid, $userid, $rating="") {

        $somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$action, array(
            "apikey"=>self::$apiKey,
            "sessionid"=>$sessionid,
            "userid"=>$userid,
            "tenantid"=>self::$tenantId,
            "itemid"=>$itemId,
            "itemdescription"=>$itemdescription,
            "itemurl"=>$itemurl,
            "itemimageurl"=>$itemimageurl,

            /**
             * Assuming your API smart enough to only use this value when
             * the action is "rate"
             */
            "ratingvalue"=>$rating
        ));

        $xml = simplexml_load_file($somewebsiteAPI);
        return $xml;
    }

    public static function GetRecommendations($recommendationType, $itemId, $userId) {
        $somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$recommendationType, array(
            'apikey'=>self::$apiKey,
            'tenantid'=>self::$tenantId,
            'itemid'=>$itemId,
            'userid'=>$userId
        ));

        $xml = simplexml_load_file($somewebsiteAPI);
        return $xml;
    }
}

And in your controller

App::import('Lib', 'acme');

class FoodController extends AppController {

    //Food is plural already I assume? You can just use
    //food, should be ok I think, else it will be weird
    //to use /foods/view/?
    var $name = "Food";
    var $uses = array("Item", "Food");

    function view($id="") {
        //We accepts only valid $id and $id > 0.
        //Take notes that this $id will be a string, not int.
        if (ctype_digit($id) && $id > 0) {

            //I don't know how you would gather the information, but I assume you
            //have a database with the information ready.

            //I assumed you have an `items` table
            $item = $this->Item->findById($id);

            $sessionid = "00988PPLO899223NHQQFA069F5434DB7EC2E34"; //$this->Session->...?
            $timeRange = "ALL";
            $userid = "24EH1725550099LLAOP3"; //$this->Auth->user('id')?

            if (!empty($item)) {
                $desc = $item['Item']['description'];
                $url = "/foods/view/".$id;
                $img = $item['Item']['img'];

                $viewResponse = ACME::SendAction("view", $id, $desc ,$url, $img, $sessionid, $userid);
                $this->set('food', $this->Food->read(null, $id));
            }else{
                $this->Session->setFlash(__('Invalid food', true));
                $this->redirect(array('action' => 'index'));
            }
        }else{
            $this->Session->setFlash(__('Invalid food', true));
            $this->redirect(array('action' => 'index'));
        }

    }

}

Edit

The code has been filled up, and of course, without any warranty :). I personally don't really like to have long arguments in a function (like SendAction, error prune), rather use shorter one like the $params in ACME::BuildLink. But just to respect your code, I didn't modify much on the SendAction method.

Then I'm not too sure how you would make use of this code, so I assumed you have a ProductsController, and somehow the user trigger url like /products/send_action/. If you can provide more information, then we would be able to help out.

Edit Again

I have modified the ACME class, as well as the controller. Yea I do miss out some variables, but I had added them back to the updated code.

Not too sure if it would work (perhaps typo), you can just modify the code if it doesn't work for you.

And for personal conventions, I usually capitalize methods which are static, like ACME:GetRecommendations or ACME::SendAction.

Oh yea, I better stick back to the variables you used. Sorry for modifying them, just I don't like long names :)

And btw, the RoadRunner's ACME Corporation? Lol!

Cheers
Lionel