问:
Create a SQLite view where a row depends on the previous row
I'd like to create a view in SQLite where a field in one row depends on the value of a field in the previous row. I could do this in Oracle using the LAG analytic function, but not sure how to go about it in SQLite.

For example, if my table looked like:

```<code>ITEM        DAY           PRICE
apple       2011-01-07    1.25
orange      2011-01-02    1.00
apple       2011-01-01    1.00
orange      2011-01-03    2.00
apple       2011-01-08    1.00
apple       2011-01-10    1.50
</code>```

I'd like my view to look like, with WHERE item = 'apple':

```<code>DAY           PRICE    CHANGE
2011-01-01    1.00     (null)
2011-01-07    1.25     0.25
2011-01-08    2.00     0.75
2011-01-10    1.50     -0.50
</code>```

Edit:

The equivalent of the query I'm looking for would look in Oracle something like (haven't tried this, but I think this is correct):

```<code>SELECT day, price,
       price - LAG( price, 1 ) OVER ( ORDER BY day ) AS change
  FROM mytable
 WHERE item = 'apple'
</code>```

答:
This should do the trick for every item (tested on SQLite):

```<code>SELECT
    day
    ,price
    ,price - (SELECT t2.price
              FROM mytable t2
              WHERE
                  t2.item = t1.item AND
                  t2.day < t1.day
              ORDER BY t2.day DESC
              LIMIT 1
             ) AS change
FROM mytable t1
</code>```

This assumes the combination between day and item is unique. And the way it works is by taking all the values less than the given day, sorting descending and then LIMIT just the first value, simulating a LAG function.

For a LEAD behavior, just flip < to > and DESC to ASC.

Body:
I'd like to create a view in SQLite where a field in one row depends on the value of a field in the previous row. I could do this in Oracle using the LAG analytic function, but not sure how to go about it in SQLite.

For example, if my table looked like:

ITEM        DAY           PRICE
apple       2011-01-07    1.25
orange      2011-01-02    1.00
apple       2011-01-01    1.00
orange      2011-01-03    2.00
apple       2011-01-08    1.00
apple       2011-01-10    1.50

I'd like my view to look like, with WHERE item = 'apple':

DAY           PRICE    CHANGE
2011-01-01    1.00     (null)
2011-01-07    1.25     0.25
2011-01-08    2.00     0.75
2011-01-10    1.50     -0.50

Edit:

The equivalent of the query I'm looking for would look in Oracle something like (haven't tried this, but I think this is correct):

SELECT day, price,
       price - LAG( price, 1 ) OVER ( ORDER BY day ) AS change
  FROM mytable
 WHERE item = 'apple'

Body:
This should do the trick for every item (tested on SQLite):

SELECT
    day
    ,price
    ,price - (SELECT t2.price
              FROM mytable t2
              WHERE
                  t2.item = t1.item AND
                  t2.day < t1.day
              ORDER BY t2.day DESC
              LIMIT 1
             ) AS change
FROM mytable t1

This assumes the combination between day and item is unique. And the way it works is by taking all the values less than the given day, sorting descending and then LIMIT just the first value, simulating a LAG function.

For a LEAD behavior, just flip < to > and DESC to ASC.


来源: stackexchange

问:
Extension methods in D?
Hey folks, I'm trying to get these bits of syntax to make sense to me:

```<code>S[] split(S)(S s) if (isSomeString!S)
{
    ...
}
</code>```

and

```<code>string join(in string[] words, string sep)
{
    ...
}
</code>```

(As seen in phobos/src/std/string.d)

As far as I can tell, this is the piece of code that lets us do stuff like:

```<code>string[] parts = "/foo/bar/baz".split("/"); // string[] {"foo", "bar", "baz"}
string part = parts.join("-"); // string "foo-bar-baz"
</code>```

Which basically makes me believe something like the extension methods I know from CSharp are possible in d. The problems I have are:

That I'm not 100% sure i'm looking at the right function declarations here

That I don't see what makes them similar.

答:
In D, any function which takes an array as its first argument can be called as if it were a member function of that array. And since strings are arrays, that would include strings. So, something like

```<code>T[] replace(in T[] array, in T[] from, in T[] to)
</code>```

can be called two different ways:

```<code>auto replacedStr1 = replace("hello world", "hello", "goodbye");
auto replacedStr2 = "hello world".replace("hello", "goodbye");
</code>```

This feature currently only works for arrays (IIRC, it came about due to a bug that allowed it, and it was decided that it was actually nice to have, so it was actually made a part of the language), but supposedly, at some point, it will be made to work for all types. Having it work for all types is called uniform function call syntax. With that implemented, you'd be able to do stuff like

```<code>auto bigger = 2.max(5);
</code>```

But as uniform function call syntax has not been implemented yet, you can only do that sort of thing with arrays. It's quite common for people to program that way with strings rather than passing them as the first argument to a function.

ContentLicense: CC BY-SA 2.5

Title: Extension methods in D?

Body:
Hey folks, I'm trying to get these bits of syntax to make sense to me:

S[] split(S)(S s) if (isSomeString!S)
{
    ...
}

and

string join(in string[] words, string sep)
{
    ...
}

(As seen in phobos/src/std/string.d)

As far as I can tell, this is the piece of code that lets us do stuff like:

string[] parts = "/foo/bar/baz".split("/"); // string[] {"foo", "bar", "baz"}
string part = parts.join("-"); // string "foo-bar-baz"

Which basically makes me believe something like the extension methods I know from CSharp are possible in d. The problems I have are:

That I'm not 100% sure i'm looking at the right function declarations here

That I don't see what makes them similar.

Body:
In D, any function which takes an array as its first argument can be called as if it were a member function of that array. And since strings are arrays, that would include strings. So, something like

T[] replace(in T[] array, in T[] from, in T[] to)

can be called two different ways:

auto replacedStr1 = replace("hello world", "hello", "goodbye");
auto replacedStr2 = "hello world".replace("hello", "goodbye");

This feature currently only works for arrays (IIRC, it came about due to a bug that allowed it, and it was decided that it was actually nice to have, so it was actually made a part of the language), but supposedly, at some point, it will be made to work for all types. Having it work for all types is called uniform function call syntax. With that implemented, you'd be able to do stuff like

auto bigger = 2.max(5);

But as uniform function call syntax has not been implemented yet, you can only do that sort of thing with arrays. It's quite common for people to program that way with strings rather than passing them as the first argument to a function.


问:
how to upload a file with size greater than 5mb to AWS in single upload operation

function uploadGuideMedia(req, res, next) {
    if (!req.file && !req.body.id) {
        return res.status(401).send({
            status: 401,
            data: "Upload a file with 'file' key"
        });
    }
    db.query('SELECT * from guide_media where _id = $1', [req.body.id], function(err, guide) {
        if (err) return next(err);
        if (guide.rows.length == 0) {
            return res.status(404).send({
                status: 404,
                data: "Guide_media not found"
            })
        } else {
            let name = req.file.path + path.extname(req.file.originalname);
            fs.renameSync(req.file.path, name);
            req.file.path = name;
            var s3bucket = new AWS.S3({
                params: {
                    Bucket: 'mapery-v2'
                }
            });
            fs.readFile(req.file.path, function(err, lq_file) {
                s3bucket.createBucket(function() {
                    var params = {
                        Key: 'upload-v2/' + req.file.originalname,
                        Body: lq_file,
                        ContentType: req.file.mimetype,
                        ACL: 'public-read'
                    };
                    s3bucket.upload(params, function(err, aws_images) {
                        fs.unlink(req.file.path, function(err) {
                            db.query('UPDATE guide_media SET image_path = $1 WHERE _id = $2  RETURNING *', [aws_images.Location, req.body.id], function(err, guide_res) {
                                if (err) return next(err);
                                return res.status(200).send({
                                    status: 'success',
                                    data: guide_res.rows
                                });
                            });
                        });
                    })
                })
            })
        }
    });
}```

I am trying to upload video files to the AWS, but when the size of a file is greater than 5mb it is uploading as a part(2 parts for 5mb and 3 parts for 10mb). But in this https://aws.amazon.com/s3/faqs/#How_much_data_can_I_store they said we can upload up to 5gb  in single upload operation. Am I wrong anywhere??

答:
Uploading in parts doesn't mean your file will be stored on S3 in multiple parts. If the payload is large enough, the SDK uploads the file in multiple parts concurrently so that uploads can be retried in parts if one of them fails. By default, the SDK uses a partSize of 5MB. You can set the partSize to 10 MB using the following code.

```<code>var params = {Bucket: 'bucket', Key: 'key', Body: stream};
var options = {partSize: 10 * 1024 * 1024, queueSize: 1};
s3.upload(params, options, function(err, data) {
  console.log(err, data);
});
</code>```

EDIT: Link to the documentation for the upload method.
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

ContentLicense: CC BY-SA 3.0

Body:
function uploadGuideMedia(req, res, next) {
    if (!req.file && !req.body.id) {
        return res.status(401).send({
            status: 401,
            data: "Upload a file with 'file' key"
        });
    }
    db.query('SELECT * from guide_media where _id = $1', [req.body.id], function(err, guide) {
        if (err) return next(err);
        if (guide.rows.length == 0) {
            return res.status(404).send({
                status: 404,
                data: "Guide_media not found"
            })
        } else {
            let name = req.file.path + path.extname(req.file.originalname);
            fs.renameSync(req.file.path, name);
            req.file.path = name;
            var s3bucket = new AWS.S3({
                params: {
                    Bucket: 'mapery-v2'
                }
            });
            fs.readFile(req.file.path, function(err, lq_file) {
                s3bucket.createBucket(function() {
                    var params = {
                        Key: 'upload-v2/' + req.file.originalname,
                        Body: lq_file,
                        ContentType: req.file.mimetype,
                        ACL: 'public-read'
                    };
                    s3bucket.upload(params, function(err, aws_images) {
                        fs.unlink(req.file.path, function(err) {
                            db.query('UPDATE guide_media SET image_path = $1 WHERE _id = $2  RETURNING *', [aws_images.Location, req.body.id], function(err, guide_res) {
                                if (err) return next(err);
                                return res.status(200).send({
                                    status: 'success',
                                    data: guide_res.rows
                                });
                            });
                        });
                    })
                })
            })
        }
    });
}

I am trying to upload video files to the AWS, but when the size of a file is greater than 5mb it is uploading as a part(2 parts for 5mb and 3 parts for 10mb). But in this https://aws.amazon.com/s3/faqs/#How_much_data_can_I_store they said we can upload up to 5gb  in single upload operation. Am I wrong anywhere??

Body:
Uploading in parts doesn't mean your file will be stored on S3 in multiple parts. If the payload is large enough, the SDK uploads the file in multiple parts concurrently so that uploads can be retried in parts if one of them fails. By default, the SDK uses a partSize of 5MB. You can set the partSize to 10 MB using the following code.

var params = {Bucket: 'bucket', Key: 'key', Body: stream};
var options = {partSize: 10 * 1024 * 1024, queueSize: 1};
s3.upload(params, options, function(err, data) {
  console.log(err, data);
});

EDIT: Link to the documentation for the upload method.
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property


问:
Java Multi Threading priority relation with start() method
My code and output are as below :-

My question is that the priority of main thread and thread t4 is 9 and that of thread t is 5 then why line 1 to 4 (marked in output) is coming before line 5 i.e. why t.start() gets priority over t4.start() which will be executed by main thread which has priority of 9.

Main thread priority is 9 so first t4.start() should get executed but then why t.start() is getting executed first ?

And if I reverse the order of calling start method i.e. if I call in order t4.start() and then t.start() then output is as expected.

Output

```<code>5

5

Main Thread Priority :9

5

Calling MyRunnable2 from main....9

Child Class                                - line 1

Child Class                                - line 2

End of Child loop                                - line 3

Calling MyRunnable2 from MyThread                - line 4

MyRunnable2 Class....Main....9                   - line 5

MyRunnable2 Class....From MyThread run....5
</code>```

CODE :-

```<code>public class ThreadPriority
{

    public static void main(String[] args)
    {
        MyThread t = new MyThread();
        System.out.println(Thread.currentThread().getPriority());
        System.out.println(t.getPriority());
        t.setName("From MyThread");

        Thread.currentThread().setPriority(9);

        System.out.println("Main Thread Priority :" + Thread.currentThread().getPriority());
        System.out.println(t.getPriority());

        MyRunnable2 r4 = new MyRunnable2();
        Thread t4 = new Thread(r4,"Main");
        System.out.println("Calling MyRunnable2 from main"+"...."+t4.getPriority());

        t.start();
        t4.start();
    }

}

class MyRunnable2 implements Runnable
{
    public void run()
    {
        System.out.println("MyRunnable2 Class"+"...."+Thread.currentThread().getName()+"...."+Thread.currentThread().getPriority());

    }
}
class MyThread extends Thread
{
    public void run()
    {
        for (int i=0;i<2;i++)
            System.out.println("Child Class");

        System.out.println("End of Child loop");

        MyRunnable2 r2 = new MyRunnable2();
        Thread t2 = new Thread(r2,"From MyThread run");
        System.out.println("Calling MyRunnable2 from MyThread");
        t2.start();

    }
</code>```

答:
The higher the integer, the higher the priority.
At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution.
Only when that thread stops, yields, or becomes not runnable for some reason will a lower priority thread start executing.

If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion.

Rule of thumb : At any given time, the highest priority thread is running. However, this is not a guaranteed. The thread scheduler may choose to run a lower priority thread to avoid starvation. For this reason, use priority only to affect scheduling policy for efficiency purposes. Do not rely on thread priority for algorithm correctness.

I hope the above information clarifies your query.

Body:
My code and output are as below :-

My question is that the priority of main thread and thread t4 is 9 and that of thread t is 5 then why line 1 to 4 (marked in output) is coming before line 5 i.e. why t.start() gets priority over t4.start() which will be executed by main thread which has priority of 9.

Main thread priority is 9 so first t4.start() should get executed but then why t.start() is getting executed first ?

And if I reverse the order of calling start method i.e. if I call in order t4.start() and then t.start() then output is as expected.

Output

5

5

Main Thread Priority :9

5

Calling MyRunnable2 from main....9

Child Class                                - line 1

Child Class                                - line 2

End of Child loop                                - line 3

Calling MyRunnable2 from MyThread                - line 4

MyRunnable2 Class....Main....9                   - line 5

MyRunnable2 Class....From MyThread run....5

CODE :-

public class ThreadPriority
{

    public static void main(String[] args)
    {
        MyThread t = new MyThread();
        System.out.println(Thread.currentThread().getPriority());
        System.out.println(t.getPriority());
        t.setName("From MyThread");

        Thread.currentThread().setPriority(9);

        System.out.println("Main Thread Priority :" + Thread.currentThread().getPriority());
        System.out.println(t.getPriority());

        MyRunnable2 r4 = new MyRunnable2();
        Thread t4 = new Thread(r4,"Main");
        System.out.println("Calling MyRunnable2 from main"+"...."+t4.getPriority());

        t.start();
        t4.start();
    }

}

class MyRunnable2 implements Runnable
{
    public void run()
    {
        System.out.println("MyRunnable2 Class"+"...."+Thread.currentThread().getName()+"...."+Thread.currentThread().getPriority());

    }
}
class MyThread extends Thread
{
    public void run()
    {
        for (int i=0;i<2;i++)
            System.out.println("Child Class");

        System.out.println("End of Child loop");

        MyRunnable2 r2 = new MyRunnable2();
        Thread t2 = new Thread(r2,"From MyThread run");
        System.out.println("Calling MyRunnable2 from MyThread");
        t2.start();

    }


问:
can't move image to a folder using move_uploaded_file function
I am a beginner in PHP. I am trying to move an image from tmp_name to my desired folder. the data has been successfully updated in the database. but the image is not moved to my img folder

```<code>Warning: move_uploaded_file(img/5a251bdf492fa.jpeg): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/phpdasar/pertemuan13/functions.php on line 113

Warning: move_uploaded_file(): Unable to move '/Applications/XAMPP/xamppfiles/temp/php6UtzgY' to 'img/5a251bdf492fa.jpeg' in /Applications/XAMPP/xamppfiles/htdocs/phpdasar/pertemuan13/functions.php on line 113
</code>```

I am using Mac, and I have tried to change the permission of all related folder to read & write (XAMPP folder, htdoc folder ....) , but it still didn't work.

what went wrong in here? Thanks in advance :)

答:
With the following error

Warning: move_uploaded_file(img/5a251bdf492fa.jpeg): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/phpdasar/pertemuan13/functions.php on line 113

I can assume that you have given the relative path for destination

You need to specify the absolute path to the function. move_uploaded_file()

The following line will help you

```<code>move_uploaded_file($file, dirname(__FILE__) . '/img/' . $file_name);
</code>```

move_uploaded_file never creates the folder itself, so you need to create the folder img manually.

Body:
I am a beginner in PHP. I am trying to move an image from tmp_name to my desired folder. the data has been successfully updated in the database. but the image is not moved to my img folder

Warning: move_uploaded_file(img/5a251bdf492fa.jpeg): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/phpdasar/pertemuan13/functions.php on line 113

Warning: move_uploaded_file(): Unable to move '/Applications/XAMPP/xamppfiles/temp/php6UtzgY' to 'img/5a251bdf492fa.jpeg' in /Applications/XAMPP/xamppfiles/htdocs/phpdasar/pertemuan13/functions.php on line 113

I am using Mac, and I have tried to change the permission of all related folder to read & write (XAMPP folder, htdoc folder ....) , but it still didn't work.

what went wrong in here? Thanks in advance :)

Body:
With the following error

Warning: move_uploaded_file(img/5a251bdf492fa.jpeg): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/phpdasar/pertemuan13/functions.php on line 113

I can assume that you have given the relative path for destination

You need to specify the absolute path to the function. move_uploaded_file()

The following line will help you

move_uploaded_file($file, dirname(__FILE__) . '/img/' . $file_name);

move_uploaded_file never creates the folder itself, so you need to create the folder img manually.


问:
How can I create dynamic labels using UIStackView
I have 10 UILabels with different sizes, and I want to arrange them in 3 rows, and all rows have leading alignment, and if the last item of each row can't fit in remaining space of parent view, it have to move to the next line. How can I do that by using UIStackview?

答:
You can try to do something like that:

Your ViewController

```<code>    for item in array {
        let someView = VPView(frame: CGRect(x: 0, y: 0, width: 70, height: 20))
        someView.translatesAutoresizingMaskIntoConstraints = false
        stackView.addArrangedSubview(someView)
    }
</code>```

UIView Class:

```<code>class VPView: UIView {

    let myLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addLabel()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func addLabels() {

        //Mark: - Styles
        let labelH: CGFloat = 15
        let labelW: CGFloat = 70

        //MARK: - My Label
        self.myLabel.frame = CGRect(x: 0, y: 0, width: labelW, height: labelH)
        self.myLabel.backgroundColor = UIColor.blue
        self.myLabel.textAlignment = NSTextAlignment.center
        self.myLabel.numberOfLines = 0
        self.addSubview(self.myLabel)

        self.myLabel.translatesAutoresizingMaskIntoConstraints = false
        self.myLabel.heightAnchor.constraint(equalToConstant: labelH).isActive = true
        self.myLabel.widthAnchor.constraint(equalToConstant: labelW).isActive = true
        self.myLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        self.myLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true

    }
}
</code>```

Body:
You can try to do something like that:

Your ViewController

    for item in array {
        let someView = VPView(frame: CGRect(x: 0, y: 0, width: 70, height: 20))
        someView.translatesAutoresizingMaskIntoConstraints = false
        stackView.addArrangedSubview(someView)
    }

UIView Class:

class VPView: UIView {

    let myLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addLabel()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func addLabels() {

        //Mark: - Styles
        let labelH: CGFloat = 15
        let labelW: CGFloat = 70

        //MARK: - My Label
        self.myLabel.frame = CGRect(x: 0, y: 0, width: labelW, height: labelH)
        self.myLabel.backgroundColor = UIColor.blue
        self.myLabel.textAlignment = NSTextAlignment.center
        self.myLabel.numberOfLines = 0
        self.addSubview(self.myLabel)

        self.myLabel.translatesAutoresizingMaskIntoConstraints = false
        self.myLabel.heightAnchor.constraint(equalToConstant: labelH).isActive = true
        self.myLabel.widthAnchor.constraint(equalToConstant: labelW).isActive = true
        self.myLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        self.myLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true

    }
}


问:
ASP.NET MVC5 Razor Refresh modal dialog
I'm tryin' to get actual time in modal dialog every time a user press the Order button.

```<code><a class="btn btn-primary" data-toggle="modal" data-target="#OrderModal">@MEDONET.Language.Doctor.Texts.Order</a>
</code>```

So every time he do this in the modal div OrderModal

```<code><div id="OrderModal" class="modal fade" role="dialog">
    @Html.Action("CreateOrderForm", Model.CreateOrderVM)
</div>
</code>```

Which calls to CreateOrderForm action

```<code>public ActionResult CreateOrderForm(CreateOrderVM createOrderVM)
    {
        createOrderVM.Minute = DateTime.Now.Minute.ToString().PadLeft(2, '0');
        return View("CreateOrderForm", createOrderVM);
    }
</code>```

So that action is actually running every time and calls CreateOrderForm.cshtml file

```<code>@{
Layout = null;
}
@model MEDONET.Models.CreateOrderVM

<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title text-center">Order To Line</h4>
    </div>
    <div class="modal-body">
        @using (Html.BeginForm("CreateOrder", "Doctors", FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.DoctorId)
            <div class="row text-center">
                <p>Date & Time</p>
                @Html.Label("Year")
                @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Year } })<br />
                @Html.Label("Month")
                @Html.EditorFor(model => model.Month, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Month } })<br />
                @Html.Label("Day")
                @Html.EditorFor(model => model.Day, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Day } })<br />
                @Html.Label("Hour")
                @Html.EditorFor(model => model.Hour, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Hour } })<br />
                @Html.Label("Minute")
                @Html.EditorFor(model => model.Minute, new { htmlAttributes = new { @class = "form-control" } })<br />
                @if (this.User.IsInRole("Registrator"))
                {
                    @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })<br />
                }
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
        }
    </div>
    <div class="modal-footer">

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

BUT! The popup fields are still filled with the first time given while parent page loading.

How can I give a user new time every time he press the Order button?

答:
Razor code is executed only once, when page loads first time. After that, each time you toggle the modal popup, it just show/hide the same HTML. The solution would be to update the HTML, once you click the button to open the Modal. You can use JQuery's load() method to achieve this.

First you need to use JavaScript to toggle the Modal instead of HTML. Modify your button like below

```<code><a class="btn btn-primary" id="openModal">@MEDONET.Language.Doctor.Texts.Order</a>
</code>```

In JavaScript, add the event handler for this button like below

```<code>$('#openModal').on('click', function() {
  ...
})
</code>```

Then, load the content of child action.

```<code>$('#openModal').on('click', function() {
  $("#OrderModal").load("@Url.Action("CreateOrderForm", "ControllerName")", function() {
    $('#OrderModal').modal('show')
  });
})
</code>```

I haven't tested above code, and it may need few typo correction. Let me know, if it doesn't work.

Title: ASP.NET MVC5 Razor Refresh modal dialog

Body:
I'm tryin' to get actual time in modal dialog every time a user press the Order button.

@MEDONET.Language.Doctor.Texts.Order

So every time he do this in the modal div OrderModal

    @Html.Action("CreateOrderForm", Model.CreateOrderVM)

Which calls to CreateOrderForm action

public ActionResult CreateOrderForm(CreateOrderVM createOrderVM)
    {
        createOrderVM.Minute = DateTime.Now.Minute.ToString().PadLeft(2, '0');
        return View("CreateOrderForm", createOrderVM);
    }

So that action is actually running every time and calls CreateOrderForm.cshtml file

@{
Layout = null;
}
@model MEDONET.Models.CreateOrderVM

        <button type="button" class="close" data-dismiss="modal">×</button>

Order To Line

        @using (Html.BeginForm("CreateOrder", "Doctors", FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.DoctorId)

Date & Time

                @Html.Label("Year")
                @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Year } })

                @Html.Label("Month")
                @Html.EditorFor(model => model.Month, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Month } })

                @Html.Label("Day")
                @Html.EditorFor(model => model.Day, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Day } })

                @Html.Label("Hour")
                @Html.EditorFor(model => model.Hour, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Hour } })

                @Html.Label("Minute")
                @Html.EditorFor(model => model.Minute, new { htmlAttributes = new { @class = "form-control" } })

                @if (this.User.IsInRole("Registrator"))
                {
                    @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })

                }
                <button type="submit" class="btn btn-default">Submit</button>

        }

BUT! The popup fields are still filled with the first time given while parent page loading.

How can I give a user new time every time he press the Order button?

Body:
Razor code is executed only once, when page loads first time. After that, each time you toggle the modal popup, it just show/hide the same HTML. The solution would be to update the HTML, once you click the button to open the Modal. You can use JQuery's load() method to achieve this.

First you need to use JavaScript to toggle the Modal instead of HTML. Modify your button like below

<a class="btn btn-primary" id="openModal">@MEDONET.Language.Doctor.Texts.Order</a>

In JavaScript, add the event handler for this button like below

$('#openModal').on('click', function() {
  ...
})

Then, load the content of child action.

$('#openModal').on('click', function() {
  $("#OrderModal").load("@Url.Action("CreateOrderForm", "ControllerName")", function() {
    $('#OrderModal').modal('show')
  });
})

I haven't tested above code, and it may need few typo correction. Let me know, if it doesn't work.


问:
How to check whether particular user_id is present in user_id field in mongodb
What want to write a query to check if user_id=10 is exists in mongodb. If user_id=10 already exists, then edit its other fields. If it does not exist, then insert user_id=10 along with other fields.
I am using meteor js.

Below is the code:

```<code>Meteor.methods({
'dbs.update'(user_id,name,add)
{
if (Dbs.find){user_id:user_id}))
{
if(typeof name !=="undefined" && name)
{
Dbs.update({user_id:user_id},{$set: {name: name}});
}
if(typeof add !=="undefined" && add)
{
 Dbs.update({user_id:user_id},{$set: {add:add}});
}
}
else
{
Dbs.insert({user_id:user_idname:name,add:add});
}
}
</code>```

With this code i am  able to update existing records.but not able to insert new records if not existing.
db.collection.find({ "user_id" : { $exists : true}}):checks for  field user_id is present or not.So is there any query to check particular id/value exists in field user_id ?

答:
Going by your latest comment, the below should work.</p>

```<code>Meteor.methods({
    'dbs.update' (user_id, name, add) {

        // find at least one doc which contains the user_id passed.
        var getUserDocument = Dbs.findOne({
            user_id: user_id
        });

        if (getUserDocument) { // if there exists a document with the given user_id

            // do your update stuff here

        } else { // if no doc has been found with user_id (which means that getUserDocument will be undefined)

            //do your insert.
            Dbs.insert({
                user_id: user_id,
                name: name,
                add: add
            });
        }
    }
});
</code>```

Body:
What want to write a query to check if user_id=10 is exists in mongodb. If user_id=10 already exists, then edit its other fields. If it does not exist, then insert user_id=10 along with other fields.
I am using meteor js.

Below is the code:

Meteor.methods({
'dbs.update'(user_id,name,add)
{
if (Dbs.find){user_id:user_id}))
{
if(typeof name !=="undefined" && name)
{
Dbs.update({user_id:user_id},{$set: {name: name}});
}
if(typeof add !=="undefined" && add)
{
 Dbs.update({user_id:user_id},{$set: {add:add}});
}
}
else
{
Dbs.insert({user_id:user_idname:name,add:add});
}
}

With this code i am  able to update existing records.but not able to insert new records if not existing.
db.collection.find({ "user_id" : { $exists : true}}):checks for  field user_id is present or not.So is there any query to check particular id/value exists in field user_id ?

Body:
Going by your latest comment, the below should work.

Meteor.methods({
    'dbs.update' (user_id, name, add) {

        // find at least one doc which contains the user_id passed.
        var getUserDocument = Dbs.findOne({
            user_id: user_id
        });

        if (getUserDocument) { // if there exists a document with the given user_id

            // do your update stuff here

        } else { // if no doc has been found with user_id (which means that getUserDocument will be undefined)

            //do your insert.
            Dbs.insert({
                user_id: user_id,
                name: name,
                add: add
            });
        }
    }
});


问:
What are the best practices for returning errors from functions?
I usually do something like the example below when I need to return error messages from a function, if no errors occur I just return an empyty string. Is this best practice, or are there alternatve ways of returning error messages from functions?</p>

```<code>Function Test() as String
  ' Do something
  If error occured Then
    Return "Some error message"
  Else
    Return ""
End Functon
</code>```

答:
A Request-Response pattern can help with handling errors and the many ways something might fail. For example, in a credit card authentication procedure you might have:

```<code>class CreditCardAuthenticationRequest {
    string CreditCardNumber;
    string FullName;
    ...
}

class CreditCardAuthenticationResponse {
    CreditProcessorStatusCode Status;
    CreditProcessorWarnings[] Warnings;
    CreditProcessorErrors[] Errors;
    Exception Exception;
    ...
}
</code>```

Now suddenly all your error handling and validation can be contained in a neat little package. The Patterns in Action sample application from DoFactory.com uses this extensively.

OwnerDisplayName: Sean Taylor

Body:
I usually do something like the example below when I need to return error messages from a function, if no errors occur I just return an empyty string. Is this best practice, or are there alternatve ways of returning error messages from functions?

Function Test() as String
  ' Do something
  If error occured Then
    Return "Some error message"
  Else
    Return ""
End Functon

Body:
A Request-Response pattern can help with handling errors and the many ways something might fail. For example, in a credit card authentication procedure you might have:

class CreditCardAuthenticationRequest {
    string CreditCardNumber;
    string FullName;
    ...
}

class CreditCardAuthenticationResponse {
    CreditProcessorStatusCode Status;
    CreditProcessorWarnings[] Warnings;
    CreditProcessorErrors[] Errors;
    Exception Exception;
    ...
}

Now suddenly all your error handling and validation can be contained in a neat little package. The Patterns in Action sample application from DoFactory.com uses this extensively.

OwnerDisplayName: David Thomas Garcia


问:
explain how to use this specific function of foldl
```<code> sum :: (Num a) => [a] -> a
 sum xs = foldl (\acc x -> acc + x) 0 xs
</code>```

foldl is folds the list up from the left side. So first we get the acc=0 and put the list xs to x ,then doing the function ->acc+x.After calculation, we get the new acc which is equal to acc+x. But why is that? I think this result of acc+x is the new value of x based on the function x->acc+x.

答:
From your question, it sounds like you don't understand how the lambda function (\acc x -> acc + x) works here.

The function is not x->acc+x, but acc x->acc + x. In fact, you could rewrite the "sum" equation as

```<code>sum xs = foldl (+) 0 xs
</code>```

Since (\acc x -> acc + x) is the same as (+)

I suggest you (re)read http://learnyouahaskell.com/higher-order-functions#lambdas

Body:
 sum :: (Num a) => [a] -> a
 sum xs = foldl (\acc x -> acc + x) 0 xs

foldl is folds the list up from the left side. So first we get the acc=0 and put the list xs to x ,then doing the function ->acc+x.After calculation, we get the new acc which is equal to acc+x. But why is that? I think this result of acc+x is the new value of x based on the function x->acc+x.

Body:
From your question, it sounds like you don't understand how the lambda function (\acc x -> acc + x) works here.

The function is not x->acc+x, but acc x->acc + x. In fact, you could rewrite the "sum" equation as

sum xs = foldl (+) 0 xs

Since (\acc x -> acc + x) is the same as (+)

I suggest you (re)read http://learnyouahaskell.com/higher-order-functions#lambdas


问:
Bootstrap dropdown tab not working
I have a dropdown to switch between panes for the selected item in the dropdown.
Normally it would switch panes when I press on the item from the dropdown but since the new bootstrap version (4.0.0-beta.2) it doesn't respond anymore and it leaves me with a tab.js:155 Uncaught TypeError: Cannot read property 'nodeName' of undefined error.

JSFiddle

```<code><div class="tab-pane fade show active" id="adventure" role="tabpanel" aria-labelledby="adventure-tab">
   <div class="card" style="">
      <div class="tab-content">
         <div class="tab-pane fade show active" id="large-clipper" aria-labelledby="large-clipper-tab">
            <div class="card-header">
               <div class="dropdown btn-group float-right">
                  <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  Variations
                  </button>
                  <div class="dropdown-menu" role="tablist" aria-labelledby="dropdownMenuButton">
                     <a class="dropdown-item nav-link" id="large-clipper-tab" href="#large-clipper" data-toggle="tab" role="tab" aria-controls="large-clipper" aria-selected="false">Large Clipper</a>
                     <a class="dropdown-item nav-link" id="festive-large-clipper-tab" href="#festive-large-clipper" data-toggle="tab" role="tab" aria-controls="festive-large-clipper" aria-selected="false">Festive Large Clipper</a>
                  </div>
               </div>
               <img src="http://eversong.ivyro.net/SHIP/00000024.png" height="50" width="50">
               <h4 style="display:inline-block">Large Clipper</h4>
            </div>
            <div class="card-body">
               <h6 class="text-muted">
                  Just a big and fast clipper.
               </h6>
               <p class=" p-y-1">
                  <span style="font-style:italic">Level requirements: </span>
                  <span>Adventure: 30 </span>
                  <span>Trade: 56 </span>
                  <span>Maritime: 75</span>
               </p>
               <div class="row">
                  <div class="col-md-6"><a class="btn btn-primary btn-lg btn-block my-1" href="">Selling: <span>5</span> </a></div>
                  <div class="col-md-6"><a class="btn btn-primary btn-lg btn-block my-1" href="">Buying: <span>10</span> </a></div>
               </div>
            </div>
         </div>
         <div class="tab-pane fade" id="festive-large-clipper"  role="tabpanel" aria-labelledby="large-clipper-tab">
            <div class="card-header">
               <div class="btn-group float-right">
                  <button class="btn btn-primary dropdown-toggle" id="variationsDropdown" type="button" aria-haspopup="true" aria-expanded="true" data-toggle="dropdown"> Variations </button>
                  <div class="dropdown-menu" aria-labelledby="variationsDropdown">
                     <a class="dropdown-item" href="#large-clipper" data-toggle="tab">Large Clipper</a>
                     <a class="dropdown-item" href="#festive-large-clipper" data-toggle="tab">Festive Large Clipper</a>
                  </div>
               </div>
               <img src="http://eversong.ivyro.net/SHIP/00000024.png" height="50" width="50">
               <h4 style="display:inline-block">Festive Large Clipper</h4>
            </div>
            <div class="card-body">
               <h6 class="text-muted">
                  A large clipper but with fancy plating.
               </h6>
               <p class=" p-y-1">
                  <span style="font-style:italic">Level requirements: </span>
                  <span>Adventure: 30 </span>
                  <span>Trade: 56 </span>
                  <span>Maritime: 75</span>
               </p>
               <div class="row">
                  <div class="col-md-6"><a class="btn btn-primary btn-lg btn-block my-1" href="">Selling: <span>5</span> </a></div>
                  <div class="col-md-6"><a class="btn btn-primary btn-lg btn-block my-1" href="">Buying: <span>10</span> </a></div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
</code>```

Required files

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

答: There is a bug with tabs in v4 beta 2, this will be fixed in beta 3, see https://github.com/twbs/bootstrap/pull/23087</p>

Title: Bootstrap dropdown tab not working

Body:
I have a dropdown to switch between panes for the selected item in the dropdown.
Normally it would switch panes when I press on the item from the dropdown but since the new bootstrap version (4.0.0-beta.2) it doesn't respond anymore and it leaves me with a tab.js:155 Uncaught TypeError: Cannot read property 'nodeName' of undefined error.

JSFiddle

                  <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  Variations
                  </button>

                     Large Clipper
                     Festive Large Clipper

Large Clipper

                  Just a big and fast clipper.

                  Level requirements:
                  Adventure: 30
                  Trade: 56
                  Maritime: 75

Selling: 5

Buying: 10

                  <button class="btn btn-primary dropdown-toggle" id="variationsDropdown" type="button" aria-haspopup="true" aria-expanded="true" data-toggle="dropdown"> Variations </button>

                     Large Clipper
                     Festive Large Clipper

Festive Large Clipper

                  A large clipper but with fancy plating.

                  Level requirements:
                  Adventure: 30
                  Trade: 56
                  Maritime: 75

Selling: 5

Buying: 10

Required files

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">


问:
Update Chart JS with date range selector
I am trying to update a chart depending on the dates and and shifts selected using ajax. My ajax call returns an array like this:

```<code>0
date    "2017-11-20"
shift   "Day Shift"
availability    100
1
date    "2017-11-21"
shift   "Day Shift"
availability    63.63636363636363
2
date    "2017-11-22"
shift   "Day Shift"
availability    63.63636363636363
3
date    "2017-11-23"
shift   "Day Shift"
availability    63.63636363636363
4
date    "2017-11-24"
shift   "Day Shift"
availability    14.285714285714285
5
date    "2017-11-20"
shift   "Night Shift"
availability    67.56756756756756
6
date    "2017-11-21"
shift   "Night Shift"
availability    67.56756756756756
7
date    "2017-11-22"
shift   "Night Shift"
availability    67.56756756756756
8
date    "2017-11-23"
shift   "Night Shift"
availability    67.56756756756756
</code>```

my javascript looks like this:

```<code>// on change event
var request;
$('input').on('change', function(event) {
    console.log('changed');
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }

    var rangeStart = moment($('#daterange').data('daterangepicker').startDate).unix();
    var rangeEnd = moment($('#daterange').data('daterangepicker').endDate).unix();
    var shift = 'all';
    request = $.ajax({
        url: "report_availability.php",
        type: "post",
        data: {
            rangeStart: rangeStart,
            rangeEnd: rangeEnd,
            shift: shift
        }
    });

    request.done(function (response, textStatus){
        drawChart(response);
    });

    request.fail(function (textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    request.always(function () {
       console.log('request finished');
    });
});

function drawChart(data) {
    var dates = [];
    var shift1Score = [];
    var shift2Score = [];
    for(var i in data) {
        var found = jQuery.inArray(data[i].date, dates);
        if (found < 0) {
            dates.push(data[i].date);
        }
         if(data[i].shift == 'Day Shift' ) {
            shift1Score.push(data[i].availability);
        } else {
            shift2Score.push(data[i].availability);
        }
     }

    // Destroy the chart if it already exists
    // NOT WORKING
    if(myChart!=null){
        myChart.destroy();
        console.log('destroy');
    }

    var ctx = document.getElementById("myChart").getContext('2d');
    ctx.canvas.height = 50;
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dates,
            datasets: [
            {
                label: "Day Shift",
                backgroundColor: "#3e95cd",
                data: shift1Score
            }, {
                label: "Night Shift",
                backgroundColor: "#8e5ea2",
                data: shift2Score
            }
          ]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            },
            responsive: true,
            maintainAspectRatio: false
        }
    });
 }
</code>```

I have 2 problems with this:

problem 1: The chart is not being destroyed so when I redraw it, it just redraws on top of the old chart which causes problems with the hover events. I have tried to use chart.update() to resolve this issue however this seems to just add to the original data instead of replacing it.

EDIT:- I have solved problem 1 by removing the canvas and then creating a new canvas:-

```<code>$('#myChart').remove();
$('#chartBar').append('<canvas id="myChart"></canvas>');
</code>```

Problem 2: There is more than 2 shifts.. sometime upto 5 and I do not want to hard code all of these. I would like to draw each dataset depending on how many shifts are returned in the array, I am open to changing the array structure in php or javascript but just cannot seem to figure out the correct array structrue or how to build a dynamic dataset array for the chart.

the chart should output like this for 2 shifts:

Any help would be great thanks

答:
I had the same problem that you have.

In order to update the graph i am using two functions:

Remove all datasets in current graph:

```<code>function removeDataset(chart) {
   chart.data.datasets = [];
};
</code>```

Add a new dataset to the graph:

```<code>function addDataset(chart, name, data, background, border, fill) {
    var newDataset = {
        label: name,
        data: [],
        backgroundColor: background,
        borderColor: border,
        fill: fill
    };
    for (var index = 0; index < data.length; ++index) {
        newDataset.data.push(data[index]);
    }
    chart.data.datasets.push(newDataset);
};
</code>```

So, when i have the ajax done, i use like this:

```<code>removeDataset(ctx1);
addDataset(ctx1, "Dataset Name", resp.dataset_data_json, "#007bff", "#007bff", true);
ctx1.update();
</code>```

To declare the graph, i use:

```<code>var ctx1;
$(document).ready(function () {
    var canvas1 = $("#canvas1")[0];
    canvas1.height = "300";
    ctx1 = new Chart(canvas1, config_ctx1);
});
</code>```

I hope it helps.

Body:
I am trying to update a chart depending on the dates and and shifts selected using ajax. My ajax call returns an array like this:

0
date    "2017-11-20"
shift   "Day Shift"
availability    100
1
date    "2017-11-21"
shift   "Day Shift"
availability    63.63636363636363
2
date    "2017-11-22"
shift   "Day Shift"
availability    63.63636363636363
3
date    "2017-11-23"
shift   "Day Shift"
availability    63.63636363636363
4
date    "2017-11-24"
shift   "Day Shift"
availability    14.285714285714285
5
date    "2017-11-20"
shift   "Night Shift"
availability    67.56756756756756
6
date    "2017-11-21"
shift   "Night Shift"
availability    67.56756756756756
7
date    "2017-11-22"
shift   "Night Shift"
availability    67.56756756756756
8
date    "2017-11-23"
shift   "Night Shift"
availability    67.56756756756756

my javascript looks like this:

// on change event
var request;
$('input').on('change', function(event) {
    console.log('changed');
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }

    var rangeStart = moment($('#daterange').data('daterangepicker').startDate).unix();
    var rangeEnd = moment($('#daterange').data('daterangepicker').endDate).unix();
    var shift = 'all';
    request = $.ajax({
        url: "report_availability.php",
        type: "post",
        data: {
            rangeStart: rangeStart,
            rangeEnd: rangeEnd,
            shift: shift
        }
    });

    request.done(function (response, textStatus){
        drawChart(response);
    });

    request.fail(function (textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    request.always(function () {
       console.log('request finished');
    });
});

function drawChart(data) {
    var dates = [];
    var shift1Score = [];
    var shift2Score = [];
    for(var i in data) {
        var found = jQuery.inArray(data[i].date, dates);
        if (found < 0) {
            dates.push(data[i].date);
        }
         if(data[i].shift == 'Day Shift' ) {
            shift1Score.push(data[i].availability);
        } else {
            shift2Score.push(data[i].availability);
        }
     }

    // Destroy the chart if it already exists
    // NOT WORKING
    if(myChart!=null){
        myChart.destroy();
        console.log('destroy');
    }

    var ctx = document.getElementById("myChart").getContext('2d');
    ctx.canvas.height = 50;
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dates,
            datasets: [
            {
                label: "Day Shift",
                backgroundColor: "#3e95cd",
                data: shift1Score
            }, {
                label: "Night Shift",
                backgroundColor: "#8e5ea2",
                data: shift2Score
            }
          ]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            },
            responsive: true,
            maintainAspectRatio: false
        }
    });
 }

I have 2 problems with this:

problem 1: The chart is not being destroyed so when I redraw it, it just redraws on top of the old chart which causes problems with the hover events. I have tried to use chart.update() to resolve this issue however this seems to just add to the original data instead of replacing it.

EDIT:- I have solved problem 1 by removing the canvas and then creating a new canvas:-

$('#myChart').remove();
$('#chartBar').append('<canvas id="myChart"></canvas>');

Problem 2: There is more than 2 shifts.. sometime upto 5 and I do not want to hard code all of these. I would like to draw each dataset depending on how many shifts are returned in the array, I am open to changing the array structure in php or javascript but just cannot seem to figure out the correct array structrue or how to build a dynamic dataset array for the chart.

the chart should output like this for 2 shifts:

Any help would be great thanks

Body:
I had the same problem that you have.

In order to update the graph i am using two functions:

Remove all datasets in current graph:

function removeDataset(chart) {
   chart.data.datasets = [];
};

Add a new dataset to the graph:

function addDataset(chart, name, data, background, border, fill) {
    var newDataset = {
        label: name,
        data: [],
        backgroundColor: background,
        borderColor: border,
        fill: fill
    };
    for (var index = 0; index < data.length; ++index) {
        newDataset.data.push(data[index]);
    }
    chart.data.datasets.push(newDataset);
};

So, when i have the ajax done, i use like this:

removeDataset(ctx1);
addDataset(ctx1, "Dataset Name", resp.dataset_data_json, "#007bff", "#007bff", true);
ctx1.update();

To declare the graph, i use:

var ctx1;
$(document).ready(function () {
    var canvas1 = $("#canvas1")[0];
    canvas1.height = "300";
    ctx1 = new Chart(canvas1, config_ctx1);
});

I hope it helps.


问:
How can I search data from firebase in android
I'm doing my project.
My project is App for finding room in my campus.
In my database there are room name, floor, building room and location.

I want to find all records that have a keyword that the user want to find.
And show data about that room.

My firebase

答:
Change your firebase url to
"YourFireBaseUrl/room/cb1201" to get the data of room no cb1201
you will get the data in JSON format


问:
CSS grid - hide a grid-area on click of a button
I'm trying to create a sidenav that can be shown/hidden on a button click.
I have used grid-area and grid-template-areas for the layout.
I have a grid-area for sidenav. I want the grid-area also to be hidden when the sidenav is hidden. Is it possible to achieve this?

The full code is here - https://codepen.io/devi_ks/pen/Ebddwo

$("a").on("click", function() {
  $("#sidenav").hide();
  return false;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#header {
  grid-area: header;
  border: 1px solid red;
}

#sidenav {
  grid-area: sidenav;
  border: 1px solid green;
}

#content {
  grid-area: content;
  border: 1px solid black;
}

body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 0.5fr 2fr;
  grid-template-areas: "header header" "sidenav content"
}</code>```

  Click me

 menu 1

 menu 2

 menu 3

  Some content goes here....

```

答:
You use grid-area, so the place for the side nav is allocated at start. If you hide (or even delete) the side nav, that won't change anything about this. You have to do a little trick:

Set the width for the first column to 0 and change the grid-gap because otherwise you will have a (not needed) gap at the left.

```<code>$("a").on("click", function() {
  $("#sidenav").hide(true);
  $("body").css("grid-template-columns", "0px 2fr");
  $("body").css("grid-gap", "10px 0px");
  return false;
});
</code>```

Body:
I'm trying to create a sidenav that can be shown/hidden on a button click.
I have used grid-area and grid-template-areas for the layout.
I have a grid-area for sidenav. I want the grid-area also to be hidden when the sidenav is hidden. Is it possible to achieve this?

The full code is here - https://codepen.io/devi_ks/pen/Ebddwo

$("a").on("click", function() {
  $("#sidenav").hide();
  return false;
});

#header {
  grid-area: header;
  border: 1px solid red;
}

#sidenav {
  grid-area: sidenav;
  border: 1px solid green;
}

#content {
  grid-area: content;
  border: 1px solid black;
}

body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 0.5fr 2fr;
  grid-template-areas: "header header" "sidenav content"
}

  Click me

 menu 1

 menu 2

 menu 3

  Some content goes here....

Body:
You use grid-area, so the place for the side nav is allocated at start. If you hide (or even delete) the side nav, that won't change anything about this. You have to do a little trick:

Set the width for the first column to 0 and change the grid-gap because otherwise you will have a (not needed) gap at the left.

$("a").on("click", function() {
  $("#sidenav").hide(true);
  $("body").css("grid-template-columns", "0px 2fr");
  $("body").css("grid-gap", "10px 0px");
  return false;
});

ContentLicense: CC BY-SA 4.0


问:
Unresolved reference issue in PyCharm
I have a directory structure

```<code>├── simulate.py
├── src
│   ├── networkAlgorithm.py
│   ├── ...
</code>```

And I can access the network module with sys.path.insert().

```<code>import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *
</code>```

However, pycharm complains that it cannot access the module. How can I teach pycham to resolve the reference?

答: Pycharm uses venv. In the venv's console you should install the packages explicitly or go in settings -> project interpreter -> add interpreter -> inherit global site-packages.

Title: Unresolved reference issue in PyCharm

Body:
I have a directory structure

├── simulate.py
├── src
│   ├── networkAlgorithm.py
│   ├── ...

And I can access the network module with sys.path.insert().

import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *

However, pycharm complains that it cannot access the module. How can I teach pycham to resolve the reference?


问:
style.display:none turns out to be little dots
I'm trying to accomplish a image gallery sliding function.
I have 8 images in total, one div(image gallery) which can only contain 4 images, 2 buttons on the both sides of the div(image gallery) which can allow you to click to show the next/previous 4 images.
The images path are populated from database by php and the sliding function is accomplished by javascript(style.display:block & style.display:none).
My problem is why I'm getting 4 small dots on the second page of my gallery? How can I get rid of them? Thanks for help!
Here is html code for my gallery:

```<code><div class="galleryOuter">
<button class="previous" onclick="showImage(-4)"></button>
<button class="next" onclick="showImage(4)"></button>
<p class="gallery_title">Editor's Choice</p>
<?php
$array=LoadingImages();
foreach($array as $value){
echo"<div class='gallery'>";
echo"<a target='_self' href='#'>";
settype($value['album_id'],"string");
echo"<img class='album_images' src='Images/album/".$value['album_id'].".png' width='330' height='320'>";
echo"</a>";
echo"<div class='desc'>".$value['artist_name']."</div>";
echo"</div>";
}
?>
</div>
</code>```

Here is the CSS code:

```<code>/*Image Gallery*/
div.gallery{
display:inline-block;
margin:0px 15px 30px 15px;
border:2px solid #999999;
background-color:#fff;
}
div.desc{
font-size:20px;
padding:5px;
text-align:center;
}
div.galleryOuter{
width:101%;
height:50%;
background-color:rgba(242, 242, 242,0.3);
text-align:center;
margin-top:100px;
overflow:hidden;
margin-left:-7px;
min-width:1700px;
overflow:hidden;
}
.galleryOuter:hover{
background-color:rgba(242, 242, 242,0.4);
}
div.gallery:hover{
border:2px solid #ccc;
}
p.gallery_title{
font-size:25px;
}
/*Slider Button*/
.previous{
float:left;
height:475px;
width:50px;
background-size:30px;
background-image:url('Images/icons/leftarrow.png');
background-position:center;
background-repeat:no-repeat;
background-color:rgba(242, 242, 242,0.4);
outline:none;
border:none;
cursor:pointer;
}
.next{
float:right;
height:475px;
width:50px;
background-size:30px;
background-image:url('Images/icons/rightarrow.png');
background-position:center;
background-repeat:no-repeat;
background-color:rgba(242, 242, 242,0.4);
outline:none;
border:none;
cursor:pointer;
}
.previous:hover,.next:hover{
background-color:rgba(242, 242, 242,0.7);
}
</code>```

Here is the javascript:

```<code>function showImage(input_value){
var first_image_index=0;
var first_image_index_af=first_image_index+input_value;
var x=document.getElementsByClassName("album_images");
var y=document.getElementsByClassName("desc");
if(first_image_index_af<0){first_image_index_af=0;}
if(first_image_index_af>4){first_image_index_af=4;}
for(i=0;i<4;i++){
x[first_image_index_af+i].style.display="block";
y[first_image_index_af+i].style.display="block";
x[7-(first_image_index_af+i)].style.display="none";
y[7-(first_image_index_af+i)].style.display="none";
}
}
</code>```

答: The problem is sloved. The right solution is to comment the border css in the div called 'gallery'. It seems that style.display:none applied on border properties will turn out to be dots.</p>

Body:
I'm trying to accomplish a image gallery sliding function.
I have 8 images in total, one div(image gallery) which can only contain 4 images, 2 buttons on the both sides of the div(image gallery) which can allow you to click to show the next/previous 4 images.
The images path are populated from database by php and the sliding function is accomplished by javascript(style.display:block & style.display:none).
My problem is why I'm getting 4 small dots on the second page of my gallery? How can I get rid of them? Thanks for help!
Here is html code for my gallery:

<button class="previous" onclick="showImage(-4)"></button>
<button class="next" onclick="showImage(4)"></button>

Editor's Choice

<?php
$array=LoadingImages();
foreach($array as $value){
echo"
";
echo"";
settype($value['album_id'],"string");
echo"";
echo"";
echo"
".$value['artist_name']."
";
echo"
";
}
?>

Here is the CSS code:

/*Image Gallery*/
div.gallery{
display:inline-block;
margin:0px 15px 30px 15px;
border:2px solid #999999;
background-color:#fff;
}
div.desc{
font-size:20px;
padding:5px;
text-align:center;
}
div.galleryOuter{
width:101%;
height:50%;
background-color:rgba(242, 242, 242,0.3);
text-align:center;
margin-top:100px;
overflow:hidden;
margin-left:-7px;
min-width:1700px;
overflow:hidden;
}
.galleryOuter:hover{
background-color:rgba(242, 242, 242,0.4);
}
div.gallery:hover{
border:2px solid #ccc;
}
p.gallery_title{
font-size:25px;
}
/*Slider Button*/
.previous{
float:left;
height:475px;
width:50px;
background-size:30px;
background-image:url('Images/icons/leftarrow.png');
background-position:center;
background-repeat:no-repeat;
background-color:rgba(242, 242, 242,0.4);
outline:none;
border:none;
cursor:pointer;
}
.next{
float:right;
height:475px;
width:50px;
background-size:30px;
background-image:url('Images/icons/rightarrow.png');
background-position:center;
background-repeat:no-repeat;
background-color:rgba(242, 242, 242,0.4);
outline:none;
border:none;
cursor:pointer;
}
.previous:hover,.next:hover{
background-color:rgba(242, 242, 242,0.7);
}

Here is the javascript:

function showImage(input_value){
var first_image_index=0;
var first_image_index_af=first_image_index+input_value;
var x=document.getElementsByClassName("album_images");
var y=document.getElementsByClassName("desc");
if(first_image_index_af<0){first_image_index_af=0;}
if(first_image_index_af>4){first_image_index_af=4;}
for(i=0;i<4;i++){
x[first_image_index_af+i].style.display="block";
y[first_image_index_af+i].style.display="block";
x[7-(first_image_index_af+i)].style.display="none";
y[7-(first_image_index_af+i)].style.display="none";
}
}


问:
jQuery validation: Total 100 in each row and each column
I have the following table generated problematically based on DB data:

How to Sum each row and each Column and validate each of them to 100
the only Summation of 100 per each row and per each column is allowed to submit the form otherwise error message will appear next to <100 or >100 row or column
Save button is locked until data is correct.

My Code:

```<code><style>
    table td{
        padding: 10px;
    }
</style>
<?php
    $course_id = $_GET['course_id'];
    $div_cou = explode(",",$course_id);
    $cou_id = $div_cou[0];
    $cou_name = $div_cou[1];

    $dbhost = "xxx";
    $dbuser = "xxx";
    $con    = mysqli_connect($dbhost, $dbuser, "");
    if (!$con) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    mysqli_select_db($con, 'xxx');

    $q = mysqli_query($con, "SELECT * FROM `plo` WHERE `COURSE_CODE`='$cou_id'");
    if (mysqli_num_rows($q) !=null) {
        $plos = "<p style='color:#B3175D;'>Program Learning Outcome List:</p><ol>";
        $countPlos = 0;
        $plosArray = array();
        while ($db_field = mysqli_fetch_assoc($q)) {
            $plos .= "<li>".$db_field['PLO_DESC']."</li>";
            $plosArray[$countPlos]['id']=$db_field['PLO_CODE'];
            $plosArray[$countPlos]['desc']=$db_field['PLO_DESC'];
            $countPlos++;
        }
        $plos .="</ol>";
    }
    echo $plos;

    $q = mysqli_query($con, "SELECT * FROM `slo` WHERE `COURSE_CODE`='$cou_id'");
    if (mysqli_num_rows($q) !=null) {
        $slos = "<p style='color:#037879;'>Student Learning Outcome List:</p><ol>";
        $countSlos = 0;
        $slosArray = array();
        while ($db_field = mysqli_fetch_assoc($q)) {
            $slos .= "<li style='list-style:decimal;'>".$db_field['SLO_DESC']."</li>";
            $slosArray[$countSlos]['id']=$db_field['SLO_CODE'];
            $slosArray[$countSlos]['desc']=$db_field['SLO_DESC'];
            $countSlos++;
        }
        $slos .="</ol>";
    }
    echo $slos;

    if ($countSlos)
    {
        $map = NULL;
        $map = "<p>Mapping SLO's to PLO's:</p><table>";

        $map .= "<tr><td></td>";
        $num = 1;
        for ($y = 0; $y < $countPlos; $y++) {
            $map .= "<td style='color:#B3175D;'>PLO".$num."</td>";
            $num++;
        }
        $map .="<td>Total</td></tr>";

        $num = 1;
        for ($x = 0; $x < $countSlos; $x++) {
            $map .= "<tr><td style='color:#037879;'>SLO".$num."</td>";
            for ($y = 0; $y < $countPlos; $y++) {
                $map .= "<td><li style='list-style:none;'><input type='number' min='0' max='100' name='map[]' style='display: block;width: 50px;float: left;margin-right: 5px;text-align: left;'/><input type='hidden' name='sloPlo_ids[]' value='".$plosArray[$y]['id'].",".$slosArray[$x]['id']."'/></li></td>";
            }
            $map .="<td>Sum Row.</td>";
            $num++;
            $map .= "</tr>";
        }

        $map .="<tr><td>Total</td>";
        for ($y = 0; $y < $countPlos; $y++) {
            $map .="<td>Sum Col.</td>";
        }
        $map .="</tr>";
        echo $map."</table>";
    }
?>
</code>```

Quick Link :
Fiddle

答:
https://jsfiddle.net/sudarpochong/fghj7no4/1/

I made modification to your html.

To sum row and column, we just call sumThisClass method.
Please check my fiddle.

```<code>function sumThisClass(className) {

  var sumTotal = 0;
  $("." + className).each(function(index, el) {
    let elValue = parseInt($(el).val());
    if (!isNaN(elValue)) {
      sumTotal += parseInt($(el).val());
    }
  });

  $(".sum-" + className).text(sumTotal);

  if (sumTotal > 100) {
    $(".sum-" + className).append("<div class='error'>cannot be greater than 100</div>");
  }

}
</code>```

Body:
I have the following table generated problematically based on DB data:

How to Sum each row and each Column and validate each of them to 100
the only Summation of 100 per each row and per each column is allowed to submit the form otherwise error message will appear next to <100 or >100 row or column
Save button is locked until data is correct.

My Code:

<?php
    $course_id = $_GET['course_id'];
    $div_cou = explode(",",$course_id);
    $cou_id = $div_cou[0];
    $cou_name = $div_cou[1];

    $dbhost = "xxx";
    $dbuser = "xxx";
    $con    = mysqli_connect($dbhost, $dbuser, "");
    if (!$con) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    mysqli_select_db($con, 'xxx');

    $q = mysqli_query($con, "SELECT * FROM `plo` WHERE `COURSE_CODE`='$cou_id'");
    if (mysqli_num_rows($q) !=null) {
        $plos = "
Program Learning Outcome List:

";
        $countPlos = 0;
        $plosArray = array();
        while ($db_field = mysqli_fetch_assoc($q)) {
            $plos .= "
".$db_field['PLO_DESC']."
";
            $plosArray[$countPlos]['id']=$db_field['PLO_CODE'];
            $plosArray[$countPlos]['desc']=$db_field['PLO_DESC'];
            $countPlos++;
        }
        $plos .="
";
    }
    echo $plos;

    $q = mysqli_query($con, "SELECT * FROM `slo` WHERE `COURSE_CODE`='$cou_id'");
    if (mysqli_num_rows($q) !=null) {
        $slos = "
Student Learning Outcome List:

";
        $countSlos = 0;
        $slosArray = array();
        while ($db_field = mysqli_fetch_assoc($q)) {
            $slos .= "
".$db_field['SLO_DESC']."
";
            $slosArray[$countSlos]['id']=$db_field['SLO_CODE'];
            $slosArray[$countSlos]['desc']=$db_field['SLO_DESC'];
            $countSlos++;
        }
        $slos .="
";
    }
    echo $slos;

    if ($countSlos)
    {
        $map = NULL;
        $map = "
Mapping SLO's to PLO's:

";

        $map .= "
	";
        $num = 1;
        for ($y = 0; $y < $countPlos; $y++) {
            $map .= "PLO".$num."	";
            $num++;
        }
        $map .="Total
";

        $num = 1;
        for ($x = 0; $x < $countSlos; $x++) {
            $map .= "
SLO".$num."	";
            for ($y = 0; $y < $countPlos; $y++) {
                $map .= "
<input type='number' min='0' max='100' name='map[]' style='display: block;width: 50px;float: left;margin-right: 5px;text-align: left;'/><input type='hidden' name='sloPlo_ids[]' value='".$plosArray[$y]['id'].",".$slosArray[$x]['id']."'/>
	";
            }
            $map .="Sum Row.	";
            $num++;
            $map .= "
";
        }

        $map .="
Total	";
        for ($y = 0; $y < $countPlos; $y++) {
            $map .="Sum Col.	";
        }
        $map .="
";
        echo $map."
";
    }
?>

Quick Link :
Fiddle

Body:
https://jsfiddle.net/sudarpochong/fghj7no4/1/

I made modification to your html.

To sum row and column, we just call sumThisClass method.
Please check my fiddle.

function sumThisClass(className) {

  var sumTotal = 0;
  $("." + className).each(function(index, el) {
    let elValue = parseInt($(el).val());
    if (!isNaN(elValue)) {
      sumTotal += parseInt($(el).val());
    }
  });

  $(".sum-" + className).text(sumTotal);

  if (sumTotal > 100) {
    $(".sum-" + className).append("<div class='error'>cannot be greater than 100</div>");
  }

}


问:
How to setup remote debugging of an eclipse RCP application
My RCP app is not working properly outside of the development environment so I'm trying to setup a remote debugging session.

I start the app using the following parameters:

```<code>-vmargs -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
</code>```

I then created a new debug profile which connects to port 8000. In the debug perspective I can see that the connection was successful and the various threads are listed. I should say that the app has a number of bundles (model, UI, services etc.) so I chose the bundle containing the .product as the project to debug.

But, although there seems to be a connection, I cannot set breakpoints. At least, I can set a breakpoint but it never halts.

Is there something else I need to do?

答:
-vmargs -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y

Please use above VM arguments. suspend should be y.

Body:
My RCP app is not working properly outside of the development environment so I'm trying to setup a remote debugging session.

I start the app using the following parameters:

-vmargs -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

I then created a new debug profile which connects to port 8000. In the debug perspective I can see that the connection was successful and the various threads are listed. I should say that the app has a number of bundles (model, UI, services etc.) so I chose the bundle containing the .product as the project to debug.

But, although there seems to be a connection, I cannot set breakpoints. At least, I can set a breakpoint but it never halts.

Is there something else I need to do?


问:
Way to pass multiple arguments to a function directly from input method

Suppose there is a function funxwhich takes multiple arguments(like funx(item, quantity, price) ) and outputs respective values.

Now what i can normally do is call function and pass args with it like this: funx(Lays, 2, 40)

But what i'm trying to do is something like this(this throws error though)

```<code>funx(item, quantity, price = input("use format 'Lays, 2, 40', use commas : ").split(','))
</code>```

to take user input this one time...
I could have done this(and i know its cleaner):

```<code>def funx(item, quantity, price):
    print(item, quantity, price)

def input_funx():
    item, quantity, price = input("use format 'Lays, 2, 40', use commas : ").split(',')
    return(item, quantity, price)

funx("Monaco", 3, 30)
funx(input_funx())
#but I want some different approach coz i won't be using this input_funx later
</code>```

and could have called funx(input_funx()) and job done, BUT just exploring if something similar is possible or not.

Here's the error: funx(input("enter in this format '' Lays, 20, 200 ''...use commas for separation  :  ").split(','))
TypeError: funx() missing 2 required positional arguments: 'quantity' and 'price'

Note: I explored about lambda functions if it can be used but found it returns single parameter.(correct me if wrong) :3

Is there a way something like this...funx(item, quantity, price= input("%s,%d,%f")) ... or any intuitive way(using dictionary or list or anything) which gets job done in SINGLE LINE.

Any help is welcomed. Thank you in advance.

答:
You can use argument expansion and avoid all that:

```<code>def funx(param1, param2, param3):
    print("Called with params: {}, {}, {}".format(param1, param2, param3))

funx( * input("use format 'Lays, 2, 40', use commas : ").split(","))
# or if you insist on whitespaces:
# funx( * (a.strip() for a in input("use format 'Lays, 2, 40', use commas : ").split(",")))
</code>```

That being said, there is no reason to make your code unreadable and hard to debug.

Body:
Suppose there is a function funxwhich takes multiple arguments(like funx(item, quantity, price) ) and outputs respective values.

Now what i can normally do is call function and pass args with it like this: funx(Lays, 2, 40)

But what i'm trying to do is something like this(this throws error though)

funx(item, quantity, price = input("use format 'Lays, 2, 40', use commas : ").split(','))

to take user input this one time...
I could have done this(and i know its cleaner):

def funx(item, quantity, price):
    print(item, quantity, price)

def input_funx():
    item, quantity, price = input("use format 'Lays, 2, 40', use commas : ").split(',')
    return(item, quantity, price)

funx("Monaco", 3, 30)
funx(input_funx())
#but I want some different approach coz i won't be using this input_funx later

and could have called funx(input_funx()) and job done, BUT just exploring if something similar is possible or not.

Here's the error: funx(input("enter in this format '' Lays, 20, 200 ''...use commas for separation  :  ").split(','))
TypeError: funx() missing 2 required positional arguments: 'quantity' and 'price'

Note: I explored about lambda functions if it can be used but found it returns single parameter.(correct me if wrong) :3

Is there a way something like this...funx(item, quantity, price= input("%s,%d,%f")) ... or any intuitive way(using dictionary or list or anything) which gets job done in SINGLE LINE.

Any help is welcomed. Thank you in advance.

Body:
You can use argument expansion and avoid all that:

def funx(param1, param2, param3):
    print("Called with params: {}, {}, {}".format(param1, param2, param3))

funx( * input("use format 'Lays, 2, 40', use commas : ").split(","))
# or if you insist on whitespaces:
# funx( * (a.strip() for a in input("use format 'Lays, 2, 40', use commas : ").split(",")))

That being said, there is no reason to make your code unreadable and hard to debug.


答:
You need to unpack the 'tuple' that is returned from .split() using *input(...):

```<code>>>> def funx(a1,a2,a3):
...     print(a1,a2,a3)
...
>>> funx(*input("enter in this format '' Lays, 20, 200 ''...use commas for separation  :  ").split(','))
</code>```

Output:

```<code>Lays  2  2
</code>```

Title: Way to pass multiple arguments to a function directly from input method

Body:
You need to unpack the 'tuple' that is returned from .split() using *input(...):

>>> def funx(a1,a2,a3):
...     print(a1,a2,a3)
...
>>> funx(*input("enter in this format '' Lays, 20, 200 ''...use commas for separation  :  ").split(','))

Output:

Lays  2  2


问:
Navigation Guards beforeEach infinite loop
Trying to use navigation guard, but next('/auth/login') gives infinite loop:

```<code>router.beforeEach((to, from, next) => {
  auth.validate().then((valid) => {
    if (!valid) {
      next('/auth/login')
    } else {
      next()
    }
  })
})
</code>```

router is define:

```<code>const router = new Router({
  routes: [
    {
      name: 'login',
      path: '/auth/login',
      component: login
    }
})
</code>```

答:
It seems to me like when your auth is not valid your router is sending you to /auth/login and on that page you get sent again. I handle this differently in my app, but with your code you can add a way to check where the page is comming from, using the from object in your route.

You need something to check if current route is /auth/login then ignore don't redirect.

example:

```<code> if (!valid && from.path !== '/auth/login') {}
</code>```

This will not redirect back to /auth/login because you are coming from that page.

Body:
Trying to use navigation guard, but next('/auth/login') gives infinite loop:

router.beforeEach((to, from, next) => {
  auth.validate().then((valid) => {
    if (!valid) {
      next('/auth/login')
    } else {
      next()
    }
  })
})

router is define:

const router = new Router({
  routes: [
    {
      name: 'login',
      path: '/auth/login',
      component: login
    }
})

Body:
It seems to me like when your auth is not valid your router is sending you to /auth/login and on that page you get sent again. I handle this differently in my app, but with your code you can add a way to check where the page is comming from, using the from object in your route.

You need something to check if current route is /auth/login then ignore don't redirect.

example:

 if (!valid && from.path !== '/auth/login') {}

This will not redirect back to /auth/login because you are coming from that page.


问:
Difference between `cout << x` and `cout.operator <<(x)`?
I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &); is not defined leading to compiler errors. The following code illustrates the problem:

```<code>#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";

    // This works
    std::cout << message;

    // Compiler error
    std::cout.operator <<(message);
}
</code>```

I thought that both statements should appear identical to the compiler. Apparently they are not. So what is the difference then?

Solved

As Tomalak and Prasoon indicated I needed to call this function:

```<code>std::ostream& operator<<(std::ostream&, const std::string&);
</code>```

So the following sample will work:

```<code>#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";
    operator<<(std::cout, message);
}
</code>```

Concerning my original goal (to use for_each to print a vector of strings): It seems like it's better to use std::copy with std::ostream_iterator as illustrated here: How do I use for_each to output to cout?

答: You're looking for std::ostream& operator<<(std::ostream&, const std::string&);. It's a free function.

Body:
I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &); is not defined leading to compiler errors. The following code illustrates the problem:

#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";

    // This works
    std::cout << message;

    // Compiler error
    std::cout.operator <<(message);
}

I thought that both statements should appear identical to the compiler. Apparently they are not. So what is the difference then?

Solved

As Tomalak and Prasoon indicated I needed to call this function:

std::ostream& operator<<(std::ostream&, const std::string&);

So the following sample will work:

#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";
    operator<<(std::cout, message);
}

Concerning my original goal (to use for_each to print a vector of strings): It seems like it's better to use std::copy with std::ostream_iterator as illustrated here: How do I use for_each to output to cout?


问:
Xcode breakpoints for single device only?
Is it possible to restrict breakpoints in Xcode 5.1 to be effective only one one device if several (e.g. iPhone plus iPad during development of Game Center app) are connected to Mac?</p>

答:
Not the simplest solution in the word, but this is the first thing that comes to mind:

Right-click the breakpoint, choose "Edit", and in the "Condition" field add something like this:

```<code>(BOOL)[some condition that is true only on the relevant device]
</code>```

Edit: Note that the compiler for conditional breakpoints does not support the instance.something syntax for property getter. You should only use use [instance something].

Body:
Not the simplest solution in the word, but this is the first thing that comes to mind:

Right-click the breakpoint, choose "Edit", and in the "Condition" field add something like this:

(BOOL)[some condition that is true only on the relevant device]

Edit: Note that the compiler for conditional breakpoints does not support the instance.something syntax for property getter. You should only use use [instance something].


问:
Node.js "cannot set property firstName of undefined"
I am following this tutorial,

https://www.youtube.com/watch?v=OnuC3VtEQks

to create a login system for my node app, only thing is since he is using mongoDb and I'm using mySql, I had to think of a way around him setting up his mongoose schema (right around 7:14 of the video), so I just exported a user module and assigned properties to it in my create a user logic.

Here's the user module

```<code>//user.js in models
var bcrypt = require('bcryptjs');

var User = {
    firstName: "firstName",
    lastName: "lastName",
    email: "email",
    username: "username",
    password: "password",
}

module.exports = User;

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}
</code>```

Here is my route for the registration form

```<code>// main.js in router folder
var user = require('../models/user').User;

router.post('/register', function(req, res){
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var cpassword = req.body.cpassword;

    //Validation
    // req.checkBody('firstName', 'First name is required!').notEmpty();
    // req.checkBody('lastName', 'Last name is required!').notEmpty();
    // req.checkBody('email', 'E-mail is invalid!').isEmail();
    // req.checkBody('username', 'Username is required!').notEmpty();
    // req.checkBody('password', 'Password is required!').notEmpty();
    // req.checkBody('cpassword', 'Passwords do not match!').equals(password);

    var errors = req.validationErrors();
    if(errors){
        res.render('register', {
            errors: errors
        });
        console.log(errors);
    } else {
        var newUser = user;

        newUser.firstName = firstName;
        newUser.lastName = lastName;
        newUser.email = email;
        newUser.username = username;
        newUser.password = password;

        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are now registered!');
        res.redirect('login');
    }
});
</code>```

Now I keep getting "cannot set property firstName of undefined error", but I thought I had access to my User object from the user.js module? From what I can tell it looks like he's just using the form input to instantiate the user object and create it with some password hashing.

If this is a bad approach, I am completely open to any ideas to make this simpler. I am completely new to node and my senior project is due in 2 weeks, so any help will be immensely appreciated and rewarded with upvotes and internet credits :)

答:
You declare (and export) the object User (with a capital U) earlier in the program, but later on try and access the variable user, which is undefined

```<code>var newUser = user;
</code>```

Body:
I am following this tutorial,

https://www.youtube.com/watch?v=OnuC3VtEQks

to create a login system for my node app, only thing is since he is using mongoDb and I'm using mySql, I had to think of a way around him setting up his mongoose schema (right around 7:14 of the video), so I just exported a user module and assigned properties to it in my create a user logic.

Here's the user module

//user.js in models
var bcrypt = require('bcryptjs');

var User = {
    firstName: "firstName",
    lastName: "lastName",
    email: "email",
    username: "username",
    password: "password",
}

module.exports = User;

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

Here is my route for the registration form

// main.js in router folder
var user = require('../models/user').User;

router.post('/register', function(req, res){
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var cpassword = req.body.cpassword;

    //Validation
    // req.checkBody('firstName', 'First name is required!').notEmpty();
    // req.checkBody('lastName', 'Last name is required!').notEmpty();
    // req.checkBody('email', 'E-mail is invalid!').isEmail();
    // req.checkBody('username', 'Username is required!').notEmpty();
    // req.checkBody('password', 'Password is required!').notEmpty();
    // req.checkBody('cpassword', 'Passwords do not match!').equals(password);

    var errors = req.validationErrors();
    if(errors){
        res.render('register', {
            errors: errors
        });
        console.log(errors);
    } else {
        var newUser = user;

        newUser.firstName = firstName;
        newUser.lastName = lastName;
        newUser.email = email;
        newUser.username = username;
        newUser.password = password;

        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are now registered!');
        res.redirect('login');
    }
});

Now I keep getting "cannot set property firstName of undefined error", but I thought I had access to my User object from the user.js module? From what I can tell it looks like he's just using the form input to instantiate the user object and create it with some password hashing.

If this is a bad approach, I am completely open to any ideas to make this simpler. I am completely new to node and my senior project is due in 2 weeks, so any help will be immensely appreciated and rewarded with upvotes and internet credits :)

Body:
You declare (and export) the object User (with a capital U) earlier in the program, but later on try and access the variable user, which is undefined

var newUser = user;