问:
Creating Mongoose organization/class structure?
I am building a web application with Node.js, Express, and Mongoose/MongoDB.

One question I had was how do I properly organize and structure methods related to Mongoose. I need to call Mongoose functionality inside my routes, but all examples show using Mongoose calls without structuring separate files or classes with prototypes.

IE. Setting up a schema and calling mongoose in routes

```<code>SiteModel.find({}, function(err, docs) {
if (!err){
    console.log(docs);
    process.exit();
} else {throw err;}
});
</code>```

I would like to put mongoose CRUD functions inside helper files related to logic and functionality and call them in my routes. When I use separate class methods with mongoose, no value is returned (Or due to the async nature I am unable to use the result)

```<code>//Router file
var myService =  require('../helpers/ServiceStatus');

router.get('/', authService.isLoggedIn, function(req,res){

   var serviceObject = new myService(); //Initialize class with Mongoose functions

   async.parallel({
       modelAFind: function(cb){
           //Mongoose class method is called
           var response= serviceObject.getAllServiceDetails();
           cb(null, response);
       },
       modelBFind: function(cb){
           cb(null, 2); //filler
       }
   }, function(results){
       console.log("Results of query: " + results);
   });
</code>```

Snippet from my Mongoose class where I create a service object:

```<code>//ServiceStatus.js
//Constructor
function ServiceStatus() {

}

ServiceStatus.prototype.getAllServiceDetails = function(){

    var query = SiteModel.find({});
    var promise = query.exec();

    promise.then(function (doc) {
        return doc;
    });
};
</code>```

What is the best way to deal with async, structure separate helper files with Mongoose logic and call them in routes: promises, functions with callbacks, etc? Thanks.

*Edit - Added Schema File

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('SiteModel', new Schema({

    id: String,
    service: {type: String, unique: true, required: true},
    status: String,
    settings: Object,
    lastCheck: String

}

,{
    timestamps: true
}));
</code>```

答:
So, there's a couple key rules of thumb you're missing, before we even get into the "best" way to organize your code.

When you're dealing with async methods, you have to always treat
them (and their calling code) as async.  In your example, your
getAllServiceDetails() function neither returns a promise nor
executes a callback, so you lose that context.

Using both Promises and Callbacks in the same logic stack adds
cognitive load to your brain; try and stick with one style or the
other to the greatest extent possible.

As for the best way to organize, I'd look strongly at not pulling out a whole Service class in this case, and instead look at writing a mongoose plugin, or simply extending the mongoose schema itself.  Plugins are more useful if you're going to write the same code for multiple models, so I'll assume you're not in this case and continue with examples for only SiteSchema.  You don't show your schema code here so I'm not sure what you're really saving by not simply calling SiteModel.find(...) in your routing code, but for arguments sake you could either do:

```<code>SiteSchema.statics.list = function(cb) {
  SiteSchema.find({}, cb);
}
</code>```

Which saves you from having to pass in the empty object in the calling code, but that calling code will still have to look like this:

```<code>/** snip **/
modelAFind: function(cb){
       //Mongoose class method is called
       var response= serviceObject.list(cb);
   },
</code>```

If you're using one of the most recent versions of node, you also have access to the async/await syntax, which might be more to your liking.  Note my example isn't tested, but it should look something like this:

```<code>SiteSchema.statics.list = async function() { // note the 'async' keyword
  // latest versions of Mongoose, this returns a Promoise
  return SiteSchema.find({});
}
</code>```

Then your consuming code can be

```<code>/** snip **/
modelAFind: function(cb){
       //Mongoose class method is called
       var response= await serviceObject.list(); // note 'await' keyword
       cb(null, response);
   },
</code>```

Also note that I didn't add error handling; with async/await you just use try...catch.

Body:
I am building a web application with Node.js, Express, and Mongoose/MongoDB.

One question I had was how do I properly organize and structure methods related to Mongoose. I need to call Mongoose functionality inside my routes, but all examples show using Mongoose calls without structuring separate files or classes with prototypes.

IE. Setting up a schema and calling mongoose in routes

SiteModel.find({}, function(err, docs) {
if (!err){
    console.log(docs);
    process.exit();
} else {throw err;}
});

I would like to put mongoose CRUD functions inside helper files related to logic and functionality and call them in my routes. When I use separate class methods with mongoose, no value is returned (Or due to the async nature I am unable to use the result)

//Router file
var myService =  require('../helpers/ServiceStatus');

router.get('/', authService.isLoggedIn, function(req,res){

   var serviceObject = new myService(); //Initialize class with Mongoose functions

   async.parallel({
       modelAFind: function(cb){
           //Mongoose class method is called
           var response= serviceObject.getAllServiceDetails();
           cb(null, response);
       },
       modelBFind: function(cb){
           cb(null, 2); //filler
       }
   }, function(results){
       console.log("Results of query: " + results);
   });

Snippet from my Mongoose class where I create a service object:

//ServiceStatus.js
//Constructor
function ServiceStatus() {

}

ServiceStatus.prototype.getAllServiceDetails = function(){

    var query = SiteModel.find({});
    var promise = query.exec();

    promise.then(function (doc) {
        return doc;
    });
};

What is the best way to deal with async, structure separate helper files with Mongoose logic and call them in routes: promises, functions with callbacks, etc? Thanks.

*Edit - Added Schema File

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('SiteModel', new Schema({

    id: String,
    service: {type: String, unique: true, required: true},
    status: String,
    settings: Object,
    lastCheck: String

}

,{
    timestamps: true
}));

Body:
So, there's a couple key rules of thumb you're missing, before we even get into the "best" way to organize your code.

When you're dealing with async methods, you have to always treat
them (and their calling code) as async.  In your example, your
getAllServiceDetails() function neither returns a promise nor
executes a callback, so you lose that context.

Using both Promises and Callbacks in the same logic stack adds
cognitive load to your brain; try and stick with one style or the
other to the greatest extent possible.

As for the best way to organize, I'd look strongly at not pulling out a whole Service class in this case, and instead look at writing a mongoose plugin, or simply extending the mongoose schema itself.  Plugins are more useful if you're going to write the same code for multiple models, so I'll assume you're not in this case and continue with examples for only SiteSchema.  You don't show your schema code here so I'm not sure what you're really saving by not simply calling SiteModel.find(...) in your routing code, but for arguments sake you could either do:

SiteSchema.statics.list = function(cb) {
  SiteSchema.find({}, cb);
}

Which saves you from having to pass in the empty object in the calling code, but that calling code will still have to look like this:

/** snip **/
modelAFind: function(cb){
       //Mongoose class method is called
       var response= serviceObject.list(cb);
   },

If you're using one of the most recent versions of node, you also have access to the async/await syntax, which might be more to your liking.  Note my example isn't tested, but it should look something like this:

SiteSchema.statics.list = async function() { // note the 'async' keyword
  // latest versions of Mongoose, this returns a Promoise
  return SiteSchema.find({});
}

Then your consuming code can be

/** snip **/
modelAFind: function(cb){
       //Mongoose class method is called
       var response= await serviceObject.list(); // note 'await' keyword
       cb(null, response);
   },

Also note that I didn't add error handling; with async/await you just use try...catch.


来源: stackexchange

问:
Define correctly height for UIScrollView
I'm creating a application using Swift3, and i have difficult to define correctly height for UIScrollView, i'm using autolayout and create this structure:

UIScrollView

UIView // The container view

UIImageView // Constraint Top Edges  = 20 in relation to UIView

UITextView // Constraint Top Edges = 40 in relation to UIImageView

UITextView // Constraint Top Edges = 20 in relation to UITextView

UIButton // Constraint Top Edges 30 in relation to UITextView

Currently, i'm using this logic to calculate UIScrollView height

```<code>override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize.height = scrollHeight

}
</code>```

But, i can only get the views height, and them not consider the Constraints "margins", i would like know any way to calculate correct height for UIScrollView, adjusted according their content.

答:
Close! Let's add the top margin for each view:</p>

```<code>override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height

        //Add the margins as well to the scrollHeight
        scrollHeight += view.layoutMargins.top
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize = CGRect(x: self.scrollView.contentSize.width, y: scrollHeight)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a application using Swift3, and i have difficult to define correctly height for UIScrollView, i'm using autolayout and create this structure:

UIScrollView

UIView // The container view

UIImageView // Constraint Top Edges  = 20 in relation to UIView

UITextView // Constraint Top Edges = 40 in relation to UIImageView

UITextView // Constraint Top Edges = 20 in relation to UITextView

UIButton // Constraint Top Edges 30 in relation to UITextView

Currently, i'm using this logic to calculate UIScrollView height

override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize.height = scrollHeight

}

But, i can only get the views height, and them not consider the Constraints "margins", i would like know any way to calculate correct height for UIScrollView, adjusted according their content.

Body:
Close! Let's add the top margin for each view:

override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height

        //Add the margins as well to the scrollHeight
        scrollHeight += view.layoutMargins.top
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize = CGRect(x: self.scrollView.contentSize.width, y: scrollHeight)
}


问:
React: replace links in a text
What is the proper way to replace urls in a string and render them as links with React?

Say I have a string: 'hello http://google.com world', and I want it to render like: hello http://google.com world

答:
Based on the OP's own answer I came up with the one-liner:</p>

```<code>{text
  .split(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi)
  .map((part, index) => index % 2 === 0 ? part : <a href={part} target="_blank">{part}</a>
}
</code>```

Title: React: replace links in a text

Body:
Based on the OP's own answer I came up with the one-liner:

{text
  .split(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi)
  .map((part, index) => index % 2 === 0 ? part : <a href={part} target="_blank">{part}</a>
}


问:
Webbased MySQL interface better that phpMyAdmin
Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

答: as a client I recommend Toad For Mysql (it is free)</p>

OwnerDisplayName: Siamak

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Sulaiman


问:
System.Data.Entity.Infrastructure.DbUpdateException Issue
I have a test method that tests a task that is suppose to get a task definition (task description) for edit:

```<code>[TestMethod]
public void GetTaskDefinitionsForEdit_HavingTaskDefinitions_ReturnsChecklistTaskDefinitions()
{
    // this.CreateChecklistTaskDefinition(referenceKey: "Xxx123", description: "SomeDescription");
    // this.checklistTaskTestHelper.CreateChecklistTaskDefinition(referenceKey: "Yyy234", description: "SomeOtherDescription");

    this.helper.CreateChecklistTaskDefinition(referenceKey: "Xxx123", description: "SomeDescription");
    this.helper.CreateChecklistTaskDefinition(referenceKey: "Yyy234", description: "SomeOtherDescription");

    this.CompanyDbContext.SaveChanges();

    //var result = this.checklistTaskTestHelper.checklistTaskDefinitionRepository.GetTaskDefinitionsForEdit(ChecklistReferenceType.ReconAccountGroup, "Xxx123");

    var result = this.checklistTaskDefinitionRepository.GetTaskDefinitionsForEdit(ChecklistReferenceType.ReconAccountGroup, "Xxx123");

    Assert.AreEqual(1, result.Count);
    //Assert.AreEqual("Xxx123", result[0].ReferenceKey);
    //Assert.AreEqual("SomeDescription", result[0].Description);
}
</code>```

I also have an initilize method:

```<code>protected override void Initialize()
{
    this.company = this.CreateCompany("Test company");
    this.checklistTaskDefinitionRepository = this.CreateRepository<ChecklistTaskDefinitionRepository>(this.company);
    this.helper = new ChecklistTaskTestHelper(this.checklistTaskDefinitionRepository, this.checklistTaskStatusRepository);
}
</code>```

And these at the start of the class:

```<code>private Company company;
private ChecklistTaskDefinitionRepository checklistTaskDefinitionRepository;
private ChecklistTaskStatusRepository checklistTaskStatusRepository;
private ChecklistTaskTestHelper helper;
</code>```

And as soon as I run the test method, It prints out this:

Test method Core.Data.Test.Modules.Checklists.ChecklistTaskDefinitionRepositoryTest.GetTaskDefinitionsForEdit_HavingTaskDefinitions_ReturnsChecklistTaskDefinitions threw exception:
  System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries.

答:
If you debug the test, you can retrieve the inner exception that in this case will give you the reason of the error (fk error, duplicated pk error, column does not exists, table does not exists, database does not exists).

To debug the test inside visual studio, right click on the test and click debug.

Body:
I have a test method that tests a task that is suppose to get a task definition (task description) for edit:

[TestMethod]
public void GetTaskDefinitionsForEdit_HavingTaskDefinitions_ReturnsChecklistTaskDefinitions()
{
    // this.CreateChecklistTaskDefinition(referenceKey: "Xxx123", description: "SomeDescription");
    // this.checklistTaskTestHelper.CreateChecklistTaskDefinition(referenceKey: "Yyy234", description: "SomeOtherDescription");

    this.helper.CreateChecklistTaskDefinition(referenceKey: "Xxx123", description: "SomeDescription");
    this.helper.CreateChecklistTaskDefinition(referenceKey: "Yyy234", description: "SomeOtherDescription");

    this.CompanyDbContext.SaveChanges();

    //var result = this.checklistTaskTestHelper.checklistTaskDefinitionRepository.GetTaskDefinitionsForEdit(ChecklistReferenceType.ReconAccountGroup, "Xxx123");

    var result = this.checklistTaskDefinitionRepository.GetTaskDefinitionsForEdit(ChecklistReferenceType.ReconAccountGroup, "Xxx123");

    Assert.AreEqual(1, result.Count);
    //Assert.AreEqual("Xxx123", result[0].ReferenceKey);
    //Assert.AreEqual("SomeDescription", result[0].Description);
}

I also have an initilize method:

protected override void Initialize()
{
    this.company = this.CreateCompany("Test company");
    this.checklistTaskDefinitionRepository = this.CreateRepository<ChecklistTaskDefinitionRepository>(this.company);
    this.helper = new ChecklistTaskTestHelper(this.checklistTaskDefinitionRepository, this.checklistTaskStatusRepository);
}

And these at the start of the class:

private Company company;
private ChecklistTaskDefinitionRepository checklistTaskDefinitionRepository;
private ChecklistTaskStatusRepository checklistTaskStatusRepository;
private ChecklistTaskTestHelper helper;

And as soon as I run the test method, It prints out this:

Test method Core.Data.Test.Modules.Checklists.ChecklistTaskDefinitionRepositoryTest.GetTaskDefinitionsForEdit_HavingTaskDefinitions_ReturnsChecklistTaskDefinitions threw exception:
  System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries.


问:
Get is working but post is not working in spring boot
I am trying to display a page using action in jsp page when submit button gets clicked. But I am facing a problem. When I use method="get" its works and url shows parameter that I send using the form. But the problem is when I use method="post" the url is correct but it displays error page.

Here is the code:

```<code><form id="forgotpassForm" action="anonymous/forgot_password"
method="post">
</code>```

Here is the error:

```<code>17:27:24.305 WARN --- [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound : Request method 'POST' not supported
</code>```

Thanks is advance for your responses.

答:
If you you are using spring > 4.3 you can use @PostMapping in your controller method to handle the post form

```<code>@PostMapping(value = "/anonymous/forgot_password")
public ResponseEntity<?> forgotPassword() {
...
}
</code>```

Body:
I am trying to display a page using action in jsp page when submit button gets clicked. But I am facing a problem. When I use method="get" its works and url shows parameter that I send using the form. But the problem is when I use method="post" the url is correct but it displays error page.

Here is the code:

<form id="forgotpassForm" action="anonymous/forgot_password"
method="post">

Here is the error:

17:27:24.305 WARN --- [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound : Request method 'POST' not supported

Thanks is advance for your responses.

Body:
If you you are using spring > 4.3 you can use @PostMapping in your controller method to handle the post form

@PostMapping(value = "/anonymous/forgot_password")
public ResponseEntity<?> forgotPassword() {
...
}


问:
VBA "kill file" not working on first run, but on all following runs
I've run into a rather weird error on two VBA Scripts I wrote and can't quite put my finger on where the issue might lie exactly...

It's about two VBA Macros which handle the same functionality, one for Word and one for Excel.
What the macros do is parsing some information into a temporary .txt file which is created as such:

```<code>Dim Appl
Set Appl = CreateObject("WScript.Shell").Exec("cmd.exe /k im viewissue " & issue & " > " & "D:\temp" & issue & ".txt")
Appl.Terminate
</code>```

Subsequently some information is extracted from the .txt file and written into the Excel/ Word files resprectively.

EDIT: As so:

```<code>Set FileNum = CreateObject("Scripting.FileSystemObject").OpenTextFile("D:\temp" & issue & ".txt", 1)
   'Read some lines and write them into the Word/Excel files...
FileNum.Close
</code>```

end of Edit.

After the macro is done with the file it deletes it:

```<code>Kill "D:\temp" & issue & ".txt"
</code>```

Everything works without any problems: File is created, information extraction works, file is removed... EXCEPT on the first time you try to run it.

The first time you try to run it (on a freshly started up machine) you get a "Runtime Error 70: Access denied" connected to the line with the kill command.
If you just cancel the error message window and try again, it works fine.

I've checked the following:

.txt file is created (even on first run)

permissions are set correctly so as to be able to delete it manually without a problem

same problem on both the Word and Excel macros after startup

running the script on Word (with the error message) eliminates the problem on the first run of the Excel script and vice versa (even though the stranded .txt file has been removed after the missed attempt)

I really don't know what the problem might be... Don't quite see the difference between the first run and the subsequent ones.

Any kind of hint is much appreciated.
Cheers.

EDIT: On another note I've managed to rule out the possibility, that the FileSystemObject is the source of the problem, since I get the same issue when running the script without actually doing anything with the file.

答:
Problems with code, that works 'while debugging or the second time' often emerge from cleanup or background processing. In many cases it helps to add a 'doevents' after calling the relevant parts. In your case you can try:

```<code>Dim Appl
Set Appl = CreateObject("WScript.Shell").Exec("cmd.exe /k im viewissue " & issue & " > " & "D:\temp" & issue & ".txt")
DoEvents
Appl.Terminate
Doevents
Kill "D:\temp" & issue & ".txt"
</code>```

Hope the helps.

Body:
I've run into a rather weird error on two VBA Scripts I wrote and can't quite put my finger on where the issue might lie exactly...

It's about two VBA Macros which handle the same functionality, one for Word and one for Excel.
What the macros do is parsing some information into a temporary .txt file which is created as such:

Dim Appl
Set Appl = CreateObject("WScript.Shell").Exec("cmd.exe /k im viewissue " & issue & " > " & "D:\temp" & issue & ".txt")
Appl.Terminate

Subsequently some information is extracted from the .txt file and written into the Excel/ Word files resprectively.

EDIT: As so:

Set FileNum = CreateObject("Scripting.FileSystemObject").OpenTextFile("D:\temp" & issue & ".txt", 1)
   'Read some lines and write them into the Word/Excel files...
FileNum.Close

end of Edit.

After the macro is done with the file it deletes it:

Kill "D:\temp" & issue & ".txt"

Everything works without any problems: File is created, information extraction works, file is removed... EXCEPT on the first time you try to run it.

The first time you try to run it (on a freshly started up machine) you get a "Runtime Error 70: Access denied" connected to the line with the kill command.
If you just cancel the error message window and try again, it works fine.

I've checked the following:

.txt file is created (even on first run)

permissions are set correctly so as to be able to delete it manually without a problem

same problem on both the Word and Excel macros after startup

running the script on Word (with the error message) eliminates the problem on the first run of the Excel script and vice versa (even though the stranded .txt file has been removed after the missed attempt)

I really don't know what the problem might be... Don't quite see the difference between the first run and the subsequent ones.

Any kind of hint is much appreciated.
Cheers.

EDIT: On another note I've managed to rule out the possibility, that the FileSystemObject is the source of the problem, since I get the same issue when running the script without actually doing anything with the file.

Body:
Problems with code, that works 'while debugging or the second time' often emerge from cleanup or background processing. In many cases it helps to add a 'doevents' after calling the relevant parts. In your case you can try:

Dim Appl
Set Appl = CreateObject("WScript.Shell").Exec("cmd.exe /k im viewissue " & issue & " > " & "D:\temp" & issue & ".txt")
DoEvents
Appl.Terminate
Doevents
Kill "D:\temp" & issue & ".txt"

Hope the helps.


问:
qooxdoo - custom listitem widget selection
I made custom listitem view (based on http://news.qooxdoo.org/tutorial-part-4-2-custom-widgets-4).

I have problem with selection items on this list. There is always selected first element (no matter which element on list I will click).

What should I do to resolve my problem?

Here is my list-item widget:

```
qx.Class.define("project.MyView", {
    extend : qx.ui.core.Widget,
    include : [qx.ui.form.MModelProperty],

    construct : function() {
        this.base(arguments);

        var layout = new qx.ui.layout.Grid(4, 2);
        layout.setColumnFlex(1, 1);
        this._setLayout(layout);

        this._createChildControl("icon");
        this._createChildControl("date");
        this._createChildControl("description");
    },

    properties : {
        appearance : {
            refine : true,
            init : "listitem"
        },

        icon : {
            check : "String",
            apply : "_applyIcon",
            nullable : true
        },

        date : {
            check : "String",
            apply : "_applyDate",
            nullable : true
        },

        description : {
            check : "String",
            apply : "_applyDescription",
            nullable : true
        }
    },

    members : {

        _createChildControlImpl : function(id) {
            var control;

            switch (id) {
            case "icon":
                control = new qx.ui.basic.Image(this.getIcon());
                control.setAnonymous(true);
                this._add(control, {
                    row : 0,
                    column : 0,
                    rowSpan : 2
                });
                break;

            case "date":
                control = new qx.ui.basic.Label(this.getDate());
                control.setAnonymous(true);
                this._add(control, {
                    row : 0,
                    column : 2
                });
                break;

            case "description":
                control = new qx.ui.basic.Label(this.getDescription());
                control.setAnonymous(true);
                control.setRich(true);
                this._add(control, {
                    row : 0,
                    column : 1
                });
                break;
            }

            return control || this.base(arguments, id);
        },

        _applyIcon : function(value, old) {
            var icon = this.getChildControl("icon");
            icon.setSource(value);
        },

        _applyDescription : function(value, old) {
            var description = this.getChildControl("description");
            description.setValue(value);
        },

        _applyDate : function(value, old) {
            var date = this.getChildControl("date");
            date.setValue(value);
        }

    },

    destruct : function() {

    }

});
```

... and here how I use it:

```
this.list = new qx.ui.form.List();
this.listController = new qx.data.controller.List(null, this.list);
this.listController.setDelegate({
    createItem : function() {
        return new project.MyView();
    },

    bindItem : function(controller, item, id) {
        controller.bindProperty("description", "description", null,item, id);
        controller.bindProperty("icon", "icon", null, item, id);
        controller.bindProperty("date", "date", null, item, id);
    },

    configureItem : function(item) {
        item.getChildControl("icon").setWidth(48);
        item.getChildControl("icon").setHeight(48);
        item.getChildControl("icon").setScale(true);
        item.setMinHeight(52);
    }
});
```

答:
looks like the Problem is in the bindItem function. As soon as you supply your own bindItem function, all default bound properties are not bound anymore. That means that lable, icon and model are no longer in sync. I havent tried you code but i guess with a simple binding of the model, the problem will be gone.

```<code>controller.bindProperty("", "model", null, item, id);
</code>```

This is necessary in case you want something different in your model property and with that, in your selection for example. This code line just uses the whole object as model which is in the most cases a good idea.

Best,
Martin

Body:
I made custom listitem view (based on http://news.qooxdoo.org/tutorial-part-4-2-custom-widgets-4).

I have problem with selection items on this list. There is always selected first element (no matter which element on list I will click).

What should I do to resolve my problem?

Here is my list-item widget:

qx.Class.define("project.MyView", {
    extend : qx.ui.core.Widget,
    include : [qx.ui.form.MModelProperty],

    construct : function() {
        this.base(arguments);

        var layout = new qx.ui.layout.Grid(4, 2);
        layout.setColumnFlex(1, 1);
        this._setLayout(layout);

        this._createChildControl("icon");
        this._createChildControl("date");
        this._createChildControl("description");
    },

    properties : {
        appearance : {
            refine : true,
            init : "listitem"
        },

        icon : {
            check : "String",
            apply : "_applyIcon",
            nullable : true
        },

        date : {
            check : "String",
            apply : "_applyDate",
            nullable : true
        },

        description : {
            check : "String",
            apply : "_applyDescription",
            nullable : true
        }
    },

    members : {

        _createChildControlImpl : function(id) {
            var control;

            switch (id) {
            case "icon":
                control = new qx.ui.basic.Image(this.getIcon());
                control.setAnonymous(true);
                this._add(control, {
                    row : 0,
                    column : 0,
                    rowSpan : 2
                });
                break;

            case "date":
                control = new qx.ui.basic.Label(this.getDate());
                control.setAnonymous(true);
                this._add(control, {
                    row : 0,
                    column : 2
                });
                break;

            case "description":
                control = new qx.ui.basic.Label(this.getDescription());
                control.setAnonymous(true);
                control.setRich(true);
                this._add(control, {
                    row : 0,
                    column : 1
                });
                break;
            }

            return control || this.base(arguments, id);
        },

        _applyIcon : function(value, old) {
            var icon = this.getChildControl("icon");
            icon.setSource(value);
        },

        _applyDescription : function(value, old) {
            var description = this.getChildControl("description");
            description.setValue(value);
        },

        _applyDate : function(value, old) {
            var date = this.getChildControl("date");
            date.setValue(value);
        }

    },

    destruct : function() {

    }

});

... and here how I use it:

this.list = new qx.ui.form.List();
this.listController = new qx.data.controller.List(null, this.list);
this.listController.setDelegate({
    createItem : function() {
        return new project.MyView();
    },

    bindItem : function(controller, item, id) {
        controller.bindProperty("description", "description", null,item, id);
        controller.bindProperty("icon", "icon", null, item, id);
        controller.bindProperty("date", "date", null, item, id);
    },

    configureItem : function(item) {
        item.getChildControl("icon").setWidth(48);
        item.getChildControl("icon").setHeight(48);
        item.getChildControl("icon").setScale(true);
        item.setMinHeight(52);
    }
});

Body:
looks like the Problem is in the bindItem function. As soon as you supply your own bindItem function, all default bound properties are not bound anymore. That means that lable, icon and model are no longer in sync. I havent tried you code but i guess with a simple binding of the model, the problem will be gone.

controller.bindProperty("", "model", null, item, id);

This is necessary in case you want something different in your model property and with that, in your selection for example. This code line just uses the whole object as model which is in the most cases a good idea.

Best,
Martin


问:
C Program crashes after assigning value to string
Relatively new to C, don't see what I'm doing wrong here, this piece of code crashes after assigning the 3rd string:

```<code>QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be*));
sentence->questionword->word = words[0];
sentence->verb->word = words[1];
sentence->subject->word = words[2]; //crashes here ?
</code>```

words is an char *[ ], and here's the structure of "sentence":

```<code>typedef struct QW_Be{
    Word *questionword;
    Word *verb;
    Word *subject;
    Word *rest[];
} QW_Be;
</code>```

and here's the structure of 'Word':

```<code>typedef struct Word{
    char *word;
    word_type type;
    char *context;
} Word;
</code>```

If you need any more info, just ask !

答: If you are crashing in an assign value to a string it could be the fact you are assigning a value in a place of the memory who is'nt yours. Besides, make sure to always declare how much memory you want for your string and assign your values in the right place.</p>

Body:
Relatively new to C, don't see what I'm doing wrong here, this piece of code crashes after assigning the 3rd string:

QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be*));
sentence->questionword->word = words[0];
sentence->verb->word = words[1];
sentence->subject->word = words[2]; //crashes here ?

words is an char *[ ], and here's the structure of "sentence":

typedef struct QW_Be{
    Word *questionword;
    Word *verb;
    Word *subject;
    Word *rest[];
} QW_Be;

and here's the structure of 'Word':

typedef struct Word{
    char *word;
    word_type type;
    char *context;
} Word;

If you need any more info, just ask !


问:
Get notify by Sharepoint
I'm trying to build a Web API who'll receive notification from Sharepoint when something happend (someone upload a file, delete a file, create a directory, delete a directory etc).
I saw that Sharepoint has Alert and Webhook but idk how make it works in my situation. If someone can tell me where to start .. !

Thank's :)

答:
Remote event receiver (RER) are the way to go.

Refer to the link on pnp site link below for walkthrough video.
https://github.com/SharePoint/PnP/tree/master/Samples/Core.EventReceivers

A Tutorial on MSDN:
https://dev.office.com/sharepoint/docs/sp-add-ins/create-a-remote-event-receiver-in-sharepoint-add-ins

The link below has a List events available, declarative provisioning code to add remote event receiver to the SharePoint Add-in project. The Elements.xml file for the remote event receiver references the web service in the web application and the remote events that you specified.
https://dev.office.com/sharepoint/docs/sp-add-ins/handle-events-in-sharepoint-add-ins

Title: Get notify by Sharepoint


问:
Adding class to a div being collided
http://output.jsbin.com/kulobolutu/

This link contains the output of my code.
I have some divs where one div is draggable. You can drag that and collide it with another one. So I want the collided div to move ahead a little in such a way that it does not get out of the screen and adjust itself smoothly to another position.
Please help me in this case, i am badly stuck in this task.
Thanks in advance.

```<code>var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

function m() {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;

    html = $( area ).children().not( box ).map( function ( i ) {
      return '<p>Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '</p>';
    }).get().join( '' );

    $( '#result' ).html( html );

}

$('#box0').draggable({
  drag: function(){
    m();
  }
});
</code>```

答:
for live working demo, click here

Use this javascript and css and it works

```<code>var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

function m() {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;

    html = $( area ).children().not( box ).map( function ( i ) {
    if(overlaps( box, this )){
      $("#box" + (i+1)).addClass("overlapped");
      }
      return '<p>Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '</p>';

    }).get().join( '' );

    $( '#result' ).html( html );

}

$('#box0').draggable({
  drag: function(){
    $(".overlapped").removeClass("overlapped");
    m();
  }
});
</code>```

Add these lines to Css

```<code>.overlapped{
  border:1px solid red;
}
</code>```

Title: Adding class to a div being collided

Body:
http://output.jsbin.com/kulobolutu/

This link contains the output of my code.
I have some divs where one div is draggable. You can drag that and collide it with another one. So I want the collided div to move ahead a little in such a way that it does not get out of the screen and adjust itself smoothly to another position.
Please help me in this case, i am badly stuck in this task.
Thanks in advance.

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

function m() {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;

    html = $( area ).children().not( box ).map( function ( i ) {
      return '
Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '
';
    }).get().join( '' );

    $( '#result' ).html( html );

}

$('#box0').draggable({
  drag: function(){
    m();
  }
});

Body:
for live working demo, click here

Use this javascript and css and it works

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

function m() {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;

    html = $( area ).children().not( box ).map( function ( i ) {
    if(overlaps( box, this )){
      $("#box" + (i+1)).addClass("overlapped");
      }
      return '<p>Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '</p>';

    }).get().join( '' );

    $( '#result' ).html( html );

}

$('#box0').draggable({
  drag: function(){
    $(".overlapped").removeClass("overlapped");
    m();
  }
});

Add these lines to Css

.overlapped{
  border:1px solid red;
}


问:
Auto-Interval precision in MS Chart
I'm currently using the charting within .NET using System.Windows.Forms.DataVisualization.Charting.Chart. Thus far it seems very powerful, and works great. However, there is a huge problem in terms of how it is auto-calculating intervals. I use a lot of double values, and in libraries like ZedGraph, it handles this perfectly. It selects min/max/interval just fine. However, in MS Chart, it may select 206.3334539832 as a minimum, and intervals of a similar decimal precision. Obviously this looks quite ugly.

So, I tried simply making the axis format {0.00} and it works great when it loads the chart. Except when you zoom in, you need greater precision, maybe at 4 decimal places instead of 2. It seems I'm either stuck with 9 decimal places all the time, or else a constant fixed number that may break when someone requires greater precision. I'd rather it pick up the precision based on the level of zoom currently applied. Libraries like ZedGraph and Dundas (which I believe MS is even using!) tend to pick good values that change as you zoom in and out.

Is there any way to have the intervals change precision as the zoom frame changes? It's probably some simple property I have set wrong, but it's hard to tell with the millions of properties this thing has (especially when there's about 14 places that represent the concept of Interval).

答:
Why not modify number format string.

Create format string

```<code>string formatString = "{0.00";
</code>```

Identify zoom level, say zoomLevel = 2;

```<code>formatString = formatString.PadRight(5+zoomLevel, '0');
formatString += "}";
</code>```

Now use this format on axis legend. Use string builder or some better way to modify the format string.

Title: Auto-Interval precision in MS Chart

Body:
Why not modify number format string.

Create format string

string formatString = "{0.00";

Identify zoom level, say zoomLevel = 2;

formatString = formatString.PadRight(5+zoomLevel, '0');
formatString += "}";

Now use this format on axis legend. Use string builder or some better way to modify the format string.


问:
Dependency installation for Python (Django) project
I'm new to Python, but I had a requirement at my work-place. Another programmer is developing a project on Python, Django framework, and my task is to find a way in which this project will be executed at any computer.
So, I'm talking about something like Composer for PHP. I need an easiest way that at debian branch to write in terminal a command, that will find kind of "composer.json" file on that project, will read all the required software, modules, libraries and install it step-by-step on PC.

Any ideas how to do it in the easiest way? Thanks.

答:
Using pip freeze > requirements.txt is an anti-pattern. It does some things right, such as pinning version numbers, but it can lead to problems with orphan packages later.

I use pip-tools, this way only your top level dependencies are placed in your requirements.in file and then I use pip-sync to sync my local environment with pip.

There's a lot more information on pip best practices in my 2016 Pycon UK talk - Avoiding the "left pad" problem: How to secure your pip install process


问:
Incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Am trying to pass a List<> from an activity to a fragment.

When an imageView is clicked; the onClick event triggers a call to the server that takes the userId of the user that clicked on the imageView and the userId of the users profile you want to see.i have an interface that  that takes the response gotten from the server, which is then sent to a new fragment class. The problem am having is that i cannot pass a List<> through the bundle.

This is the newInstance of the fragment class and the parameter am trying to send across

```<code>  public static HomeUserProfileFragment newInstance(String postTotal, String followersTotal
        , String followingTotal, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putStringArrayList(UPLOAD_POST_LIST,uploadPostList);
    args.putStringArrayList(FOLLOWERS_LIST,followersList);
    args.putStringArrayList(FOLLOWING_LIST, followingList);
    fragment.setArguments(args);
    return fragment;
}
</code>```

While this is the the Activity class that the Above Fragment is been called from.

```<code> @Override
public void onClickUserProfile(String post, String followers, String following, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}
</code>```

So am getting the following errors:

```<code>Error:(56, 50) error: incompatible types: List<UploadPost> cannot be converted to ArrayList<String>
Error:(57, 48) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Error:(58, 49) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
</code>```

答:
I finally got a solution. I had to implement Parcelable to UploadPost model class and FollowUser model class. Since these two model class are called in a third class that hold them as well as other parameters that are sent from the server, i had to implement Parcelable to the model class.

Then: newInstance method of Fragment class:

```<code> public static HomeUserProfileFragment newInstance(String yourId, String other_UserId,  String name,String username,String userImage,String postTotal, String followersTotal
        , String followingTotal, ArrayList<UploadPost> uploadPostList, ArrayList<FollowUser> followersList, ArrayList<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(YOUR_USER_ID, yourId); // this holds the id of the user that his profile wants to be seen.
    args.putString(VIEWER_USER_ID, other_UserId); // this holds the id of the user that want to see your profile. this Id is used to determine if the user is a friend or not.so if not a friend the follow button will be displayed.
    args.putString(NAME,name);
    args.putString(USERNAME, username);
    args.putString(USER_IMAGE, userImage);
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putParcelableArrayList(UPLOAD_POST_LIST,  uploadPostList);
    args.putParcelableArrayList(FOLLOWERS_LIST,  followersList);
    args.putParcelableArrayList(FOLLOWING_LIST,  followingList);
    fragment.setArguments(args);
    return fragment;
}
</code>```

And Activity class calling Fragment:

```<code>    @Override
public void onClickUserProfile(String yourId, String viewerId, String name, String username, String userImage, String post,
                               String followers, String following, ArrayList<UploadPost> uploadPostList, ArrayList<FollowUser> followersList, ArrayList<FollowUser> followingList) {
    this.yourId = yourId;
    this.viewerId = viewerId;
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(yourId,viewerId,name, username,userImage,post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}
</code>```

that is my Answer

Body:
Am trying to pass a List<> from an activity to a fragment.

When an imageView is clicked; the onClick event triggers a call to the server that takes the userId of the user that clicked on the imageView and the userId of the users profile you want to see.i have an interface that  that takes the response gotten from the server, which is then sent to a new fragment class. The problem am having is that i cannot pass a List<> through the bundle.

This is the newInstance of the fragment class and the parameter am trying to send across

  public static HomeUserProfileFragment newInstance(String postTotal, String followersTotal
        , String followingTotal, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putStringArrayList(UPLOAD_POST_LIST,uploadPostList);
    args.putStringArrayList(FOLLOWERS_LIST,followersList);
    args.putStringArrayList(FOLLOWING_LIST, followingList);
    fragment.setArguments(args);
    return fragment;
}

While this is the the Activity class that the Above Fragment is been called from.

 @Override
public void onClickUserProfile(String post, String followers, String following, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}

So am getting the following errors:

Error:(56, 50) error: incompatible types: List<UploadPost> cannot be converted to ArrayList<String>
Error:(57, 48) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Error:(58, 49) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>

Body:
I finally got a solution. I had to implement Parcelable to UploadPost model class and FollowUser model class. Since these two model class are called in a third class that hold them as well as other parameters that are sent from the server, i had to implement Parcelable to the model class.

Then: newInstance method of Fragment class:

 public static HomeUserProfileFragment newInstance(String yourId, String other_UserId,  String name,String username,String userImage,String postTotal, String followersTotal
        , String followingTotal, ArrayList<UploadPost> uploadPostList, ArrayList<FollowUser> followersList, ArrayList<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(YOUR_USER_ID, yourId); // this holds the id of the user that his profile wants to be seen.
    args.putString(VIEWER_USER_ID, other_UserId); // this holds the id of the user that want to see your profile. this Id is used to determine if the user is a friend or not.so if not a friend the follow button will be displayed.
    args.putString(NAME,name);
    args.putString(USERNAME, username);
    args.putString(USER_IMAGE, userImage);
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putParcelableArrayList(UPLOAD_POST_LIST,  uploadPostList);
    args.putParcelableArrayList(FOLLOWERS_LIST,  followersList);
    args.putParcelableArrayList(FOLLOWING_LIST,  followingList);
    fragment.setArguments(args);
    return fragment;
}

And Activity class calling Fragment:

    @Override
public void onClickUserProfile(String yourId, String viewerId, String name, String username, String userImage, String post,
                               String followers, String following, ArrayList<UploadPost> uploadPostList, ArrayList<FollowUser> followersList, ArrayList<FollowUser> followingList) {
    this.yourId = yourId;
    this.viewerId = viewerId;
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(yourId,viewerId,name, username,userImage,post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}

that is my Answer


问:
Query with wildcard and mandatory clauses
I have two tables, TableA and TableB which has to be join in such a way

ColumnA is mandatory to match

ColumnB and ColumnC can match (if not then should be considered as wildcard)

I have written below query for this

```<code>SELECT *
FROM TableA  JOIN TableB ON (TableA.ColumnA = TableB.ColumnA) AND
(TableA.ColumnB = TableB.ColumnB OR TableA.ColumnC = TableB.ColumnC)
</code>```

In words, ColumnA should be matched with ColumnA while if ColumnB (from TableB) is NULL then consider it as a wildcard and if ColumnC (From TableB) is a NULL then consider it as a wild card.

Now, I suspect that this will not generate correct result because as per boolean math

Which has

True AND False = False

What I am looking for

```<code>True AND (True OR False) = True
True AND (True OR True) = True
True AND (False OR True) = True
False AND (True OR True) = False
False AND (True or False) = False
False AND (False OR True) = False
False AND (False OR False) = False
</code>```

{This is just a part of large query so I am not to share the complete example, I'm sorry for that}

答:
Looking at your logic, columns B and C are really just red herrings here and you can safely ignore them. So your query is much simpler:

```<code>SELECT *
FROM TableA
JOIN TableB
    ON TableA.ColumnA = TableB.ColumnA
</code>```

Additionally, you may want a column to indicate that B or C matched also, so you could do this:

```<code>SELECT *,
       CASE
           WHEN TableA.ColumnB = TableB.ColumnB OR TableA.ColumnC = TableB.ColumnC
               THEN 0
               ELSE 1 END
           AS IsWildcard
FROM TableA
JOIN TableB
    ON TableA.ColumnA = TableB.ColumnA
</code>```

Body:
I have two tables, TableA and TableB which has to be join in such a way

ColumnA is mandatory to match

ColumnB and ColumnC can match (if not then should be considered as wildcard)

I have written below query for this

SELECT *
FROM TableA  JOIN TableB ON (TableA.ColumnA = TableB.ColumnA) AND
(TableA.ColumnB = TableB.ColumnB OR TableA.ColumnC = TableB.ColumnC)

In words, ColumnA should be matched with ColumnA while if ColumnB (from TableB) is NULL then consider it as a wildcard and if ColumnC (From TableB) is a NULL then consider it as a wild card.

Now, I suspect that this will not generate correct result because as per boolean math

Which has

True AND False = False

What I am looking for

True AND (True OR False) = True
True AND (True OR True) = True
True AND (False OR True) = True
False AND (True OR True) = False
False AND (True or False) = False
False AND (False OR True) = False
False AND (False OR False) = False

{This is just a part of large query so I am not to share the complete example, I'm sorry for that}

Body:
Looking at your logic, columns B and C are really just red herrings here and you can safely ignore them. So your query is much simpler:

SELECT *
FROM TableA
JOIN TableB
    ON TableA.ColumnA = TableB.ColumnA

Additionally, you may want a column to indicate that B or C matched also, so you could do this:

SELECT *,
       CASE
           WHEN TableA.ColumnB = TableB.ColumnB OR TableA.ColumnC = TableB.ColumnC
               THEN 0
               ELSE 1 END
           AS IsWildcard
FROM TableA
JOIN TableB
    ON TableA.ColumnA = TableB.ColumnA


问:
Why I can not read and display data from Firebase real-time database?
I am trying to develop an android which is read and display data from Firebase database, unfortunately, I could not able to display any data from the database.There are no error messages or any error issues are noted in Android monitor(I am using Android Studio).The only issue I noticed which is in FriendlyMessage file setText,setName,setPhotoUrl this three methods are never used.

There are three parts of the project, 1)mainactivity,2)MessageAdapter,3)Friendlymessage
1)MaiinActivity

```<code> public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;

private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mFirebaseDatabaseReference;
private ChildEventListener monchildlistner;
private String mUsername;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mUsername = ANONYMOUS;

    mFirebaseDatabase=FirebaseDatabase.getInstance();
    mFirebaseDatabaseReference=mFirebaseDatabase.getReference().child("message");

    // Initialize references to views
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageListView = (ListView) findViewById(R.id.messageListView);
    mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mSendButton = (Button) findViewById(R.id.sendButton);

    // Initialize message ListView and its adapter
    List<FriendlyMessage> friendlyMessage = new ArrayList<>();
    mMessageAdapter = new MessageAdapter(this, R.layout.item_message,friendlyMessage);
    mMessageListView.setAdapter(mMessageAdapter);

    // Initialize progress bar
    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    // ImagePickerButton shows an image picker to upload a image for a message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO: Fire an intent to show an image picker
        }
    });

    // Enable Send button when there's text to send
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    });
    mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});

    // Send button sends a message and clears the EditText
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO: Send messages on click
      FriendlyMessage friendlyMessage=new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
             mFirebaseDatabaseReference.push().setValue(friendlyMessage);
            // Clear input box
            mMessageEditText.setText("");
        }
    });
    monchildlistner=new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            FriendlyMessage friendlymessage=dataSnapshot.getValue(FriendlyMessage.class);
            mMessageAdapter.add(friendlymessage);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
       //when a message added on the database at that time addchildeventlistener will fire up and refer us to onchildadded method
    mFirebaseDatabaseReference.addChildEventListener(monchildlistner);

}
</code>```

}
 2)MessageAdapter:

```<code>public class MessageAdapter extends ArrayAdapter<FriendlyMessage>{
public MessageAdapter(Context context, int resource, List<FriendlyMessage> objects) {
    super(context, resource, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
    }

    ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
    TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
    TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);

    FriendlyMessage message = getItem(position);

    boolean isPhoto = message.getPhotoUrl() != null;
    if (isPhoto) {
        messageTextView.setVisibility(View.GONE);
        photoImageView.setVisibility(View.VISIBLE);
        Glide.with(photoImageView.getContext())
                .load(message.getPhotoUrl())
                .into(photoImageView);
    } else {
        messageTextView.setVisibility(View.VISIBLE);
        photoImageView.setVisibility(View.GONE);
        messageTextView.setText(message.getText());
    }
    authorTextView.setText(message.getName());

    return convertView;
}
</code>```

}
3)FriendlyMessage:

```<code>public class FriendlyMessage {
private String text;
private String name;
private String photoUrl;

public FriendlyMessage() {
}

public FriendlyMessage(String text, String name, String photoUrl) {
    this.text = text;
    this.name = name;
    this.photoUrl = photoUrl;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(String photoUrl) {
    this.photoUrl = photoUrl;
}
</code>```

}

答:
After you add your message, you are not notifying the adapter to refresh or load the content that is newly added.

```<code>adapter.notifyDataSetChanged()
</code>```

would work

Body:
I am trying to develop an android which is read and display data from Firebase database, unfortunately, I could not able to display any data from the database.There are no error messages or any error issues are noted in Android monitor(I am using Android Studio).The only issue I noticed which is in FriendlyMessage file setText,setName,setPhotoUrl this three methods are never used.

There are three parts of the project, 1)mainactivity,2)MessageAdapter,3)Friendlymessage
1)MaiinActivity

 public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;

private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mFirebaseDatabaseReference;
private ChildEventListener monchildlistner;
private String mUsername;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mUsername = ANONYMOUS;

    mFirebaseDatabase=FirebaseDatabase.getInstance();
    mFirebaseDatabaseReference=mFirebaseDatabase.getReference().child("message");

    // Initialize references to views
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageListView = (ListView) findViewById(R.id.messageListView);
    mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mSendButton = (Button) findViewById(R.id.sendButton);

    // Initialize message ListView and its adapter
    List<FriendlyMessage> friendlyMessage = new ArrayList<>();
    mMessageAdapter = new MessageAdapter(this, R.layout.item_message,friendlyMessage);
    mMessageListView.setAdapter(mMessageAdapter);

    // Initialize progress bar
    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    // ImagePickerButton shows an image picker to upload a image for a message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO: Fire an intent to show an image picker
        }
    });

    // Enable Send button when there's text to send
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    });
    mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});

    // Send button sends a message and clears the EditText
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO: Send messages on click
      FriendlyMessage friendlyMessage=new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
             mFirebaseDatabaseReference.push().setValue(friendlyMessage);
            // Clear input box
            mMessageEditText.setText("");
        }
    });
    monchildlistner=new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            FriendlyMessage friendlymessage=dataSnapshot.getValue(FriendlyMessage.class);
            mMessageAdapter.add(friendlymessage);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
        }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
       //when a message added on the database at that time addchildeventlistener will fire up and refer us to onchildadded method
    mFirebaseDatabaseReference.addChildEventListener(monchildlistner);

}

}
 2)MessageAdapter:

public class MessageAdapter extends ArrayAdapter<FriendlyMessage>{
public MessageAdapter(Context context, int resource, List<FriendlyMessage> objects) {
    super(context, resource, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
    }

    ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
    TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
    TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);

    FriendlyMessage message = getItem(position);

    boolean isPhoto = message.getPhotoUrl() != null;
    if (isPhoto) {
        messageTextView.setVisibility(View.GONE);
        photoImageView.setVisibility(View.VISIBLE);
        Glide.with(photoImageView.getContext())
                .load(message.getPhotoUrl())
                .into(photoImageView);
    } else {
        messageTextView.setVisibility(View.VISIBLE);
        photoImageView.setVisibility(View.GONE);
        messageTextView.setText(message.getText());
    }
    authorTextView.setText(message.getName());

    return convertView;
}

}
3)FriendlyMessage:

public class FriendlyMessage {
private String text;
private String name;
private String photoUrl;

public FriendlyMessage() {
}

public FriendlyMessage(String text, String name, String photoUrl) {
    this.text = text;
    this.name = name;
    this.photoUrl = photoUrl;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(String photoUrl) {
    this.photoUrl = photoUrl;
}

}

Body:
After you add your message, you are not notifying the adapter to refresh or load the content that is newly added.

adapter.notifyDataSetChanged()

would work


问:
Ascending order with three integers for C++
```<code>#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " << b;
    }
    else if (((a == a) && (b >= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }
    else if (((a >= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " << b;
    }
    else if (((a > c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " << a;
    }
    else if (((a >= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}
</code>```

<p>For this assignment, I used 1, 2, and 3 for entering the integer.
My question is why these input (1, 2, 3) and (2, 1, 3) and (3, 2, 1)
don't ascended properl?   </p>

答:
You really want to make sure the numbers entered are in ascending order. A single test can make sure of that.</p>
```<code>do {
     cout << "Enter 3 numbers in ascending order: ";
     cin >> arr[0] >> arr[1] >> arr[2];
} while (!(arr[0] <= arr[1] && arr[1] <= arr[2]));
</code>```

Body:
#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " <= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " <= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " < c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " <= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}

For this assignment, I used 1, 2, and 3 for entering the integer.
My question is why these input (1, 2, 3) and (2, 1, 3) and (3, 2, 1)
don't ascended properl?

Body:
You really want to make sure the numbers entered are in ascending order. A single test can make sure of that.

do {
     cout << "Enter 3 numbers in ascending order: ";
     cin >> arr[0] >> arr[1] >> arr[2];
} while (!(arr[0] <= arr[1] && arr[1] <= arr[2]));

ContentLicense: CC BY-SA 4.0


问:
Storing passwords while keeping the integrity of getch()
Whats an easy way I can store the password the user inputs while still keeping the password hidden?

```<code>  char password[9];
   int i;
   printf("Enter your password: ");
   for (i=0;i<9;i++)
   {
   password[i] = getch();
   printf("*");
   }
   for (i=0;i<9;i++)
   printf("%c",password[i]);
   getch();
   }
</code>```

I wanna store the password so I can do a simple if (password[i] == root_password) so the proper password continues on.

答:
Your problem appears to be that you're not checking for newline '\n' nor end-of-file.

```<code>printf("Enter your password: ");
char password[9];
int i;
for (i = 0; i < sizeof password - 1; i++)
{
    int c = getch();
    if (c == '\n' || c == EOF)
        break;
    }
    password[i] = c;
    printf("*");
}
password[i] = '\0';
</code>```

This way, password will end up being an ASCIIZ string, suitable for printing with puts, printf("%s", password), or - crucially...

```<code>if (strcmp(password, root_password)) == 0)
    your_wish_is_my_command();
</code>```

Note that we read at most 8 characters into the password as we need one extra character for the NUL terminator.  You could increase that if you wanted.

Body:
Whats an easy way I can store the password the user inputs while still keeping the password hidden?

  char password[9];
   int i;
   printf("Enter your password: ");
   for (i=0;i<9;i++)
   {
   password[i] = getch();
   printf("*");
   }
   for (i=0;i<9;i++)
   printf("%c",password[i]);
   getch();
   }

I wanna store the password so I can do a simple if (password[i] == root_password) so the proper password continues on.

Body:
Your problem appears to be that you're not checking for newline '\n' nor end-of-file.

printf("Enter your password: ");
char password[9];
int i;
for (i = 0; i < sizeof password - 1; i++)
{
    int c = getch();
    if (c == '\n' || c == EOF)
        break;
    }
    password[i] = c;
    printf("*");
}
password[i] = '\0';

This way, password will end up being an ASCIIZ string, suitable for printing with puts, printf("%s", password), or - crucially...

if (strcmp(password, root_password)) == 0)
    your_wish_is_my_command();

Note that we read at most 8 characters into the password as we need one extra character for the NUL terminator.  You could increase that if you wanted.


问:
How to fix Curl SSL CA Cert error
I implemented the Xero-API using this library, having implemented it, it worked fine on localhost, then i uploaded to my server then i get this error</p>

```<code>Curl error: Problem with the SSL CA cert (path? access rights?)
</code>```

答: Assuming that the certs do exist in the path and php has the ability to access the server. Try restart apache first, it might be something simple, if not try regenerate the cert, it might have gotten corrupt somehow. </p>

Title: How to fix Curl SSL CA Cert error

Body:
I implemented the Xero-API using this library, having implemented it, it worked fine on localhost, then i uploaded to my server then i get this error

Curl error: Problem with the SSL CA cert (path? access rights?)


问:
change colour of partial text css or javascript
Is there any way of achieving a different colour on part of text, via css or script, based on a shape outline e.g a circle or oval curve...with CSS or JS only.

An example is this, see how the colour of the S and part of the U are different based on the image?-
example of effect

Theres a similar question but this is in illustrator - https://graphicdesign.stackexchange.com/questions/20127/text-silhouette-change-color-in-middle-of-a-letter-illustrator

Instinct says no way, but there could be some magical clipping effect that can achieve the same?

答:
I was a bit slower than Emil Østervig, but I wanted to write the same :-) I created a little example for the mix blend mode property, which does NOT work in IE and Edge. I dont think you can exactly recreate your Image with pure CSS, but it is an interesting option to maybe dig a bit deeper.

.image {
  background: url(http://www.iconsdb.com/icons/preview/red/wolf-xxl.png);
  background-repeat: no-repeat;
}

.inverted {
  background-repeat: no-repeat;
  color: blue;
  width: 50%;
  height: 256px;
  mix-blend-mode: screen;
  font-size: 64px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image">
  <div class="inverted">
    Wolf <br>
    Wolf <br>
    Wolf
  </div>
</div></code>```

Body:
I was a bit slower than Emil Østervig, but I wanted to write the same :-) I created a little example for the mix blend mode property, which does NOT work in IE and Edge. I dont think you can exactly recreate your Image with pure CSS, but it is an interesting option to maybe dig a bit deeper.

.image {
  background: url(http://www.iconsdb.com/icons/preview/red/wolf-xxl.png);
  background-repeat: no-repeat;
}

.inverted {
  background-repeat: no-repeat;
  color: blue;
  width: 50%;
  height: 256px;
  mix-blend-mode: screen;
  font-size: 64px;
}

<div class="image">
  <div class="inverted">
    Wolf <br>
    Wolf <br>
    Wolf
  </div>
</div>


问:
SC.Widget.Events.FINISH only firing once with HTML5 Embed Widget
I successfully bound SC.Widget.Events.FINISH to my widget, but it won't run more than once. I read that this issue was fixed it 2013, but it's still present. (I recall this code working last year, or the year before that, so it must be a new iteration of the same bug.

Here's my code:

```<code><html>
<audio src="intro.mp3" type="audio/mp3"></audio>
<iframe onload="javascript:LoadWidget()" id="lure" width="100%" height="600" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/playlists/135934116&enable_api=true&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true">
</iframe>
</html>
<script type="text/javascript">
//alert("Hey!")
Boom = "http://162.13.25.174/urw14a2kb"
</script>
<script type="text/javascript" src="https://w.soundcloud.com/player/api.js" />
<script type="text/javascript">
var iframeElement   = document.querySelector('iframe');
var iframeElementID = iframeElement.id;
var widget1         = SC.Widget(iframeElement)
</script>
<script type="text/javascript">
//alert("It is running. Kinda.")
var iframeElement   = document.getElementsByTagName('iframe');
var iframeElementID = iframeElement.id;
var widget1         = SC.Widget(iframeElement[0])
//alert("It's on.")
//var player = SC.getPlayer('102641127')
console.log("Window has " + Object.keys(window).length)
console.log("window's Object is " + Object.getOwnPropertyNames(window))
DatMap = new window.Map()
//alert(DatMap)
console.log("SC has " + Object.keys(window.SC).length)
console.log("SC is " + Object.getOwnPropertyNames(window.SC))
console.log("SC.Widget() has " +         Object.getOwnPropertyNames(window.SC.Widget("lure")))
//setTimeout(LoadWidget, 1000)
function GotIt(response) {
    //alert("GotIt is now running")
    //alert(response)
    i = 0
    for(key in response) {
        i = i + 1
    }
    //alert(i)
    i = i - 1
    //playNextTrack()
    MyWidget.play()
    //alert(Object.keys(MyWidget).length)
    //alert("Properties of MyWidget: " +     Object.getOwnPropertyNames(MyWidget))
    MyWidget.bind(SC.Widget.Events.FINISH, playNextTrack())

}
function reBind() {
    MyWidget.bind(SC.Widget.Events.FINISH, playNextTrack())
}
function playNextTrack() {
    console.log(alert("playNextTrack fired."))
    MyWidget.skip(Math.floor((Math.random() * i) + 0));
    MyWidget.bind(C.Widget.Events.PLAY, reBind())
}
function LoadWidget() {
    MyWidget = window.SC.Widget("lure");
    //alert(Object.keys(MyWidget.getSounds(GotIt)).length)
    GetSounds = Object.keys(MyWidget.getSounds(GotIt)).length
}
//tracks = window.SC.Widget('/user/183/tracks')
//alert(window.SC.get(iframeElementID))
//alert('Latest track: ' + tracks[0].title);
</script>
<script type="text/javascript">

</script>
</code>```

Thanks in advance!

答: This should be fixed now. Please try again and let us know if there is still a problem!</p>

Body:
I successfully bound SC.Widget.Events.FINISH to my widget, but it won't run more than once. I read that this issue was fixed it 2013, but it's still present. (I recall this code working last year, or the year before that, so it must be a new iteration of the same bug.

Here's my code:

<audio src="intro.mp3" type="audio/mp3"></audio>

Thanks in advance!


问:
Altering Linux with Buildroot
Could you please tell me how can I use Buildroot on the image of Ubuntu, remove some of its parts such as graphics, and save the image file of a lighter Ubuntu?</p>

答:
This is not possible with Buildroot. Buildroot builds a system from scratch, it is not meant to alter an existing system.

You may want to start out with reading the Buildroot manual if you want to understand what Buildroot does.

Title: Altering Linux with Buildroot


问:
JavaScript - Google API lat/lng from country name
I wonder why this does not work, it perfectly logs Object {lat: 52.132633, lng: 5.291265999999999}. But only the console.log() inside the done() function works. To other one does not work, while I return that exact variable...

```<code>function getLatLng() {
    var LatLng;
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    })
    .done(function(data) {
        LatLng = data.results[0];
        console.log(LatLng);
    })
    return LatLng;
}

console.log(getLatLng());
</code>```

I need some workaround so that I can make the initMap() function work with my lattitude and longitude variables:

```<code>function getLatLng() {
    var LatLng;
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    })
    .done(function(data) {
        LatLng = data.results[0];
        console.log(LatLng);
    })
    return LatLng;
}

console.log(getLatLng()); // undefined

  function initMap() {

    var styledMapType = new google.maps.StyledMapType(
        [],
        {name: 'Styled Map'});

    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: latVal, lng: lngVal}, // error >>> undefined
      zoom: 11,
      mapTypeControlOptions: {
        mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
                'styled_map']
      }
    });

    map.mapTypes.set('styled_map', styledMapType);
    map.setMapTypeId('styled_map');
  }
</code>```

答:
This is because the call to the google api is asynchronous.
This means the outer console log is executed while the response from google is still pending.

You could write it like this:

```<code>function getLatLng() {
    return $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    });
}

getLatLng().done(function(data) {
    var latlng = data.results[0];
    console.log(latlng);
    //...further processing
});
</code>```

If you need access to latlng outside the done function you could rewrite as so:

```<code>function getLatLngPromise() {
    return new Promise(function(resolve) {
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
            type: 'GET',
            dataType: 'json',
        }).done(function(data) {
            resolve(data);
        });
    });
}

async function getLatLng() {
    var data = await getLatLngPromise();
    return data[0];
}

var latlng = getLatLng();
console.log(latlng);
</code>```

Or you could parametrize the initMap with a latlng parameter and move the initMap call to the done function of my first example. (pastebin.com/VpSUma9R)

Body:
I wonder why this does not work, it perfectly logs Object {lat: 52.132633, lng: 5.291265999999999}. But only the console.log() inside the done() function works. To other one does not work, while I return that exact variable...

function getLatLng() {
    var LatLng;
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    })
    .done(function(data) {
        LatLng = data.results[0];
        console.log(LatLng);
    })
    return LatLng;
}

console.log(getLatLng());

I need some workaround so that I can make the initMap() function work with my lattitude and longitude variables:

function getLatLng() {
    var LatLng;
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    })
    .done(function(data) {
        LatLng = data.results[0];
        console.log(LatLng);
    })
    return LatLng;
}

console.log(getLatLng()); // undefined

  function initMap() {

    var styledMapType = new google.maps.StyledMapType(
        [],
        {name: 'Styled Map'});

    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: latVal, lng: lngVal}, // error >>> undefined
      zoom: 11,
      mapTypeControlOptions: {
        mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
                'styled_map']
      }
    });

    map.mapTypes.set('styled_map', styledMapType);
    map.setMapTypeId('styled_map');
  }

Body:
This is because the call to the google api is asynchronous.
This means the outer console log is executed while the response from google is still pending.

You could write it like this:

function getLatLng() {
    return $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    });
}

getLatLng().done(function(data) {
    var latlng = data.results[0];
    console.log(latlng);
    //...further processing
});

If you need access to latlng outside the done function you could rewrite as so:

function getLatLngPromise() {
    return new Promise(function(resolve) {
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
            type: 'GET',
            dataType: 'json',
        }).done(function(data) {
            resolve(data);
        });
    });
}

async function getLatLng() {
    var data = await getLatLngPromise();
    return data[0];
}

var latlng = getLatLng();
console.log(latlng);

Or you could parametrize the initMap with a latlng parameter and move the initMap call to the done function of my first example. (pastebin.com/VpSUma9R)


问:
What is equivalent query in yii2
As search filtering is not working when use findbysql in yii2 searchmodel, so I want to write an equivalent query of "SELECT * FROM challan WHERE id IN (SELECT MAX(id) FROM challan GROUP BY sid)" in Yii2

答:
I have found answer after spending many hours and here it is</p>

```<code>Challan::find()->Where(['challan.id' => Challan::find()->select(['MAX(id)'])->groupBy('sid')]);
</code>```

Title: What is equivalent query in yii2

Body:
I have found answer after spending many hours and here it is

Challan::find()->Where(['challan.id' => Challan::find()->select(['MAX(id)'])->groupBy('sid')]);


问:
Equivalent of apply() by row in the tidyverse?
I want to insert a new column into a data.frame, which value is TRUE when there is at least one missing value in the row and FALSE otherwise.

For that problem, apply is a a perfect use case:

 EDIT - added example

```<code>tab <- data.frame(a = 1:10, b = c(NA, letters[2:10]), c = c(LETTERS[1:9], NA))

tab$missing <- apply(tab, 1, function(x) any(is.na(x)))
</code>```

However, I loaded the strict package, and got this error: apply() coerces X to a matrix so is dangerous to use with data frames.Please use lapply() instead.

I know that I can safely ignore this error, however, I was wondering if there was a way to code it using one of the tidyverse packages, in a simple manner. I tried unsuccessfully with dplyr:

```<code>tab %>%
  rowwise() %>%
  mutate(missing = any(is.na(.), na.rm = TRUE))
</code>```

答:
This works for the example data:</p>

```<code>library(tidyverse)

tab <- data_frame(a = 1:10,
                  b = c(NA, letters[2:10]),
                  c = c(LETTERS[1:9], NA))

tab_1 <- tab %>% mutate(missing = ifelse(is.na(b), TRUE, ifelse(is.na(c), TRUE, FALSE)))

> tab_1
    a    b    c missing
1   1 <NA>    A    TRUE
2   2    b    B   FALSE
3   3    c    C   FALSE
4   4    d    D   FALSE
5   5    e    E   FALSE
6   6    f    F   FALSE
7   7    g    G   FALSE
8   8    h    H   FALSE
9   9    i    I   FALSE
10 10    j <NA>    TRUE
</code>```

Body:
I want to insert a new column into a data.frame, which value is TRUE when there is at least one missing value in the row and FALSE otherwise.

For that problem, apply is a a perfect use case:

 EDIT - added example

tab <- data.frame(a = 1:10, b = c(NA, letters[2:10]), c = c(LETTERS[1:9], NA))

tab$missing <- apply(tab, 1, function(x) any(is.na(x)))

However, I loaded the strict package, and got this error: apply() coerces X to a matrix so is dangerous to use with data frames.Please use lapply() instead.

I know that I can safely ignore this error, however, I was wondering if there was a way to code it using one of the tidyverse packages, in a simple manner. I tried unsuccessfully with dplyr:

tab %>%
  rowwise() %>%
  mutate(missing = any(is.na(.), na.rm = TRUE))

Body:
This works for the example data:

library(tidyverse)

tab <- data_frame(a = 1:10,
                  b = c(NA, letters[2:10]),
                  c = c(LETTERS[1:9], NA))

tab_1 <- tab %>% mutate(missing = ifelse(is.na(b), TRUE, ifelse(is.na(c), TRUE, FALSE)))

> tab_1
    a    b    c missing
1   1 <NA>    A    TRUE
2   2    b    B   FALSE
3   3    c    C   FALSE
4   4    d    D   FALSE
5   5    e    E   FALSE
6   6    f    F   FALSE
7   7    g    G   FALSE
8   8    h    H   FALSE
9   9    i    I   FALSE
10 10    j <NA>    TRUE


问:
Configuring an MSI file to launch and kill a program upon installation
I have an application I've developed in Visual Studio 2010 and need to configure the installer (as a .msi file) to launch the program and then kill the task. I have a custom action in the msi to launch the program, but I'm having trouble adding a step to kill the task as well. Any suggestions would be great. Thank you!</p>

答:
You will need to create a custom action in order to handle this. Windows Installer doesn't have a kill process event. Below is a native C++ app that I created to handle this.</p>

```<code>// KillProc.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"

#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <algorithm>
#include <string>

BOOL KillProcess(_TCHAR* szProcessToKill);
TCHAR* AcTcharlower(TCHAR *pString);

int _tmain(int argc, _TCHAR* argv[])
{

    if(argc > 1){
        KillProcess(argv[1]);
    }else{
        // No Process found
    }
    return 0;
}

BOOL KillProcess(_TCHAR* szProcessToKill){
    HANDLE hProcessSnap;
    HANDLE hProcess;
    PROCESSENTRY32 processEntry32;
    LPWSTR lpszBuffer = new TCHAR[MAX_PATH];
    LPWSTR lpszProcessToKill = new TCHAR[MAX_PATH];
    lpszProcessToKill = AcTcharlower(szProcessToKill);
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);  // Takes a snapshot of all the processes
    if(hProcessSnap == INVALID_HANDLE_VALUE){
        return( FALSE );
    }

    processEntry32.dwSize = sizeof(PROCESSENTRY32);
    if(!Process32First(hProcessSnap, &processEntry32))
    {
        CloseHandle(hProcessSnap);
        return( FALSE );
    }

    do
    {
        lpszBuffer = processEntry32.szExeFile;
        if(!wcsicmp(lpszBuffer,szProcessToKill)){    // Is this our Process
            hProcess = OpenProcess(PROCESS_TERMINATE,0, processEntry32.th32ProcessID);  // It is so get the process handle
            TerminateProcess(hProcess,0);
            CloseHandle(hProcess);
        }
    }while(Process32Next(hProcessSnap,&processEntry32));  // gets next member of snapshot

    CloseHandle(hProcessSnap);  // closes the snapshot handle
    return( TRUE );
}

TCHAR* AcTcharlower(TCHAR *pString)
{
    static TCHAR pBuffer[MAX_PATH];
    TCHAR *s = pString;
    TCHAR *t = pBuffer;
    while (*s != '\0')
    {
        *t = tolower(*s);
        s++;
        t++;
    }
    return(pBuffer);
}
</code>```

Body:
You will need to create a custom action in order to handle this. Windows Installer doesn't have a kill process event. Below is a native C++ app that I created to handle this.

// KillProc.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"

#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <algorithm>
#include <string>

BOOL KillProcess(_TCHAR* szProcessToKill);
TCHAR* AcTcharlower(TCHAR *pString);

int _tmain(int argc, _TCHAR* argv[])
{

    if(argc > 1){
        KillProcess(argv[1]);
    }else{
        // No Process found
    }
    return 0;
}

BOOL KillProcess(_TCHAR* szProcessToKill){
    HANDLE hProcessSnap;
    HANDLE hProcess;
    PROCESSENTRY32 processEntry32;
    LPWSTR lpszBuffer = new TCHAR[MAX_PATH];
    LPWSTR lpszProcessToKill = new TCHAR[MAX_PATH];
    lpszProcessToKill = AcTcharlower(szProcessToKill);
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);  // Takes a snapshot of all the processes
    if(hProcessSnap == INVALID_HANDLE_VALUE){
        return( FALSE );
    }

    processEntry32.dwSize = sizeof(PROCESSENTRY32);
    if(!Process32First(hProcessSnap, &processEntry32))
    {
        CloseHandle(hProcessSnap);
        return( FALSE );
    }

    do
    {
        lpszBuffer = processEntry32.szExeFile;
        if(!wcsicmp(lpszBuffer,szProcessToKill)){    // Is this our Process
            hProcess = OpenProcess(PROCESS_TERMINATE,0, processEntry32.th32ProcessID);  // It is so get the process handle
            TerminateProcess(hProcess,0);
            CloseHandle(hProcess);
        }
    }while(Process32Next(hProcessSnap,&processEntry32));  // gets next member of snapshot

    CloseHandle(hProcessSnap);  // closes the snapshot handle
    return( TRUE );
}

TCHAR* AcTcharlower(TCHAR *pString)
{
    static TCHAR pBuffer[MAX_PATH];
    TCHAR *s = pString;
    TCHAR *t = pBuffer;
    while (*s != '\0')
    {
        *t = tolower(*s);
        s++;
        t++;
    }
    return(pBuffer);
}