问:
Version Deprecation Facebook Graph API v2.2
our Facebook Login is not working right now. We have received a message from Facebook Developer Portal:

"Name of app" currently has access to Graph API v2.2 which will reach the end of its
  2-year lifetime on 27 March, 2017. To ensure a smooth transition,
  please migrate all calls to Graph API v2.3 or higher.

To check if your app will be affected by this upgrade you can use the
  Version Upgrade Tool. This will show you which calls, if any, are
  affected by this change as well as any replacement calls in newer
  versions. If you do not see any calls, your app may not be affected by
  this change.

You can also use our changelog to see the full list of changes in all
  Graph API versions.

We are using ASP.NET MVC 5, and we are using or authentication like this:

```<code>var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId = "****",
                AppSecret = "****",
                AuthenticationType = "Facebook",
                SignInAsAuthenticationType = "ExternalCookie",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async ctx => ctx.Identity.AddClaim(new Claim(ClaimTypes.Email, ctx.User["email"].ToString()))
                }
            };

            facebookAuthenticationOptions.Scope.Add("email");
</code>```

But today, our login info object, is null in ExternalLoginCallback:

```<code>        [HttpGet]
        [AllowAnonymous]
        [RequireHttps]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null)
        {
            try
            {
                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (loginInfo == null)
                {
                    return RedirectToAction("Login");
                }
... more code here...
</code>```

In Facebook Dev. Portal our API Version is 2.3

We have tested many options, with no results:

Access email address in the OAuth ExternalLoginCallback from Facebook v2.4 API in ASP.NET MVC 5

Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?

Thank you much for the help.

答:
I had the same problem and here is how I managed to fix it and get the email from Facebook.

Update following NuGet Pacakges

Microsoft.Owin to version 3.1.0-rc1

Microsoft.Owin.Security to version 3.1.0-rc1

Microsoft.Owin.Security.Cookies to version 3.1.0-rc1

Microsoft.Owin.Security.OAuth to version 3.1.0-rc1

Microsoft.Owin.Security.Facebook to version 3.1.0-rc1

Then add the following code to the Identity Startup class

```<code>var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);
</code>```

This is the definition class for FacebookBackChannelHandler():

```<code>using System;
using System.Net.Http;

public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        System.Threading.CancellationToken cancellationToken)
    {
        // Replace the RequestUri so it's not malformed
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
</code>```

Body:
our Facebook Login is not working right now. We have received a message from Facebook Developer Portal:

"Name of app" currently has access to Graph API v2.2 which will reach the end of its
  2-year lifetime on 27 March, 2017. To ensure a smooth transition,
  please migrate all calls to Graph API v2.3 or higher.

To check if your app will be affected by this upgrade you can use the
  Version Upgrade Tool. This will show you which calls, if any, are
  affected by this change as well as any replacement calls in newer
  versions. If you do not see any calls, your app may not be affected by
  this change.

You can also use our changelog to see the full list of changes in all
  Graph API versions.

We are using ASP.NET MVC 5, and we are using or authentication like this:

var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId = "****",
                AppSecret = "****",
                AuthenticationType = "Facebook",
                SignInAsAuthenticationType = "ExternalCookie",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async ctx => ctx.Identity.AddClaim(new Claim(ClaimTypes.Email, ctx.User["email"].ToString()))
                }
            };

            facebookAuthenticationOptions.Scope.Add("email");

But today, our login info object, is null in ExternalLoginCallback:

        [HttpGet]
        [AllowAnonymous]
        [RequireHttps]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null)
        {
            try
            {
                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (loginInfo == null)
                {
                    return RedirectToAction("Login");
                }
... more code here...

In Facebook Dev. Portal our API Version is 2.3

We have tested many options, with no results:

Access email address in the OAuth ExternalLoginCallback from Facebook v2.4 API in ASP.NET MVC 5

Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?

Thank you much for the help.

Body:
I had the same problem and here is how I managed to fix it and get the email from Facebook.

Update following NuGet Pacakges

Microsoft.Owin to version 3.1.0-rc1

Microsoft.Owin.Security to version 3.1.0-rc1

Microsoft.Owin.Security.Cookies to version 3.1.0-rc1

Microsoft.Owin.Security.OAuth to version 3.1.0-rc1

Microsoft.Owin.Security.Facebook to version 3.1.0-rc1

Then add the following code to the Identity Startup class

var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);

This is the definition class for FacebookBackChannelHandler():

using System;
using System.Net.Http;

public class FacebookBackChannelHandler : HttpClientHandler
{
    protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        System.Threading.CancellationToken cancellationToken)
    {
        // Replace the RequestUri so it's not malformed
        if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
        {
            request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
        }

        return await base.SendAsync(request, cancellationToken);
    }
}


来源: stackexchange

问:
Meteor Reactivity Using a Collection and SubCollection (e.g. Reactive Joins)
Is it possible to implement reactivity by a sub-class with a transformed collection?

This is the example code of jamgold on the Meteor forum; the sub-class subcollection is joined to the main-class collection_name. If something changes on the collection_name collection, Meteor is in fact reactive. However, when something changes on the sub-collection subcollection, this is not reactively pushed to this publish/subscription.

```<code>Collection = new Meteor.Collection('collection_name');
if(Meteor.isServer)
{
    Meteor.publish('collection', function(query,options) {
        var self = this;
        var handler = null;
        query = query == undefined ? {} : query;
        options = options == undefined ? {} : options;
        //
        handler = Collection.find(query,options).observeChanges({
            added: function (id, doc) {
                var object = null;
                doc.object = Meteor.subcollection.findOne({_id: doc.objectId},);
                self.added('collection_name', id, doc);
            },
            changed: function (id, fields) {
                self.changed('collection_name', id, fields);
            },
            removed: function (id) {
                self.removed('collection_name', id);
            }
        });
        self.ready();
        self.onStop(function () {
            if(handler) handler.stop();
        });
    });
}

if(Meteor.isClient)
{
    Meteor.subscribe('collection');
}
</code>```

答:
To make it reactive for the SubCollection, you would need to also observe it's changes as well.  Keep in mind that this becomes very complex fast and my example only works if there is a 1 to 1 relationship between your Collection and SubCollection.  You could implement something that works for a 1 to many relationship, but you will have some logic issues to address (e.g. when a doc in SubCollection changes...does that invalidate all associated Collection docs that were already published with that SubCollection doc.  If so then do you emit a removed then an added to re-send them with their updated SubCollection doc, etc.).

Here is the full example.

```<code>const Collection = new Meteor.Collection('collection_name');
const SubCollection = new Meteor.Collection('sub_collection_name');

if (Meteor.isServer) {
  Meteor.publish('collection', function(query,options) {
    var self = this;
    var handler = null;
    query = query == undefined ? {} : query;
    options = options == undefined ? {} : options;

        // enable reactivity for Collection
    handler = Collection.find(query, options).observeChanges({
        added: function (id, doc) {
          // find the associated object (using it's id) and add it to the doc
          doc.object = SubCollection.findOne({_id: doc.objectId});

                    // now pass the original doc + the associated object down to client
          self.added('collection_name', id, doc);
        },
        changed: function (id, fields) {
                    // doc.object is assumed to already exist on the doc...so just notify the subscriber
                    // of the changes in Collection
          self.changed('collection_name', id, fields);
        },
        removed: function (id) {
                    // doc.object is assumed to already exist on the doc...so just notify the subscriber
                    // of the changes in Collection
          self.removed('collection_name', id);
        }
    });

        var handleSubCollectionDocChange = function(callbackThis, id) {
            // find the doc from Collection that has a reference to the new SubCollection doc
            var parentCollectionDoc = Collection.findOne({objectId: id});

            // only do something if one exists
            if (parentCollectionDoc) {
                // remove the previously published doc since the SubCollection doc changed (if it was previously published)
                self.removed('collection_name', parentCollectionDoc._id);

                // store the new SubCollection doc in Collection.object
                parentCollectionDoc.object = doc;

                // send down the Collection doc (with new SubCollection doc attached)
                self.added('collection_name', parentCollectionDoc._id, parentCollectionDoc);
            }
        };

        // enable reactivity for SubCollection
        subhandler = SubCollection.find().observeChanges({
          added: function (id, doc) {
                // find the doc from Collection that has a reference to the new SubCollection doc
                var parentCollectionDoc = Collection.findOne({objectId: id});

                // only do something if one exists
                if (parentCollectionDoc) {
                    // remove the previously published doc since the SubCollection doc changed (if it was previously published)
                    self.removed('collection_name', parentCollectionDoc._id);

                    // store the new SubCollection doc in Collection.object
                    parentCollectionDoc.object = doc;

                    // send down the Collection doc (with new SubCollection doc attached)
                self.added('collection_name', parentCollectionDoc._id, parentCollectionDoc);
                }
          },
          changed: function (id, fields) {
                // get the full SubCollection doc (since we only get the fields that actually changed)
                var doc = SubCollection.findOne({_id: id});

                // find the doc from Collection that has a reference to the new SubCollection doc
                var parentCollectionDoc = Collection.findOne({objectId: id});

                // only do something if one exists
                if (parentCollectionDoc) {
                    // remove the previously published doc since the SubCollection doc changed (if it was previously published)
                    self.removed('collection_name', parentCollectionDoc._id);

                    // store the new SubCollection doc in Collection.object
                    parentCollectionDoc.object = doc;

                    // send down the Collection doc (with new SubCollection doc attached)
                self.added('collection_name', parentCollectionDoc._id, parentCollectionDoc);
                }
          },
          removed: function (id) {
                // find the doc from Collection that has a reference to the new SubCollection doc
                var parentCollectionDoc = Collection.findOne({objectId: id});

                // only do something if one exists
                if (parentCollectionDoc) {
                    // remove the previously published doc since the SubCollection doc no longer exists (if it was previously published)
                self.removed('collection_name', parentCollectionDoc._id);
                }
          }
        });

    self.ready();
    self.onStop(function () {
        if (handler) handler.stop();
                if (subhandler) subhandler.stop();
    });
  });
}
</code>```

With that said, if you are only trying to achieve reactive joins then you really should look into the Meteor Publish Composite package.  It handles reactive joins very easily and will keep your publication up to date with the parent collection changes or any of the child collections change.

Here is what a publication would look like (based on your example) using publish composite.

```<code>const Collection = new Meteor.Collection('collection_name');
const SubCollection = new Meteor.Collection('sub_collection_name');

Meteor.publishComposite('collection', function(query, options) {
  query = query == undefined ? {} : query;
  options = options == undefined ? {} : options;

  return {
    find: function() {
      return Collection.find(query,options);
    },
    children: [{
      find: function(collectionDoc) {
        return SubCollection.find({_id: collectionDoc.objectId});
      }
    }],
  };
});
</code>```

With this example, anytime Collection or associated SubCollection docs change they will be sent to the client.

The only gotcha with this approach is that it publishes the docs into their respective collections.  So you would have to perform the join (SubDocument lookup) on the client.  Assuming we have subscribed to the above publication and we wanted to get a SubCollection doc for a certain Collection doc on the client, then it would look like this.

```<code>// we are on the client now
var myDoc = Collection.findOne({ //..search selector ..// });
myDoc.object = SubCollection.findOne({_id: myDoc.objectId});
</code>```

The composite publication ensures that the latest SubCollection doc is always on the client.  The only problem with the above approach is that if your SubCollection doc changes and is published to the client, your data will be stale because you have stored an static (and unreactive) version of the SubCollection doc in myDoc.object.

The way around this is to only perform your join when you need it and don't store the results.  Or, another option is to use the Collection Helpers package and create a helper function that dynamically does the join for you.

```<code>// we are on the client now
Collection.helpers({
  object: function() {
    return SubCollection.findOne({_id: myDoc.objectId});
  },
});
</code>```

With this helper in place, anytime you need access to the joined SubCollection doc you would access it like this.

```<code>var myDoc = Collection.findOne({ //..search selector ..// });
console.dir(myDoc.object);
</code>```

Under the covers, the collection helper does the SubCollection lookup for you.

So long story short, take your pick (roll your own reactive join publication or use Publish Composite + Collection Helpers).  My recommendation is to use the packages because it's a tried and true solution that works as advertised out of the box (fyi...I use this combination in several of my Meteor apps).

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to implement reactivity by a sub-class with a transformed collection?

This is the example code of jamgold on the Meteor forum; the sub-class subcollection is joined to the main-class collection_name. If something changes on the collection_name collection, Meteor is in fact reactive. However, when something changes on the sub-collection subcollection, this is not reactively pushed to this publish/subscription.

Collection = new Meteor.Collection('collection_name');
if(Meteor.isServer)
{
    Meteor.publish('collection', function(query,options) {
        var self = this;
        var handler = null;
        query = query == undefined ? {} : query;
        options = options == undefined ? {} : options;
        //
        handler = Collection.find(query,options).observeChanges({
            added: function (id, doc) {
                var object = null;
                doc.object = Meteor.subcollection.findOne({_id: doc.objectId},);
                self.added('collection_name', id, doc);
            },
            changed: function (id, fields) {
                self.changed('collection_name', id, fields);
            },
            removed: function (id) {
                self.removed('collection_name', id);
            }
        });
        self.ready();
        self.onStop(function () {
            if(handler) handler.stop();
        });
    });
}

if(Meteor.isClient)
{
    Meteor.subscribe('collection');
}

Body:
To make it reactive for the SubCollection, you would need to also observe it's changes as well.  Keep in mind that this becomes very complex fast and my example only works if there is a 1 to 1 relationship between your Collection and SubCollection.  You could implement something that works for a 1 to many relationship, but you will have some logic issues to address (e.g. when a doc in SubCollection changes...does that invalidate all associated Collection docs that were already published with that SubCollection doc.  If so then do you emit a removed then an added to re-send them with their updated SubCollection doc, etc.).

Here is the full example.

const Collection = new Meteor.Collection('collection_name');
const SubCollection = new Meteor.Collection('sub_collection_name');

if (Meteor.isServer) {
  Meteor.publish('collection', function(query,options) {
    var self = this;
    var handler = null;
    query = query == undefined ? {} : query;
    options = options == undefined ? {} : options;

        // enable reactivity for Collection
    handler = Collection.find(query, options).observeChanges({
        added: function (id, doc) {
          // find the associated object (using it's id) and add it to the doc
          doc.object = SubCollection.findOne({_id: doc.objectId});

                    // now pass the original doc + the associated object down to client
          self.added('collection_name', id, doc);
        },
        changed: function (id, fields) {
                    // doc.object is assumed to already exist on the doc...so just notify the subscriber
                    // of the changes in Collection
          self.changed('collection_name', id, fields);
        },
        removed: function (id) {
                    // doc.object is assumed to already exist on the doc...so just notify the subscriber
                    // of the changes in Collection
          self.removed('collection_name', id);
        }
    });

        var handleSubCollectionDocChange = function(callbackThis, id) {
            // find the doc from Collection that has a reference to the new SubCollection doc
            var parentCollectionDoc = Collection.findOne({objectId: id});

            // only do something if one exists
            if (parentCollectionDoc) {
                // remove the previously published doc since the SubCollection doc changed (if it was previously published)
                self.removed('collection_name', parentCollectionDoc._id);

                // store the new SubCollection doc in Collection.object
                parentCollectionDoc.object = doc;

                // send down the Collection doc (with new SubCollection doc attached)
                self.added('collection_name', parentCollectionDoc._id, parentCollectionDoc);
            }
        };

        // enable reactivity for SubCollection
        subhandler = SubCollection.find().observeChanges({
          added: function (id, doc) {
                // find the doc from Collection that has a reference to the new SubCollection doc
                var parentCollectionDoc = Collection.findOne({objectId: id});

                // only do something if one exists
                if (parentCollectionDoc) {
                    // remove the previously published doc since the SubCollection doc changed (if it was previously published)
                    self.removed('collection_name', parentCollectionDoc._id);

                    // store the new SubCollection doc in Collection.object
                    parentCollectionDoc.object = doc;

                    // send down the Collection doc (with new SubCollection doc attached)
                self.added('collection_name', parentCollectionDoc._id, parentCollectionDoc);
                }
          },
          changed: function (id, fields) {
                // get the full SubCollection doc (since we only get the fields that actually changed)
                var doc = SubCollection.findOne({_id: id});

                // find the doc from Collection that has a reference to the new SubCollection doc
                var parentCollectionDoc = Collection.findOne({objectId: id});

                // only do something if one exists
                if (parentCollectionDoc) {
                    // remove the previously published doc since the SubCollection doc changed (if it was previously published)
                    self.removed('collection_name', parentCollectionDoc._id);

                    // store the new SubCollection doc in Collection.object
                    parentCollectionDoc.object = doc;

                    // send down the Collection doc (with new SubCollection doc attached)
                self.added('collection_name', parentCollectionDoc._id, parentCollectionDoc);
                }
          },
          removed: function (id) {
                // find the doc from Collection that has a reference to the new SubCollection doc
                var parentCollectionDoc = Collection.findOne({objectId: id});

                // only do something if one exists
                if (parentCollectionDoc) {
                    // remove the previously published doc since the SubCollection doc no longer exists (if it was previously published)
                self.removed('collection_name', parentCollectionDoc._id);
                }
          }
        });

    self.ready();
    self.onStop(function () {
        if (handler) handler.stop();
                if (subhandler) subhandler.stop();
    });
  });
}

With that said, if you are only trying to achieve reactive joins then you really should look into the Meteor Publish Composite package.  It handles reactive joins very easily and will keep your publication up to date with the parent collection changes or any of the child collections change.

Here is what a publication would look like (based on your example) using publish composite.

const Collection = new Meteor.Collection('collection_name');
const SubCollection = new Meteor.Collection('sub_collection_name');

Meteor.publishComposite('collection', function(query, options) {
  query = query == undefined ? {} : query;
  options = options == undefined ? {} : options;

  return {
    find: function() {
      return Collection.find(query,options);
    },
    children: [{
      find: function(collectionDoc) {
        return SubCollection.find({_id: collectionDoc.objectId});
      }
    }],
  };
});

With this example, anytime Collection or associated SubCollection docs change they will be sent to the client.

The only gotcha with this approach is that it publishes the docs into their respective collections.  So you would have to perform the join (SubDocument lookup) on the client.  Assuming we have subscribed to the above publication and we wanted to get a SubCollection doc for a certain Collection doc on the client, then it would look like this.

// we are on the client now
var myDoc = Collection.findOne({ //..search selector ..// });
myDoc.object = SubCollection.findOne({_id: myDoc.objectId});

The composite publication ensures that the latest SubCollection doc is always on the client.  The only problem with the above approach is that if your SubCollection doc changes and is published to the client, your data will be stale because you have stored an static (and unreactive) version of the SubCollection doc in myDoc.object.

The way around this is to only perform your join when you need it and don't store the results.  Or, another option is to use the Collection Helpers package and create a helper function that dynamically does the join for you.

// we are on the client now
Collection.helpers({
  object: function() {
    return SubCollection.findOne({_id: myDoc.objectId});
  },
});

With this helper in place, anytime you need access to the joined SubCollection doc you would access it like this.

var myDoc = Collection.findOne({ //..search selector ..// });
console.dir(myDoc.object);

Under the covers, the collection helper does the SubCollection lookup for you.

So long story short, take your pick (roll your own reactive join publication or use Publish Composite + Collection Helpers).  My recommendation is to use the packages because it's a tried and true solution that works as advertised out of the box (fyi...I use this combination in several of my Meteor apps).


问:
AFNetworking Crash Report in Console
In my demo, I am calling API by using AFNetworking SDK not by installing cocoapod and my code work is below,

```<code>    strURL = @"http://services.groupkt.com/country/get/all";

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:strURL parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
</code>```

This code work gives me proper result as per the API but during API call I got following crash report in my console.

Does anyone knows what are these errors are and how to solve it?

Thanks.

答:
It might be an Apple's internal bug and you may also need to update the version of Xcode to the latest one (8.3)

Check out the following answer

nw_host_stats_add_src recv too small, received 24, expected 28

I tested the same code as you (running Xcode 8.3) and that is my console output

Title: AFNetworking Crash Report in Console

Body:
In my demo, I am calling API by using AFNetworking SDK not by installing cocoapod and my code work is below,

    strURL = @"http://services.groupkt.com/country/get/all";

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:strURL parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

This code work gives me proper result as per the API but during API call I got following crash report in my console.

Does anyone knows what are these errors are and how to solve it?

Thanks.


问:
Database stored procedure create string based on format string like sprintf
Sybase ASE has a format-string based print statement:

```<code>print 'some value: %1!, some other value: %2!, info: %3!, @val1, @val2, @val3
</code>```

I would like to create VARCHAR-information in the same manner, but I can't manage to find a function which allows to do this as conveniently. It seems the only option is to concatenate the results of CONVERT() functions.

Is there similar functionality not for printing but for writing to variables?

答:
I think, this not any so function.

Use:

```<code>SET @str = REPLACE(REPLACE(REPLACE( 'some value: %1!, some other value: %2!, info: %3!', '%1', @val1 ),  '%2', @val2), '%3', @val3)
</code>```

Body:
Sybase ASE has a format-string based print statement:

print 'some value: %1!, some other value: %2!, info: %3!, @val1, @val2, @val3

I would like to create VARCHAR-information in the same manner, but I can't manage to find a function which allows to do this as conveniently. It seems the only option is to concatenate the results of CONVERT() functions.

Is there similar functionality not for printing but for writing to variables?

Body:
I think, this not any so function.

Use:

SET @str = REPLACE(REPLACE(REPLACE( 'some value: %1!, some other value: %2!, info: %3!', '%1', @val1 ),  '%2', @val2), '%3', @val3)


问:
allocating memory using calloc and freeing
gcc 4.4.4 c89

I have a program that I am testing. I create a struct object called devname and allocate memory so that I can fill the elements. I display them and then free the memory that was allocated.

However, I am getting the following error:

```<code>invalid operands to binary != (have ‘struct Devices_names’ and ‘void *’)
</code>```

That is in my for loop for displaying the structure elements. However, I feel I am testing for a NULL pointer.

Just a further question, is there an problem with the free?

Many thanks for any advice,

```<code>#include <stdio.h>
#include <stdlib.h>

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;

static void g_create_device_names(size_t devices);
static void g_get_device_names();
static void destroy_devices();

int main(void)
{
#define DEVICES 5
    g_create_device_names(DEVICES);

    g_get_device_names();

    destroy_devices();

    return 0;
}

static void g_create_device_names(size_t devices)
{
    size_t i = 0;
    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }

    for(i = 0; i < devices; i++) {
        devname[i].id = i;
        sprintf(devname[i].name, "device: %d", i);
    }
}

static void g_get_device_names()
{
    size_t i = 0;

    for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE
        printf("Device id --- [ %d ]\n", devname[i].id);
        printf("Device name - [ %s ]\n", devname[i].name);
    }
}

static void destroy_devices()
{
    while(devname != NULL) {
        free(devname++);
    }
}
</code>```

答:
After calloc you need only test for returned pointer to be not-null (and calloc call succeeded).

But once you callocated an array you cannot determine how many items in allocation having only pointer to it, so neither devname[i] != NULL, nor devname+i != NULL will not work, altough second will compile. Only environment or RTL know this. And this is great difference between *alloc allocation and static declaration (even it is of variable size as introduced in C99). So you NEED to store size of allocated array elsewhere.

Also remember, array (or any other memory chunk) allocated with single calloc() should be deallocated with single free() call with SAME pointer as returned by malloc. Passing any other pointer to free() cause undefined behaviaour (which is often FAIL).

So your code should be:

```<code>static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;
size_t devicecount;

...

    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }
    devicecount = devices;

...

    for(i = 0; i<devicecount; i++) { // <-- no error more here

...

static void destroy_devices()
{
    free(devname);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
gcc 4.4.4 c89

I have a program that I am testing. I create a struct object called devname and allocate memory so that I can fill the elements. I display them and then free the memory that was allocated.

However, I am getting the following error:

invalid operands to binary != (have ‘struct Devices_names’ and ‘void *’)

That is in my for loop for displaying the structure elements. However, I feel I am testing for a NULL pointer.

Just a further question, is there an problem with the free?

Many thanks for any advice,

#include <stdio.h>
#include <stdlib.h>

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;

static void g_create_device_names(size_t devices);
static void g_get_device_names();
static void destroy_devices();

int main(void)
{
#define DEVICES 5
    g_create_device_names(DEVICES);

    g_get_device_names();

    destroy_devices();

    return 0;
}

static void g_create_device_names(size_t devices)
{
    size_t i = 0;
    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }

    for(i = 0; i < devices; i++) {
        devname[i].id = i;
        sprintf(devname[i].name, "device: %d", i);
    }
}

static void g_get_device_names()
{
    size_t i = 0;

    for(i = 0; devname[i] != NULL; i++) { <-- ERROR HERE
        printf("Device id --- [ %d ]\n", devname[i].id);
        printf("Device name - [ %s ]\n", devname[i].name);
    }
}

static void destroy_devices()
{
    while(devname != NULL) {
        free(devname++);
    }
}

Body:
After calloc you need only test for returned pointer to be not-null (and calloc call succeeded).

But once you callocated an array you cannot determine how many items in allocation having only pointer to it, so neither devname[i] != NULL, nor devname+i != NULL will not work, altough second will compile. Only environment or RTL know this. And this is great difference between *alloc allocation and static declaration (even it is of variable size as introduced in C99). So you NEED to store size of allocated array elsewhere.

Also remember, array (or any other memory chunk) allocated with single calloc() should be deallocated with single free() call with SAME pointer as returned by malloc. Passing any other pointer to free() cause undefined behaviaour (which is often FAIL).

So your code should be:

static struct Devices_names {
#define MAX_NAME_LEN 80
    int id;
    char name[MAX_NAME_LEN];
} *devname;
size_t devicecount;

...

    devname = calloc(devices, sizeof *devname);
    if(devname == NULL) {
        exit(0);
    }
    devicecount = devices;

...

    for(i = 0; i<devicecount; i++) { // <-- no error more here

...

static void destroy_devices()
{
    free(devname);
}


问:
Issue with String to Date conversion after Timezone parsing
I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.

```<code>public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
        System.out.println(inputDate);
        Date convertedDate = null;
        String inputDateStr ;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone(toTimezone));

        inputDateStr = df.format(inputDate);

        System.out.println("Formatted Date In String Format: " + inputDateStr);
        //Now trying to convert it back to date
        try {
            convertedDate = df.parse(inputDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }

    public static void main(String args[]) {
        System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
    }
</code>```

Output is

```<code>Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017
</code>```

The formatted date in string and date format in output is different.

答: Date instance does not retain any formatting information. For further details look at the Stackoverflow question. You will get your answer with a better insight to the Date object.</p>

Body:
I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.

public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
        System.out.println(inputDate);
        Date convertedDate = null;
        String inputDateStr ;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone(toTimezone));

        inputDateStr = df.format(inputDate);

        System.out.println("Formatted Date In String Format: " + inputDateStr);
        //Now trying to convert it back to date
        try {
            convertedDate = df.parse(inputDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }

    public static void main(String args[]) {
        System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
    }

Output is

Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017

The formatted date in string and date format in output is different.


问:
Simple web crawler very slow
I have built a very simple web crawler to crawl ~100 small json files in the URL below. The issue is that the crawler takes more than an hour to complete. I find that hard to understand given how small the json files are. Am I doing something fundamentally wrong here?</p>

```<code>def get_senate_vote(vote):
    URL = 'https://www.govtrack.us/data/congress/113/votes/2013/s%d/data.json' % vote
    response = requests.get(URL)
    json_data = json.loads(response.text)
    return json_data

def get_all_votes():
    all_senate_votes = []
    URL = "http://www.govtrack.us/data/congress/113/votes/2013"
    response = requests.get(URL)
    root = html.fromstring(response.content)
    for a in root.xpath('/html/body/pre/a'):
        link = a.xpath('text()')[0].strip()
        if link[0] == 's':
            vote = int(link[1:-1])
            try:
                vote_json = get_senate_vote(vote)
            except:
                return all_senate_votes
            all_senate_votes.append(vote_json)

    return all_senate_votes

vote_data = get_all_votes()
</code>```

答:
Here is a rather simple code sample, I've calculated the time taken for each call. On my system its taking on an average 2 secs per request, and there are 582 pages to visit, so around 19 mins without printing the JSON to the console. In your case network time plus print time may increase it.

```<code>#!/usr/bin/python

import requests
import re
import time
def find_votes():
    r=requests.get("https://www.govtrack.us/data/congress/113/votes/2013/")
    data = r.text
    votes = re.findall('s\d+',data)
    return votes

def crawl_data(votes):
    print("Total pages: "+str(len(votes)))
    for x in votes:
        url ='https://www.govtrack.us/data/congress/113/votes/2013/'+x+'/data.json'
        t1=time.time()
        r=requests.get(url)
        json = r.json()
        print(time.time()-t1)
crawl_data(find_votes())
</code>```

Title: Simple web crawler very slow

Body:
I have built a very simple web crawler to crawl ~100 small json files in the URL below. The issue is that the crawler takes more than an hour to complete. I find that hard to understand given how small the json files are. Am I doing something fundamentally wrong here?

def get_senate_vote(vote):
    URL = 'https://www.govtrack.us/data/congress/113/votes/2013/s%d/data.json' % vote
    response = requests.get(URL)
    json_data = json.loads(response.text)
    return json_data

def get_all_votes():
    all_senate_votes = []
    URL = "http://www.govtrack.us/data/congress/113/votes/2013"
    response = requests.get(URL)
    root = html.fromstring(response.content)
    for a in root.xpath('/html/body/pre/a'):
        link = a.xpath('text()')[0].strip()
        if link[0] == 's':
            vote = int(link[1:-1])
            try:
                vote_json = get_senate_vote(vote)
            except:
                return all_senate_votes
            all_senate_votes.append(vote_json)

    return all_senate_votes

vote_data = get_all_votes()

Body:
Here is a rather simple code sample, I've calculated the time taken for each call. On my system its taking on an average 2 secs per request, and there are 582 pages to visit, so around 19 mins without printing the JSON to the console. In your case network time plus print time may increase it.

#!/usr/bin/python

import requests
import re
import time
def find_votes():
    r=requests.get("https://www.govtrack.us/data/congress/113/votes/2013/")
    data = r.text
    votes = re.findall('s\d+',data)
    return votes

def crawl_data(votes):
    print("Total pages: "+str(len(votes)))
    for x in votes:
        url ='https://www.govtrack.us/data/congress/113/votes/2013/'+x+'/data.json'
        t1=time.time()
        r=requests.get(url)
        json = r.json()
        print(time.time()-t1)
crawl_data(find_votes())


问:
How to retrieve data in jquery from mvc list type of model
I have a class like below:

```<code>public class CustomBenefitCommittee
{
    public bool? IsChecked { get; set; }
    public bool PropertyError { get; set; }
}
</code>```

And I am using this class as a list type in MVC model like:

```<code>@model List<CustomBenefitCommittee>
</code>```

I want to retrieve data from this model in jQuery. I am trying right now as

```<code>@{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var json = serializer.Serialize(Model);
}

var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
    $.each(model, function () {
        alert(model.PropertyError );
    });
}
</code>```

This is giving me undefind. Can someone help me out getting the values from this model.

答:
Make a loop like this:

```<code> $.each(model, function(key, value) { alert(value.PropertyError); });
</code>```

It will work.

Body:
I have a class like below:

public class CustomBenefitCommittee
{
    public bool? IsChecked { get; set; }
    public bool PropertyError { get; set; }
}

And I am using this class as a list type in MVC model like:

@model List<CustomBenefitCommittee>

I want to retrieve data from this model in jQuery. I am trying right now as

@{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var json = serializer.Serialize(Model);
}

var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
    $.each(model, function () {
        alert(model.PropertyError );
    });
}

This is giving me undefind. Can someone help me out getting the values from this model.

Body:
Make a loop like this:

 $.each(model, function(key, value) { alert(value.PropertyError); });

It will work.


问:
How to copy a string to clipboard with ng-click in AngularJS?
I want to copy link on click button in AnuglarJS. I have tried below code but I have stucked in this error:

This is my button :

```<code><button class="btn btn-info" ng-click="test2(\'' + decodeURI(data.name) + '\');" >copy</button>
</code>```

this my function in controller.js :

```<code>  $scope.test2 = function (name)
    {
        var res = 'http://example.com?from=' + name;
        var range = document.createRange();
        range.selectNode(res); // here getting error
        window.getSelection().addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy email command was ' + msg);
        } catch (err) {
            console.log('Oops, unable to copy');
        }
        window.getSelection().removeAllRanges();
    }
</code>```

click on button I want to copy this link any one can please help me how can do that.

答:
According to the selectNode() documentation range.selectNode() expects a param of type node where your node is a string -> var res = 'http://example.com?from=' + name;.

The Range.selectNode() method sets the Range to contain the Node and
  its contents. The parent Node of the start and end of the Range will
  be the same as the parent of the referenceNode.

Just create a dummy element for copy, append it to your DOM, copy it and remove it from DOM:

```<code>$scope.copyToClipboard = function (name) {
    var copyElement = document.createElement("textarea");
    copyElement.style.position = 'fixed';
    copyElement.style.opacity = '0';
    copyElement.textContent = 'http://example.com?from=' + decodeURI(name);
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyElement);
    copyElement.select();
    document.execCommand('copy');
    body.removeChild(copyElement);
}
</code>```

View

```<code><button class="btn btn-info"
        ng-click="copyToClipboard(data.name);">copy</button>
</code>```

Body:
I want to copy link on click button in AnuglarJS. I have tried below code but I have stucked in this error:

This is my button :

<button class="btn btn-info" ng-click="test2(\'' + decodeURI(data.name) + '\');" >copy</button>

this my function in controller.js :

  $scope.test2 = function (name)
    {
        var res = 'http://example.com?from=' + name;
        var range = document.createRange();
        range.selectNode(res); // here getting error
        window.getSelection().addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy email command was ' + msg);
        } catch (err) {
            console.log('Oops, unable to copy');
        }
        window.getSelection().removeAllRanges();
    }

click on button I want to copy this link any one can please help me how can do that.

Body:
According to the selectNode() documentation range.selectNode() expects a param of type node where your node is a string -> var res = 'http://example.com?from=' + name;.

The Range.selectNode() method sets the Range to contain the Node and
  its contents. The parent Node of the start and end of the Range will
  be the same as the parent of the referenceNode.

Just create a dummy element for copy, append it to your DOM, copy it and remove it from DOM:

$scope.copyToClipboard = function (name) {
    var copyElement = document.createElement("textarea");
    copyElement.style.position = 'fixed';
    copyElement.style.opacity = '0';
    copyElement.textContent = 'http://example.com?from=' + decodeURI(name);
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyElement);
    copyElement.select();
    document.execCommand('copy');
    body.removeChild(copyElement);
}

View

<button class="btn btn-info"
        ng-click="copyToClipboard(data.name);">copy</button>


问:
How to make full screen java applets?
I am designing a psychology experiment with java applets. I have to make my java applets full screen. What is the best way of doing this and how can I do this.

Since I haven't been using java applets for 3 years(The last time I've used it was for a course homework :) ) I have forgotten most of the concepts. I googled and found that link:
Dani web

But in the method described in above link you have to put a JFrame inside the applet which I have no idea how to do it.

Whatever I need a quick and dirty method b'cause I don't have much time and this is the reason why I asked it here.

Thanx in advance

答:
Why not just open a new Frame from the applet (either from the "start()" method or, preferably, after the user presses an "open" button) and set it to be maximized?

```<code>JFrame frame = new JFrame();
//more initialization code here
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(dim.width, dim.height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
</code>```

Don't forget: The JFrame should be created and opened from the EDT. Applet start() is not guaranteed to be called on that thread, so use SwingUtilities.invokeLater(). Of course, if you opt for the button route, button listener is called on the EDT, so you should be safe.

OwnerDisplayName: holydiver

Title: How to make full screen java applets?

LastEditorDisplayName: cletus

Body:
Why not just open a new Frame from the applet (either from the "start()" method or, preferably, after the user presses an "open" button) and set it to be maximized?

JFrame frame = new JFrame();
//more initialization code here
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(dim.width, dim.height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

Don't forget: The JFrame should be created and opened from the EDT. Applet start() is not guaranteed to be called on that thread, so use SwingUtilities.invokeLater(). Of course, if you opt for the button route, button listener is called on the EDT, so you should be safe.

OwnerDisplayName: Ran Biron


问:
Socket.io - Socket splitting into rooms
I'm trying to create a multiplayer game that creates new rooms for each two sockets that connect. How would I go about doing this? Can someone please provide an example?

答:
As a starting point you can use the following example

```<code>const io = require('socket.io')()

/* room to join next connected socket */
let prevRoom = null

io.on('connection', socket => {
  let room

  if (prevRoom == null) {
    /* create new room if there is no room with one player */
    room = Math.random().toString(36).slice(2)
    prevRoom = room
  } else {
    /* join existing room with one player and mark that it is now complete */
    room = prevRoom
    prevRoom = null
  }

  socket.join(room)

  /* send message from one socket in this room to another */
  socket.on('message', data => {
    socket.broadcast.to(room).emit('message', data)
  })
})

io.listen(3000)
</code>```

The problem with this example is that in case one player from a room leaves the game, another will remain alone until he or she refreshes the page. Depending on the application you may need to add some logic here.

Title: Socket.io - Socket splitting into rooms

Body:
As a starting point you can use the following example

const io = require('socket.io')()

/* room to join next connected socket */
let prevRoom = null

io.on('connection', socket => {
  let room

  if (prevRoom == null) {
    /* create new room if there is no room with one player */
    room = Math.random().toString(36).slice(2)
    prevRoom = room
  } else {
    /* join existing room with one player and mark that it is now complete */
    room = prevRoom
    prevRoom = null
  }

  socket.join(room)

  /* send message from one socket in this room to another */
  socket.on('message', data => {
    socket.broadcast.to(room).emit('message', data)
  })
})

io.listen(3000)

The problem with this example is that in case one player from a room leaves the game, another will remain alone until he or she refreshes the page. Depending on the application you may need to add some logic here.


问:
Why use Spring's Mock MVC when you have unit test of your controller classes
I have seen people around me using Spring MVC in unit tests for controller classes, which is not helpful in what a unit test is for.

Unit tests are supposed to test your actual implementation of the controller class, and this can be achieved more accurately with simple Junit tests rather than using Spring Mock MVC.

But then the question arises, what's the real usage of Spring Mock MVC then? What do you need it for?

Let's say I have below code :

```<code>@Controller
@RequestMapping("/systemusers")
public class SystemUserController
{
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getUser(final Model model)
    {

        // some logic to return user's details as json

        return UserDetailsPage;
    }
 }
</code>```

I can test this class/controller more accurately with Junit than with Spring Mock MVC (all it does is generates some json which can be asserted with junit).

I can also test with Spring Mock MVC like using the correct endpoint returns the correct HTTP status and correct response page string.

But doesn't that mean that we are testing Spring MVC's functionality rather than the actual code for method under test?

P.S. : I have kept the code to minimal which I think is sufficient to explain my question. Assume there is no compilation error.

答:
Based on My experience I will try to answer your question.

First thing we need to understand why we use unit testing?

It is a extra check used by developer to write clean working code.
  Clean working code means every line written should be doing what it is
  expected to do. how do you achieve this? Here comes unit testing. The
  standalone unit of code you are writing should be verified standalone.
  Method is best part in code which represents standalone unit code
  template.

Unit Testing for Method

Developer should write a test for method which describes the method
  behavior. And possible checks that i follow is  is it returning the
  expected value considering all positive scenarios? is it working in
  case of Exception? is it calling correct subsequent methods ?

Developer should verify the method by actually calling it providing a
  mock environment

Below is possible answer to your question. though it is solely based upon the developers.

Controller methods are intended to invoke correct service call accepting input and returning the value from service to view.
So I may think of write a unit test case for controller method as you are thinking is a right approach. But you should verify the method by calling it in same way as it will be called in real time.
so you need to call controller method in same way as MVC does. Hence it is better option to use MockMVC.
MockMVC is also useful to verify the urls, input params , response and status which are part of controller method. Considering these all it makes it standalone unit of code.

Hope this will clarify your doubt.

ContentLicense: CC BY-SA 4.0

Body:
I have seen people around me using Spring MVC in unit tests for controller classes, which is not helpful in what a unit test is for.

Unit tests are supposed to test your actual implementation of the controller class, and this can be achieved more accurately with simple Junit tests rather than using Spring Mock MVC.

But then the question arises, what's the real usage of Spring Mock MVC then? What do you need it for?

Let's say I have below code :

@Controller
@RequestMapping("/systemusers")
public class SystemUserController
{
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getUser(final Model model)
    {

        // some logic to return user's details as json

        return UserDetailsPage;
    }
 }

I can test this class/controller more accurately with Junit than with Spring Mock MVC (all it does is generates some json which can be asserted with junit).

I can also test with Spring Mock MVC like using the correct endpoint returns the correct HTTP status and correct response page string.

But doesn't that mean that we are testing Spring MVC's functionality rather than the actual code for method under test?

P.S. : I have kept the code to minimal which I think is sufficient to explain my question. Assume there is no compilation error.


问:
Get Application's main window
UIApplication has a method keyWindow, however if an alert view is showing then this returns the window of the alert view and not the main window of the application.

How can I get the app's main window?

答:
Swift 3</p>

```<code>class func sharedInstance() -> AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }
</code>```

Title: Get Application's main window

Body:
Swift 3

class func sharedInstance() -> AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }


问:
ImportError: No module named 'django.core.urlresolvers'
I am working on Django project where I need to create a form for inputs. I tried to import reverse from django.core.urlresolvers. I got an error:

```<code>line 2, in from django.core.urlresolvers import reverse ImportError: No module named 'django.core.urlresolvers'
</code>```

I am using Python 3.5.2, Django 2.0 and MySQL.

答:
Django 2.0 removes the django.core.urlresolvers module, which was moved to django.urls in version 1.10. You should change any import to use django.urls instead, like this:

```<code>from django.urls import reverse
</code>```

Note that Django 2.0 removes some features that previously were in django.core.urlresolvers, so you might have to make some more changes before your code works. See the features deprecated in 1.9 for details on those additional changes.

Body:
I am working on Django project where I need to create a form for inputs. I tried to import reverse from django.core.urlresolvers. I got an error:

line 2, in from django.core.urlresolvers import reverse ImportError: No module named 'django.core.urlresolvers'

I am using Python 3.5.2, Django 2.0 and MySQL.

Body:
Django 2.0 removes the django.core.urlresolvers module, which was moved to django.urls in version 1.10. You should change any import to use django.urls instead, like this:

from django.urls import reverse

Note that Django 2.0 removes some features that previously were in django.core.urlresolvers, so you might have to make some more changes before your code works. See the features deprecated in 1.9 for details on those additional changes.


问:
Why is the ternary operator used to define 1 and 0 in a macro?
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

```<code>#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
</code>```

Does the use of the ternary operator here make any difference?

Isn't

```<code>#define FOO (1 > 0)
</code>```

the same as

```<code>#define BAR ( (1 > 0) ? 1 : 0)
</code>```

?

I tried evaluating it by using

```<code>printf("%d", FOO == BAR);
</code>```

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

答:
In C it doesn't matter.
Boolean expressions in C have type int and a value that's either 0 or 1, so

```<code>ConditionalExpr ? 1 : 0
</code>```

has no effect.

In C++, it's effectively a cast to int, because conditional expressions in C++ have type bool.

```<code>#include <stdio.h>
#include <stdbool.h>

#ifndef __cplusplus

#define print_type(X) _Generic(X, int: puts("int"), bool: puts("bool") );

#else
template<class T>
int print_type(T const& x);
template<> int print_type<>(int const& x) { return puts("int"); }
template<> int print_type<>(bool const& x) { return puts("bool"); }

#endif

int main()
{
    print_type(1);
    print_type(1 > 0);
    print_type(1 > 0 ? 1 : 0);

/*c++ output:
  int
  int
  int

  cc output:
  int
  bool
  int
*/

}
</code>```

It's also possible no effect was intended, and the author simply thought it made the code clearer.

Body:
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )

Does the use of the ternary operator here make any difference?

Isn't

#define FOO (1 > 0)

the same as

#define BAR ( (1 > 0) ? 1 : 0)

?

I tried evaluating it by using

printf("%d", FOO == BAR);

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

Body:
In C it doesn't matter.
Boolean expressions in C have type int and a value that's either 0 or 1, so

ConditionalExpr ? 1 : 0

has no effect.

In C++, it's effectively a cast to int, because conditional expressions in C++ have type bool.

#include <stdio.h>
#include <stdbool.h>

#ifndef __cplusplus

#define print_type(X) _Generic(X, int: puts("int"), bool: puts("bool") );

#else
template<class T>
int print_type(T const& x);
template<> int print_type<>(int const& x) { return puts("int"); }
template<> int print_type<>(bool const& x) { return puts("bool"); }

#endif

int main()
{
    print_type(1);
    print_type(1 > 0);
    print_type(1 > 0 ? 1 : 0);

/*c++ output:
  int
  int
  int

  cc output:
  int
  bool
  int
*/

}

It's also possible no effect was intended, and the author simply thought it made the code clearer.


问:
angular match value from passed array with item from loop on the page
trying to match value from passed array and loop on the page

```<code>.then(function (data) {
    vm.outputL = data;
    vm.array = [];

    for(var i=0; i < vm.outputL.length; i++){

        vm.block = false;
        if(vm.outputL[i].id < 100){

            vm.block = true;

        }

        vm.array.push(vm.block)

    }
}
</code>```

and html code

```<code> <li ng-repeat="item in vm.outputL">
    <div>{[item.id]}</div>
    <div ng-if="vm.array">something</div>
 <li>
</code>```

how can I match value from vm.block and loop item on the page?

答:
They way you handle data results vm.array and vm.outputL to have different length.

If I am not mistaken, what might be useful based on your question is to push vm.block without caring about its value so that you can match it to the itterating items.

This block might be useful:

Controller:

```<code>    vm.block = false;
    if(vm.outputL[i].id < 100){
       vm.block = true;
    }
    vm.array.push(vm.block)
</code>```

Template:

```<code><li ng-repeat="item in vm.outputL">
    <div>{[item.id]}</div>
    <div ng-if="vm.array[$index]">something</div>
 <li>
</code>```

Body:
trying to match value from passed array and loop on the page

.then(function (data) {
    vm.outputL = data;
    vm.array = [];

    for(var i=0; i < vm.outputL.length; i++){

        vm.block = false;
        if(vm.outputL[i].id < 100){

            vm.block = true;

        }

        vm.array.push(vm.block)

    }
}

and html code

{[item.id]}

something

how can I match value from vm.block and loop item on the page?

Body:
They way you handle data results vm.array and vm.outputL to have different length.

If I am not mistaken, what might be useful based on your question is to push vm.block without caring about its value so that you can match it to the itterating items.

This block might be useful:

Controller:

    vm.block = false;
    if(vm.outputL[i].id < 100){
       vm.block = true;
    }
    vm.array.push(vm.block)

Template:

<li ng-repeat="item in vm.outputL">
    <div>{[item.id]}</div>
    <div ng-if="vm.array[$index]">something</div>
 <li>


问:
Node js: Express js asynchronous db query execution-return results got undefiend
Just started to learn express js framework ,here is my simple database query execution part its invoked with this url localhost:3000/api/test.

```<code>db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is:', results[0].id);

            return results;
        });
</code>```

Does it really asynchronous?? suppose another user request this url does he need to wait for the previous query execution??.

I've heard about async package ,but don't know how this is applicable in my case

UPDATE

I got proper result in console.log(); but when i return the result i got undefined error

Here is my model.js

```<code>module.exports = {
    getUser:function () {
        db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is: ', results[0].id);

        });

    }

}
</code>```

From my controller.js

```<code>var model = require('../models/user.js');
module.exports = {
    getData : function(req, res){
        //invoke model
        console.log(model.getUser());

    }
}
</code>```

答:
When you deal with callback, the safe and clean way to handle them is Promises. It's now standard in JavaScript and don't require any module.

And yes it is asynchronous. Behind, there'll be network access and dialogs with the database server. Only when they're done chatting will the callback be called.

```<code>module.exports = {
    getUser: function () {
        // wrap asynchronously called callback in Promise
        new Promise((resolve, reject) => {
            db.query("SELECT * FROM user", (error, results, fields) => {
                if (error) {
                    reject(error); // similar to "throw"
                }
                else {
                    resolve({ results, fields }); // similar to "return"
                }
            });
        });
    }
};
</code>```

How do you use it:

Vanilla notation:

```<code>// similar to "try"
model.getUser()
.then((answer) => {
    console.log("answer", answer);
})
// similar to "catch"
.catch((error) => {
    console.log("error", error);
});
</code>```

async-await notation (only available in last versions of nodejs & browsers):

```<code>// you must be in an async environement to use "await"
async function wrapper() {
    try {
        var answer = await model.getUser(); // wait for Promise resolution
        console.log("answer", answer);
    }
    catch(error) {
        console.log("error", error);
    }
}
// async function return automatically a Promise so you can chain them easily
wrapper();
</code>```

Body:
Just started to learn express js framework ,here is my simple database query execution part its invoked with this url localhost:3000/api/test.

db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is:', results[0].id);

            return results;
        });

Does it really asynchronous?? suppose another user request this url does he need to wait for the previous query execution??.

I've heard about async package ,but don't know how this is applicable in my case

UPDATE

I got proper result in console.log(); but when i return the result i got undefined error

Here is my model.js

module.exports = {
    getUser:function () {
        db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is: ', results[0].id);

        });

    }

}

From my controller.js

var model = require('../models/user.js');
module.exports = {
    getData : function(req, res){
        //invoke model
        console.log(model.getUser());

    }
}

Body:
When you deal with callback, the safe and clean way to handle them is Promises. It's now standard in JavaScript and don't require any module.

And yes it is asynchronous. Behind, there'll be network access and dialogs with the database server. Only when they're done chatting will the callback be called.

module.exports = {
    getUser: function () {
        // wrap asynchronously called callback in Promise
        new Promise((resolve, reject) => {
            db.query("SELECT * FROM user", (error, results, fields) => {
                if (error) {
                    reject(error); // similar to "throw"
                }
                else {
                    resolve({ results, fields }); // similar to "return"
                }
            });
        });
    }
};

How do you use it:

Vanilla notation:

// similar to "try"
model.getUser()
.then((answer) => {
    console.log("answer", answer);
})
// similar to "catch"
.catch((error) => {
    console.log("error", error);
});

async-await notation (only available in last versions of nodejs & browsers):

// you must be in an async environement to use "await"
async function wrapper() {
    try {
        var answer = await model.getUser(); // wait for Promise resolution
        console.log("answer", answer);
    }
    catch(error) {
        console.log("error", error);
    }
}
// async function return automatically a Promise so you can chain them easily
wrapper();


问:
Python program error at closing
I hope you can help me once again, I am still noob at programming so please bear with me. I got this error:

```<code>Traceback (most recent call last):
  File "C:\Python27\cx_Freeze exe Creator\Postcodezoekernl.py", line 136, in <module>
    postcodeinvoer = int(postcodeinvoer)
TypeError: int() argument must be a string or a number, not 'NoneType'
</code>```

The program works, but when I compile it, it will give an error when you close the program, saying there is something wrong with the code. I've tried deleting the line but the program wont work without it as it will go directly to the ELSE statement. Postcode1 is a range between certain numbers. The users have to fill in a number. If the number is within that range it will show the msgbox.

```<code>elif keuze in week2:

        postcodeinvoer = easygui.enterbox(msg="Voer een postcode in:", title="Postcodezoeker")
        postcodeinvoer = int(postcodeinvoer)

        if postcodeinvoer in postcode1:
            easygui.msgbox(msg="[Woensdag 3 mei, 10 mei, 17 mei, 24 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode2:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode3:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
</code>```

Btw is it possible to compile a python file to a single .exe file?
Hope you guys can help me. Thanks in advance!

Problem resolved!

答:
int(something) will raise either a TypeError or a ValueError if it can instanciate an int from it's argument, so the simplest solution is to catch the exception and try again. But since we want to allow the user to cancel the operation we will still test againt None and exit instead

```<code>cancel = False
basemsg = msg = "Voer een postcode in:"
while True:
    postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
    if postcodeinvoer is None:
        # user canceled
        cancel = True
        break
    try:
        postcodeinvoer = int(postcodeinvoer)
    except (TypeError, ValueError) as e:
        msg = "invalid value ! " + basemsg
    else:
        # ok, let's get out
        break

if cancel:
     # exit the program or whatever...
     raise SysExit()

# ok, proceed with the user's value
</code>```

Now you seem to be making a common newbie mistake which is to think that if something is made up of digits then it's a number, which is NOT the case. A postal code or phone number are typically strings, not integers - ask yourself what sense it would make to multiply a phone number by 2 and divide the result by a postal code ;)

IOW, you should not convert postcodeinvoer to an int at all. If you're country's postal code are only made up of digits (which is not the case in all countries), then you can test that the user input is a string made of N digits (the value of N depending on your country):

```<code>    postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
    if postcodeinvoer is None:
        # user canceled
        cancel = True
        break
    if (postcodeinvoer.isdigit() and len(postcodeinvoer) == N):
        # valid code
        break
    else:
        # invalid code, ask again
        msg = "invalid value ! " + basemsg
</code>```

but even then it might not be a good enough validation...

Title: Python program error at closing

Body:
I hope you can help me once again, I am still noob at programming so please bear with me. I got this error:

Traceback (most recent call last):
  File "C:\Python27\cx_Freeze exe Creator\Postcodezoekernl.py", line 136, in <module>
    postcodeinvoer = int(postcodeinvoer)
TypeError: int() argument must be a string or a number, not 'NoneType'

The program works, but when I compile it, it will give an error when you close the program, saying there is something wrong with the code. I've tried deleting the line but the program wont work without it as it will go directly to the ELSE statement. Postcode1 is a range between certain numbers. The users have to fill in a number. If the number is within that range it will show the msgbox.

elif keuze in week2:

        postcodeinvoer = easygui.enterbox(msg="Voer een postcode in:", title="Postcodezoeker")
        postcodeinvoer = int(postcodeinvoer)

        if postcodeinvoer in postcode1:
            easygui.msgbox(msg="[Woensdag 3 mei, 10 mei, 17 mei, 24 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode2:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode3:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)

Btw is it possible to compile a python file to a single .exe file?
Hope you guys can help me. Thanks in advance!

Problem resolved!

Body:
int(something) will raise either a TypeError or a ValueError if it can instanciate an int from it's argument, so the simplest solution is to catch the exception and try again. But since we want to allow the user to cancel the operation we will still test againt None and exit instead

cancel = False
basemsg = msg = "Voer een postcode in:"
while True:
    postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
    if postcodeinvoer is None:
        # user canceled
        cancel = True
        break
    try:
        postcodeinvoer = int(postcodeinvoer)
    except (TypeError, ValueError) as e:
        msg = "invalid value ! " + basemsg
    else:
        # ok, let's get out
        break

if cancel:
     # exit the program or whatever...
     raise SysExit()

# ok, proceed with the user's value

Now you seem to be making a common newbie mistake which is to think that if something is made up of digits then it's a number, which is NOT the case. A postal code or phone number are typically strings, not integers - ask yourself what sense it would make to multiply a phone number by 2 and divide the result by a postal code ;)

IOW, you should not convert postcodeinvoer to an int at all. If you're country's postal code are only made up of digits (which is not the case in all countries), then you can test that the user input is a string made of N digits (the value of N depending on your country):

    postcodeinvoer = easygui.enterbox(msg=msg, title="Postcodezoeker")
    if postcodeinvoer is None:
        # user canceled
        cancel = True
        break
    if (postcodeinvoer.isdigit() and len(postcodeinvoer) == N):
        # valid code
        break
    else:
        # invalid code, ask again
        msg = "invalid value ! " + basemsg

but even then it might not be a good enough validation...


答:
if you want to import reverse, import it from django.urls

```<code>from django.urls import reverse
</code>```

Title: ImportError: No module named 'django.core.urlresolvers'

Body:
if you want to import reverse, import it from django.urls

from django.urls import reverse


问:
How to perform inner join in mysql
I have to write a query such that ,I need to get events whose start date  is of 30 min from now.
My conditions are:

1) get the event from events table

2)Join created by of events with id in users table.

3)Comments from comment table with user ser id

But the problem here is if there is no comment for event then the event it self is not coming.If any comment is present it is coming.I dont want this.If comment is not there just fetch it as empty but not hide the total event .Can anyone please help me,.Thanks.

```<code> select u.email ,group_members.user_id,users.first_name,u.first_name
                as host_name,events.name,events.start_date,comments.comments,c.first_name as
                comment_user,comments.id from events
                inner join users as u on u.id = events.created_by
                inner join comments on events.id = comments.event_id
                inner join group_members on events.group_id = group_members.group_id
                inner join users as c on comments.from_user = c.id
                inner join users on group_members.user_id = users.id
                where events.start_date  between date_add(now(),interval 1 minute) and date_add(
                now(),interval 30 minute)
                and group_members.user_status = 2
                and events.status = 2
</code>```

答:
Use the INNER JOIN Keyword and select the two columns by putting them with keyword ON.

```<code>SELECT EMP.EMP_ID, EMP.EMP_NAME, DEPT.DEPT_NAME FROM EMP
INNER JOIN DEPT ON DEPT.DEPT_ID = EMP.DEPT_ID;
</code>```

Title: How to perform inner join in mysql

Body:
I have to write a query such that ,I need to get events whose start date  is of 30 min from now.
My conditions are:

1) get the event from events table

2)Join created by of events with id in users table.

3)Comments from comment table with user ser id

But the problem here is if there is no comment for event then the event it self is not coming.If any comment is present it is coming.I dont want this.If comment is not there just fetch it as empty but not hide the total event .Can anyone please help me,.Thanks.

 select u.email ,group_members.user_id,users.first_name,u.first_name
                as host_name,events.name,events.start_date,comments.comments,c.first_name as
                comment_user,comments.id from events
                inner join users as u on u.id = events.created_by
                inner join comments on events.id = comments.event_id
                inner join group_members on events.group_id = group_members.group_id
                inner join users as c on comments.from_user = c.id
                inner join users on group_members.user_id = users.id
                where events.start_date  between date_add(now(),interval 1 minute) and date_add(
                now(),interval 30 minute)
                and group_members.user_status = 2
                and events.status = 2

Body:
Use the INNER JOIN Keyword and select the two columns by putting them with keyword ON.

SELECT EMP.EMP_ID, EMP.EMP_NAME, DEPT.DEPT_NAME FROM EMP
INNER JOIN DEPT ON DEPT.DEPT_ID = EMP.DEPT_ID;


问:
Troubles installing and running ArangoDB
I am trying to use ArangoDB in my cloud9 workspace. The installation in a cloned workspace goes with no trouble, except for these lines:

```<code>/etc/init.d/arangodb3: 37: ulimit: error setting limit (Operation not permitted)
/etc/init.d/arangodb3: 38: ulimit: error setting limit (Invalid argument)
that appear when starting arangodb service.
</code>```

Then, I proceed to change the following line in /etc/arangodb3/arangod.conf: endpoint = tcp://127.0.0.1:8529

to this one:
    endpoint = tcp://[workspace]-[username].c9users.io:8081
in order to change the default running port of ArangoDB to a c9-allowed port.

That´s done with arangodb service stopped, so I the start it again, to see these lines printed out:

```<code>/etc/init.d/arangodb3: 37: ulimit: error setting limit (Operation not permitted)
/etc/init.d/arangodb3: 38: ulimit: error setting limit (Invalid argument) {startup} starting up in daemon mode changed working directory for child process to '/var/tmp'
</code>```

and then it gets my terminal back (it doesn´t keep like an ongoing process) so I type:
    sudo service arangodb status
which gives:
    * arangod is not running
How can I get this to work? Thank you!

答:
the ulimit lines are there to set the Hard and Soft quotas for open file handles, and probably exceeds your setting of /proc/sys/fs/file-max, so you may find resource shortages under heavy load.

Arangodb writes its logs under /var/log/arangodb3/arangod.log where it should inform you about reasons why it failed to start.

If you use a DNS-Name to configure your endpoint, you need to make sure that

it resolves (ping hostname)

the resolved ip is available locally (/sbin/ifconfig)

most probably the simplest way to fix this situation is to bind the endpoint to all available IP-Addresses using 0.0.0.0.

Body:
I am trying to use ArangoDB in my cloud9 workspace. The installation in a cloned workspace goes with no trouble, except for these lines:

/etc/init.d/arangodb3: 37: ulimit: error setting limit (Operation not permitted)
/etc/init.d/arangodb3: 38: ulimit: error setting limit (Invalid argument)
that appear when starting arangodb service.

Then, I proceed to change the following line in /etc/arangodb3/arangod.conf: endpoint = tcp://127.0.0.1:8529

to this one:
    endpoint = tcp://[workspace]-[username].c9users.io:8081
in order to change the default running port of ArangoDB to a c9-allowed port.

That´s done with arangodb service stopped, so I the start it again, to see these lines printed out:

/etc/init.d/arangodb3: 37: ulimit: error setting limit (Operation not permitted)
/etc/init.d/arangodb3: 38: ulimit: error setting limit (Invalid argument) {startup} starting up in daemon mode changed working directory for child process to '/var/tmp'

and then it gets my terminal back (it doesn´t keep like an ongoing process) so I type:
    sudo service arangodb status
which gives:
    * arangod is not running
How can I get this to work? Thank you!


问:
Automatically create UDP input for Graylog2 server running in Docker?
We're running a Graylog2 server in a Docker container in our development environment. It works like a charm apart from the fact that we have to re-create the UDP input every time we launch the container.

Has anyone figured out a convenient way to automatically create Graylog2 inputs?

答:
We have a puppet solution for this (graylog2 v2.2.2). Basically enable content-packs in the server.conf, and list the relevant file(s) that will be your json content (see above for UDP inputs as a nice example). Simply a file resource in puppet placed on the graylog server in the configured dir (default is /usr/share/graylog-server/contentpacks)

This will be loaded on 1st run of graylog.

It a nice way of getting in a lot of config.


问:
angularjs application - can i include business logic/backend code in my angular controllers written inside javascript file
I am developing a web application with technologies html,angularjs, java, Spring.
My requirement is to create a search page for my application. Please find the demo here

I need to enter the details and search the information.Please enter Atlanta in From text field and Chicago in To text field and click on SearchLocations button to view the information.

Few questions which i have:

1) Can i write the business logic in my angularjs controllers which are written in javascript file as the sample code shown below:

```<code>angular.module('myApp').controller('searchController', ['$scope', function($scope) {
    $scope.places = ['', ''];
    $scope.searchValue = '';

    $scope.submit = function() {
      $scope.showGrid = $scope.Passport;
      if ($scope.places[0].length > 0 && $scope.places[1].length > 0) {
        $scope.searchValue = $scope.places[0] + $scope.places[1];
      }
    };
</code>```

2) Can i write backend logic in my controllers. If yes can you please suggest any links so that i can proceed or gain knowledge from their.
The javascript code which i have written, can i say it as a backend code/business logic. Sorry about this kind of questions but i thought this is the great platform to put my questions to clarify..

If someone ask me to write backend code for this kind of search functionality, how would anyone proceed. Any suggestions would be very very helpful.The code which i wrote is as shown in the demo plunker above.Thanks.

js code:

```<code>  angular.module('myApp', ['ngAnimate', 'ui.bootstrap', 'ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.edit', 'ui.grid.cellNav']);
  angular.module('myApp').controller('citiesCtrl', function($scope) {
    // $scope. places = undefined;
    $scope.items = ["Atlanta", "Chicago", "NewYork"];
    $scope.selectAction = function() {
      console.log($scope.places1);

    };
  });

  /*Controller for searchLocations button*/
  angular.module('myApp').controller('searchController', ['$scope', function($scope) {
    $scope.places = ['', ''];
    $scope.searchValue = '';

    $scope.submit = function() {
      $scope.showGrid = $scope.Passport;
      if ($scope.places[0].length > 0 && $scope.places[1].length > 0) {
        $scope.searchValue = $scope.places[0] + $scope.places[1];
      }
    };

    $scope.users = [{
      'name': 'AtlantaChicago',
      'show': true,
      'details': [{
        "Travel Date": "10/10/2014",
        commute: "Bus"
      }, {
        "Travel Date": "10/11/2014",
        commute: "flight"
      }]
    }, {
      'name': 'NewYorkChicago',
      'show': true,
      'details': [{
        "Travel Date": "3/15/2016",
        commute: "flight"
      }, {
        "Travel Date": "10/12/2016",
        commute: "flight"
      }, ]
    }];
    $scope.gridOptions = {
      enableFiltering: true,
      columnDefs: [{
        name: 'Travel Date',
        width: '5%'
      }, {
        name: 'Departurecommute',
        enableFiltering: false,
        width: '12%'
      }],
      rowHeight: 20,
      enableHorizontalScrollbar: 2

    };
  }]);
</code>```

html code:

```<code>  <div>
      <label>
        Show one Grid
        <input type="radio" name="Passport" ng-model="Passport" value=1 ng-click="ShowPassport('Y')" />
      </label>
      <label>Show two Grids
        <input type="radio" name="Passport" ng-model="Passport" value=2 ng-click="ShowPassport('N')" />
      </label>
    </div>
    <div class="row">
      <div class="form-group" ng-controller="citiesCtrl">
        <label>From</label>
        <input type="text" ng-model="places[0]" placeholder="Type Departure City" typeahead="item for item in items | filter:$viewValue | limitTo:8">
      </div>
      <div class="form-group" ng-controller="citiesCtrl">
        <label>To</label>
        <input type="text" ng-model="places[1]" placeholder="Type Destination City" typeahead="item for item in items | filter:$viewValue | limitTo:8">
      </div>
    </div>

    <input type="button" value="SearchLocations" ng-click="submit()">

    <div ng-show="showGrid==='1'||showGrid==='2'">
      <div ng-repeat="user in users | filter: {name: searchValue} : true ">
        <h3>First Grid</h3>
        <div ui-grid="{ data: user.details }" ng-show="user.show" class="myGrid"></div>
      </div>
    </div>
    <div ng-show="showGrid==='2'">
      <div ng-repeat="user in users | filter: {name: searchValue} : true ">
        <h3>Second Grid</h3>
        <div ui-grid="{ data: user.details }" ng-show="user.show" class="myGrid"></div>
      </div>
    </div>
</code>```

答: Angular is MVW framework, the main component is view and model. So Basically its used for segregation of page rendering from Server Code. Now business logic related to client request handling and page rendering could be write in angular controller but the logic which is related to our actual data/database can not be write in angular controller.So you better know what kind of code you have in back-end and decide based on that.</p>

Body:
I am developing a web application with technologies html,angularjs, java, Spring.
My requirement is to create a search page for my application. Please find the demo here

I need to enter the details and search the information.Please enter Atlanta in From text field and Chicago in To text field and click on SearchLocations button to view the information.

Few questions which i have:

1) Can i write the business logic in my angularjs controllers which are written in javascript file as the sample code shown below:

angular.module('myApp').controller('searchController', ['$scope', function($scope) {
    $scope.places = ['', ''];
    $scope.searchValue = '';

    $scope.submit = function() {
      $scope.showGrid = $scope.Passport;
      if ($scope.places[0].length > 0 && $scope.places[1].length > 0) {
        $scope.searchValue = $scope.places[0] + $scope.places[1];
      }
    };

2) Can i write backend logic in my controllers. If yes can you please suggest any links so that i can proceed or gain knowledge from their.
The javascript code which i have written, can i say it as a backend code/business logic. Sorry about this kind of questions but i thought this is the great platform to put my questions to clarify..

If someone ask me to write backend code for this kind of search functionality, how would anyone proceed. Any suggestions would be very very helpful.The code which i wrote is as shown in the demo plunker above.Thanks.

js code:

  angular.module('myApp', ['ngAnimate', 'ui.bootstrap', 'ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.edit', 'ui.grid.cellNav']);
  angular.module('myApp').controller('citiesCtrl', function($scope) {
    // $scope. places = undefined;
    $scope.items = ["Atlanta", "Chicago", "NewYork"];
    $scope.selectAction = function() {
      console.log($scope.places1);

    };
  });

  /*Controller for searchLocations button*/
  angular.module('myApp').controller('searchController', ['$scope', function($scope) {
    $scope.places = ['', ''];
    $scope.searchValue = '';

    $scope.submit = function() {
      $scope.showGrid = $scope.Passport;
      if ($scope.places[0].length > 0 && $scope.places[1].length > 0) {
        $scope.searchValue = $scope.places[0] + $scope.places[1];
      }
    };

    $scope.users = [{
      'name': 'AtlantaChicago',
      'show': true,
      'details': [{
        "Travel Date": "10/10/2014",
        commute: "Bus"
      }, {
        "Travel Date": "10/11/2014",
        commute: "flight"
      }]
    }, {
      'name': 'NewYorkChicago',
      'show': true,
      'details': [{
        "Travel Date": "3/15/2016",
        commute: "flight"
      }, {
        "Travel Date": "10/12/2016",
        commute: "flight"
      }, ]
    }];
    $scope.gridOptions = {
      enableFiltering: true,
      columnDefs: [{
        name: 'Travel Date',
        width: '5%'
      }, {
        name: 'Departurecommute',
        enableFiltering: false,
        width: '12%'
      }],
      rowHeight: 20,
      enableHorizontalScrollbar: 2

    };
  }]);

html code:

        Show one Grid
        <input type="radio" name="Passport" ng-model="Passport" value=1 ng-click="ShowPassport('Y')" />

      Show two Grids
        <input type="radio" name="Passport" ng-model="Passport" value=2 ng-click="ShowPassport('N')" />

        From
        <input type="text" ng-model="places[0]" placeholder="Type Departure City" typeahead="item for item in items | filter:$viewValue | limitTo:8">

        To
        <input type="text" ng-model="places[1]" placeholder="Type Destination City" typeahead="item for item in items | filter:$viewValue | limitTo:8">

    <input type="button" value="SearchLocations" ng-click="submit()">

First Grid

Second Grid


问:
User Roles Permissions Database Design
I have the following database design for Users, Roles & Permissions:

Users * ---- * Roles

Roles * ---- * Permissions

A user may have many roles. A role has many permissions. There is a downside though: What if I want to give a particular special user some specific permission that is not in that user's existing roles?

Imagine I have role "Manager". John Doe is a manager. I want to give John a permission "See Activity". "See Activity" is in the "Observer" role but not in "Manager". Although I want to let John "See Activity" I don't want to give him the "Observer" role, as it has other permissions too.

One way to solve it would be to have roles corresponding to each permission together with existing roles. And whenever John needs permission "See Activity", I will grant him role "See Activity Role" which contains only one permission.

What are other designs?

答:
It is a good idea to make a less role a subset of the bigger role.
This can be easily determined by the SQL below

```<code>select count(permissions) from tblPermission where role='observer'
</code>```

This will give the total number of privileges/permission that the
role member has. Same query also for the manager's role

```<code>select count(permissions) from tblPermission where role='manager'
</code>```

Logically if the manager role is a super-class to the observer class then
the manager should be able to see activity as same with the observer.

Title: User Roles Permissions Database Design

Body:
It is a good idea to make a less role a subset of the bigger role.
This can be easily determined by the SQL below

select count(permissions) from tblPermission where role='observer'

This will give the total number of privileges/permission that the
role member has. Same query also for the manager's role

select count(permissions) from tblPermission where role='manager'

Logically if the manager role is a super-class to the observer class then
the manager should be able to see activity as same with the observer.


问:
Explode array from mysql and assign to variables PHP
OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )

What I'm trying to do is explode at the : and then assign the exploded values to variables

At most there are 4 bits of data separated by : so a max of 4 variables

Here is the code I have so far

```<code>$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);

do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4;
}while($result = mysql_fetch_assoc($query));
</code>```

It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:

The output however does NOT display the final
Advanced

it only displays
Novice
Novice/Intermediate
Intermediate/Advanced

Anyone help me please I am pulling hair out badly here .

I have also tried adding another $var5 but that doesnt help

答:
do it like this </p>

```<code>$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
$i=0;
while($result = mysql_fetch_assoc($query)){
    $var1[$i]=$row['Novice'];
    $var2[$i]=$row['Intermediate'];
    $var3[$i]=$row['Advanced '];
    echo $var1[$i].'<br>'.$var2[$i].'<br>'.$var3[$i].'<br>';
    $i++;
    }
</code>```

Body:
OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )

What I'm trying to do is explode at the : and then assign the exploded values to variables

At most there are 4 bits of data separated by : so a max of 4 variables

Here is the code I have so far

$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);

do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'
'.$var2.'
'.$var3.'
'.$var4;
}while($result = mysql_fetch_assoc($query));

It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:

The output however does NOT display the final
Advanced

it only displays
Novice
Novice/Intermediate
Intermediate/Advanced

Anyone help me please I am pulling hair out badly here .

I have also tried adding another $var5 but that doesnt help

Body:
do it like this

$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
$i=0;
while($result = mysql_fetch_assoc($query)){
    $var1[$i]=$row['Novice'];
    $var2[$i]=$row['Intermediate'];
    $var3[$i]=$row['Advanced '];
    echo $var1[$i].'<br>'.$var2[$i].'<br>'.$var3[$i].'<br>';
    $i++;
    }


问:
I want to calculate MTD, YTD, WTD according to fiscal calendar in power bi
The issue is I want to display MTD, WTD, QTD sales according to fiscal calendar for example :- If i selected date 3/9/2017 then MTD should include sales during 2/23/2017 to 3/8/2017 in power bi report. </p>

<p>Is there any formula to get MTD in fiscal calendar? </p>

答:
See this article which walks through the DAX measures you need. Note Iso QTD for example:

```<code>Iso QTD :=
IF (
    HASONEVALUE ( Dates[ISO Year] )
        && HASONEVALUE (Dates[ISO Quarter] ),
    CALCULATE (
        SUM ( Sales[Sales Amount] ),
        FILTER (
            ALL ( Dates ),
            Dates[ISO Year] = VALUES ( Dates[ISO Year] )
                && Dates[ISO Quarter] = VALUES ( Dates[ISO Quarter] )
                && Dates[Date] <= MAX ( Dates[Date] )
        )
    ),
    BLANK ()
)
</code>```

Body:
The issue is I want to display MTD, WTD, QTD sales according to fiscal calendar for example :- If i selected date 3/9/2017 then MTD should include sales during 2/23/2017 to 3/8/2017 in power bi report.

Is there any formula to get MTD in fiscal calendar?

Body:
See this article which walks through the DAX measures you need. Note Iso QTD for example:

Iso QTD :=
IF (
    HASONEVALUE ( Dates[ISO Year] )
        && HASONEVALUE (Dates[ISO Quarter] ),
    CALCULATE (
        SUM ( Sales[Sales Amount] ),
        FILTER (
            ALL ( Dates ),
            Dates[ISO Year] = VALUES ( Dates[ISO Year] )
                && Dates[ISO Quarter] = VALUES ( Dates[ISO Quarter] )
                && Dates[Date] <= MAX ( Dates[Date] )
        )
    ),
    BLANK ()
)