问:
SqlDependency with SignalR user specific
Please follow code:

_Layout:

```<code>$(function () {
    var connection = $.connection.notificationHub;

    //signalr method for push server message to client
    connection.client.addNotification = function (who) {
        //send notification here
        console.info("Send Notification")
    };

    // Start hub
    $.connection.hub.start().done(function () {
        console.log("SignalR Started")
    });
});
</code>```

Global.asax.cs:

```<code>public class Global : HttpApplication
{
    string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        //here in Application Start we will start Sql Dependency
        SqlDependency.Start(con);
    }

    protected void Session_Start(object sender, EventArgs e)
    {
        NotificationComponent NC = new NotificationComponent();
        var currentTime = DateTime.Now;
        HttpContext.Current.Session["LastUpdated"] = currentTime;
        NC.RegisterNotification(currentTime);
    }

    protected void Application_End()
    {
        //here we will stop Sql Dependency
        SqlDependency.Stop(con);
    }
}
</code>```

Controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyAction(string parameter)
{
    //Database Notification (Table - Contacts) -Add or Update
    ctx.SaveChanges();
}
</code>```

NotificationHub : Hub

```<code>private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();

public static void SendNotification(string who)
{
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
    foreach (var connectionId in _connections.GetConnections(who))
    {
        var result = context.Clients.Client(connectionId);
        if (result != null)
        {
            result.addNotification(who);
        }
    }
}
</code>```

Components.cs:

```<code>public void RegisterNotification(DateTime currentTime)
{
    string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    string sqlCommand = @"SELECT [ContactID],[ContactName],[ContactNo] from [dbo].[Contacts] where [AddedOn] > @AddedOn";
    //you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency
    using (SqlConnection con = new SqlConnection(conStr))
    {
        SqlCommand cmd = new SqlCommand(sqlCommand, con);
        cmd.Parameters.AddWithValue("@AddedOn", currentTime);
        if (con.State != System.Data.ConnectionState.Open)
        {
            con.Open();
        }
        cmd.Notification = null;
        SqlDependency sqlDep = new SqlDependency(cmd);
        sqlDep.OnChange += sqlDep_OnChange;
        //we must have to execute the command here
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            // nothing need to add here now
        }
    }
}

//After code `ctx.SaveChanges()`, call the code below (50 times):
void SqlDep_OnChange(object sender, SqlNotificationEventArgs e) //<-- Here Problem
{

    //from here we will send notification message to client
    NotificationHub.SendNotification("User1586");
    //...

    //re-register notification
    RegisterNotification(DateTime.Now);

    //HERE -After this line "RegisterNotification(DateTime.Now);", it returns again to the line: "void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)"
}
</code>```

User "User1586" is receiving multiple notifications.
The line "void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)" repeats several times.
If you have 50 online users, do 50 times on this line:

```<code>void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)
</code>```

If you have 1000 online users, do 1000 times on this line:

```<code>void SqlDep_OnChange(object sender, SqlNotificationEventArgs e).
</code>```

 In other words, user "User1586" receives several notifications.

I followed the example here: http://www.dotnetawesome.com/2016/05/push-notification-system-with-signalr.html

Idea is to send notification to a specific user after database update.

Any solution ?

答:
First of all, Sql dependency is not aware what data has changed. So you should query inside the event handler. If you want to send data corresponding the user id and specifically just for one user, I would recommend you to do like this;

Event Handler

```<code>private void SqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
    if (e.Info == SqlNotificationInfo.Insert)
    {
         RecordInfo info = GetLastInsertedRecord(); //Just a custom entity
          if(info.UserId > 0)
             NotificationHub.SendNotification(info.UserId);
    }
    RegisterNotification(DateTime.Now);
}
</code>```

Hub

```<code>public static List<UserConnection> ListUser { get; set; }
public static void SendNotification(string who)
{
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    // Get specific user from connected ones.
    string Id = ListUser.Find(x => x.UserId == who).ConnectionId;
    context.Clients.Client(Id).addNotification(who); // or another data
}
//Add every connected users to the list
public override Task OnConnected()
    {
        ListUser = new List<UserConnection>();
        var us = new UserConnection();
        us.UserId = Context.QueryString["UserId"];
        us.ConnectionId = Context.ConnectionId;
        ListUser.Add(us);

        return base.OnConnected();
    }
</code>```

UPDATE  Client

```<code>$(function () {
    var connection = $.connection.notificationHub;
    //Pass the userId here as querystring
    $.connection.hub.qs = "UserId=" + $("#labelHoldsUserId").val();
    //signalr method for push server message to client
    connection.client.addNotification = function (who) {
        //send notification here
        console.log(who + " sends message");
    };

    // Start hub
    $.connection.hub.start().done(function () {
        console.log("SignalR Started")
    });
})
</code>```

Body:
Please follow code:

_Layout:

$(function () {
    var connection = $.connection.notificationHub;

    //signalr method for push server message to client
    connection.client.addNotification = function (who) {
        //send notification here
        console.info("Send Notification")
    };

    // Start hub
    $.connection.hub.start().done(function () {
        console.log("SignalR Started")
    });
});

Global.asax.cs:

public class Global : HttpApplication
{
    string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        //here in Application Start we will start Sql Dependency
        SqlDependency.Start(con);
    }

    protected void Session_Start(object sender, EventArgs e)
    {
        NotificationComponent NC = new NotificationComponent();
        var currentTime = DateTime.Now;
        HttpContext.Current.Session["LastUpdated"] = currentTime;
        NC.RegisterNotification(currentTime);
    }

    protected void Application_End()
    {
        //here we will stop Sql Dependency
        SqlDependency.Stop(con);
    }
}

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyAction(string parameter)
{
    //Database Notification (Table - Contacts) -Add or Update
    ctx.SaveChanges();
}

NotificationHub : Hub

private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();

public static void SendNotification(string who)
{
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
    foreach (var connectionId in _connections.GetConnections(who))
    {
        var result = context.Clients.Client(connectionId);
        if (result != null)
        {
            result.addNotification(who);
        }
    }
}

Components.cs:

public void RegisterNotification(DateTime currentTime)
{
    string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    string sqlCommand = @"SELECT [ContactID],[ContactName],[ContactNo] from [dbo].[Contacts] where [AddedOn] > @AddedOn";
    //you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency
    using (SqlConnection con = new SqlConnection(conStr))
    {
        SqlCommand cmd = new SqlCommand(sqlCommand, con);
        cmd.Parameters.AddWithValue("@AddedOn", currentTime);
        if (con.State != System.Data.ConnectionState.Open)
        {
            con.Open();
        }
        cmd.Notification = null;
        SqlDependency sqlDep = new SqlDependency(cmd);
        sqlDep.OnChange += sqlDep_OnChange;
        //we must have to execute the command here
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            // nothing need to add here now
        }
    }
}

//After code `ctx.SaveChanges()`, call the code below (50 times):
void SqlDep_OnChange(object sender, SqlNotificationEventArgs e) //<-- Here Problem
{

    //from here we will send notification message to client
    NotificationHub.SendNotification("User1586");
    //...

    //re-register notification
    RegisterNotification(DateTime.Now);

    //HERE -After this line "RegisterNotification(DateTime.Now);", it returns again to the line: "void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)"
}

User "User1586" is receiving multiple notifications.
The line "void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)" repeats several times.
If you have 50 online users, do 50 times on this line:

void SqlDep_OnChange(object sender, SqlNotificationEventArgs e)

If you have 1000 online users, do 1000 times on this line:

void SqlDep_OnChange(object sender, SqlNotificationEventArgs e).

 In other words, user "User1586" receives several notifications.

I followed the example here: http://www.dotnetawesome.com/2016/05/push-notification-system-with-signalr.html

Idea is to send notification to a specific user after database update.

Any solution ?

Body:
First of all, Sql dependency is not aware what data has changed. So you should query inside the event handler. If you want to send data corresponding the user id and specifically just for one user, I would recommend you to do like this;

Event Handler

private void SqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
    if (e.Info == SqlNotificationInfo.Insert)
    {
         RecordInfo info = GetLastInsertedRecord(); //Just a custom entity
          if(info.UserId > 0)
             NotificationHub.SendNotification(info.UserId);
    }
    RegisterNotification(DateTime.Now);
}

Hub

public static List<UserConnection> ListUser { get; set; }
public static void SendNotification(string who)
{
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    // Get specific user from connected ones.
    string Id = ListUser.Find(x => x.UserId == who).ConnectionId;
    context.Clients.Client(Id).addNotification(who); // or another data
}
//Add every connected users to the list
public override Task OnConnected()
    {
        ListUser = new List<UserConnection>();
        var us = new UserConnection();
        us.UserId = Context.QueryString["UserId"];
        us.ConnectionId = Context.ConnectionId;
        ListUser.Add(us);

        return base.OnConnected();
    }

UPDATE  Client

$(function () {
    var connection = $.connection.notificationHub;
    //Pass the userId here as querystring
    $.connection.hub.qs = "UserId=" + $("#labelHoldsUserId").val();
    //signalr method for push server message to client
    connection.client.addNotification = function (who) {
        //send notification here
        console.log(who + " sends message");
    };

    // Start hub
    $.connection.hub.start().done(function () {
        console.log("SignalR Started")
    });
})


来源: stackexchange

问:
Angular Js- Is there any way to generate dynamically checkbox which are also preselected?
I have been wandering for two to three hours and I found chunks of relevant questions but my scenario just take a little curve. I have to generate a number of checkboxes which obviously would be generated through ng-repeat. How can I show the preselected values which I am getting from Api. Here is the kind of data I am receiving.

Pre-selected data

```<code>$scope.categoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].
</code>```

and this is the data over which I am using ng-repeat.

ng-repeat data

```<code>$scope.categories = [{"id":1,"name":"Garden Cleaning"},{"id":2,"name":"Gutter Cleaning"},{"id":3,"name":"Home Cleaning"},{"id":4,"name":"Pool Cleaning"}
</code>```

HTML

```<code>  <div ng-repeat="cats in categories">
      <input type="checkbox" ng-model="categoriess.id[cats.id]">
               <label>{{cats.name}}</label>
                  </div>
</code>```

Now how would i tell ng-repeat to check the preselected data, plus if I want to check few more boxes they should also be checked and I want them to store in $scope.categoriess. I have tried a number of solution either with ng-checked or by make a function call in ng-checked I got no expected results.

答:
Why don't u format your data to have another property, something like

```<code>{"id":1,"name":"Garden Cleaning", "checked": true}
</code>```

Such way, when u iterate through the data, you can check the checkbox

```<code><div ng-repeat="cats in categories">
  <input type="checkbox" ng-checked="cats.checked">
  <label>{{cats.name}}</label>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been wandering for two to three hours and I found chunks of relevant questions but my scenario just take a little curve. I have to generate a number of checkboxes which obviously would be generated through ng-repeat. How can I show the preselected values which I am getting from Api. Here is the kind of data I am receiving.

Pre-selected data

$scope.categoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].

and this is the data over which I am using ng-repeat.

ng-repeat data

$scope.categories = [{"id":1,"name":"Garden Cleaning"},{"id":2,"name":"Gutter Cleaning"},{"id":3,"name":"Home Cleaning"},{"id":4,"name":"Pool Cleaning"}

HTML

      <input type="checkbox" ng-model="categoriess.id[cats.id]">
               {{cats.name}}

Now how would i tell ng-repeat to check the preselected data, plus if I want to check few more boxes they should also be checked and I want them to store in $scope.categoriess. I have tried a number of solution either with ng-checked or by make a function call in ng-checked I got no expected results.

Body:
Why don't u format your data to have another property, something like

{"id":1,"name":"Garden Cleaning", "checked": true}

Such way, when u iterate through the data, you can check the checkbox

<div ng-repeat="cats in categories">
  <input type="checkbox" ng-checked="cats.checked">
  <label>{{cats.name}}</label>
</div>


问:
Eclipse does not show MySQL driver when creating a new database connection
I am attempting to create a Database Connection to MySQL. I right click on connections and select create a new connection. I then select MySQL. There are no drivers displayed in the drop down list and I cannot seem to go on any further. I just reloaded MySQL with Connector/J. No luck.

I am using the Eclipse Version: Kepler Service Release 2 Build id: 20140224-0627 and MySQL mysql-installer-web-community-5.6.17.0

Any help would be appreciated.

Thank you,

Willie

答:
Step 1. Go to Eclipse Market Place

Step 2. Search key word by "Data Tools"

Step 3. Install "Eclipse DTP"


问:
Can Continuous Integration Services build Linux packages natively?
CI services like TravisCI automatically build and test applications from source control.  I'm new to C++ and linux, but it seems like wrapping compiled linux applications into .deb and .rpm packages for various linux distros would also be a very common need for a build pipeline.  I googled for a few hours, and can't find any documentation or reference to streamlined mechanism in Travis or elsewhere which makes this easy.  Perhaps C++ developers are accustomed to doing this kind of thing themselves and so they just script it in the build.

However, when trying to setup the pipeline for a new team and project with multiple packages, each targeting 5+ distros and wanting to test the resulting packages, it's a perfect candidate for a CI pipeline.  We want to deploy the packages on Bintray where we have several RPM and DEB repositories prepared to receive packages for the various distros.  However, we can find no trace of a widely-used solution which takes a compiled artifact and package definition, and then rolls them up and deploys them to these repos.

Does anyone have an easy-to-use and automated solution for building linux packages as they're built in Travis before being deployed to a repository?

答: You can use CPack for that - it allows you write a general package description and build a rpm, deb and msi from the description.</p>


问:
Resolving munmap warning message
I'm writing a program and have gotten a memory location that I have stored as a unsigned int and the length of the mapping as an unsigned int and I want to unmap this.

My following approach generates the warnings:

```<code>warning: passing argument 1 of ‘munmap’ makes pointer from integer without a cast [enabled by default]

/usr/include/i386-linux-gnu/sys/mman.h:77:12: note: expected ‘void *’ but argument is of type ‘unsigned int’
</code>```

and here is causing me the warning:

```<code>//startAddr and addrRange are stored as an unsigned int,
void unmap(mapping_t *maps, const int *curSize){
  int i = 0;
  for (; i < *curSize; i++){
     munmap(maps[i].startAddr, maps[i].addrRange);
  }
}
</code>```

My program also crashes when I hit the munmap, but I am assuming that has to deal with the warning in some way

definition of struct mapping_t as requested:

```<code>typedef struct mapping{
  unsigned int startAddr;
  unsigned int endAddr;
  unsigned int addrRange;
} mapping_t;
</code>```

答:
you cannot use unsigned int for pointers. Use void *.</p>

```<code>    typedef struct mapping{
      void * startAddr;
      void * endAddr;
      unsigned int addrRange;
    }
mapping_t;
</code>```

Title: Resolving munmap warning message

Body:
I'm writing a program and have gotten a memory location that I have stored as a unsigned int and the length of the mapping as an unsigned int and I want to unmap this.

My following approach generates the warnings:

warning: passing argument 1 of ‘munmap’ makes pointer from integer without a cast [enabled by default]

/usr/include/i386-linux-gnu/sys/mman.h:77:12: note: expected ‘void *’ but argument is of type ‘unsigned int’

and here is causing me the warning:

//startAddr and addrRange are stored as an unsigned int,
void unmap(mapping_t *maps, const int *curSize){
  int i = 0;
  for (; i < *curSize; i++){
     munmap(maps[i].startAddr, maps[i].addrRange);
  }
}

My program also crashes when I hit the munmap, but I am assuming that has to deal with the warning in some way

definition of struct mapping_t as requested:

typedef struct mapping{
  unsigned int startAddr;
  unsigned int endAddr;
  unsigned int addrRange;
} mapping_t;

Body:
you cannot use unsigned int for pointers. Use void *.

    typedef struct mapping{
      void * startAddr;
      void * endAddr;
      unsigned int addrRange;
    }
mapping_t;


问:
Excel to search 2 columns that have multiple the same but combined have only one output
I have a unique building number and a unique room number.

But I have 240 buildings and looking to reference a unique space number.

Example :-

```<code>Building No. Room Number Unique reference
1                101       X132
1                102       A123
1                103       C123
1                104       B123
2                101       G123
2                102       D343
3                101       X111
</code>```

So if i use Building 1 and room 103 = C123 been struggling with this for 24 hours so any help would be appreciated.

答:
Enter as an array formula with Ctrl + Shift + Enter

```<code>=INDEX(C:C,MATCH("1"&"103",A:A&B:B,0),0)
</code>```

Change 1 and 103 to cell references and limit the columns.

Body:
I have a unique building number and a unique room number.

But I have 240 buildings and looking to reference a unique space number.

Example :-

Building No. Room Number Unique reference
1                101       X132
1                102       A123
1                103       C123
1                104       B123
2                101       G123
2                102       D343
3                101       X111

So if i use Building 1 and room 103 = C123 been struggling with this for 24 hours so any help would be appreciated.

Body:
Enter as an array formula with Ctrl + Shift + Enter

=INDEX(C:C,MATCH("1"&"103",A:A&B:B,0),0)

Change 1 and 103 to cell references and limit the columns.


问:
Clustered Column Store Index gets created in the beginning and vanishes once the job is completed
I have an existing application which has many SQL Server stored procedures that run as below.These stored procs are applied on a data file and compute is done as per some business rules.

```<code>1) Pre-process
2) Process
3) Post-Process
</code>```

In Pre-process, we are creating 'n' no. of tables with clustered column store index in place.  When the job kicks off the tables get created with clustered column store index but the indexes vanish once the job is completed. ( This happens only for a large input data file. )

When I run the job on a small data file the clustered column store index gets created on the tables and it exists even after the completion of job.

Note :- The code is the same when i executed it for both small and large data files.

Can somebody share your thoughts on this if you have encountered similar problem?

答:
Two things will cause an already fully established Index to 'vanish' from a table:

A process or user deletes it.

The transaction in which the index was created is rolled back, either because an exception was raised later in the transaction, the transaction wasn't recoverable, or via an explicit Rollback.

And that's it. You're answer lies in one of the two above.

I know this is not the answer you were looking for, it is however guaranteed to be THE answer. Somewhere your code is failing and that's why the indexes are now vanishing.

Sql Server isn't a slapdash RDBMS - if it just arbitrarily just randomly dropped indexes then you know we'd be all over it. By your own admission you have complicated code.

Our DataWarehouse routinely drops and rebuilds indexes of all sorts - the only times it's 'missing' them has been the result of a bug in our code.

Body:
I have an existing application which has many SQL Server stored procedures that run as below.These stored procs are applied on a data file and compute is done as per some business rules.

1) Pre-process
2) Process
3) Post-Process

In Pre-process, we are creating 'n' no. of tables with clustered column store index in place.  When the job kicks off the tables get created with clustered column store index but the indexes vanish once the job is completed. ( This happens only for a large input data file. )

When I run the job on a small data file the clustered column store index gets created on the tables and it exists even after the completion of job.

Note :- The code is the same when i executed it for both small and large data files.

Can somebody share your thoughts on this if you have encountered similar problem?


问:
Can I access javascripts from iframe parent on another domain
I control both domains and could set whatever policies necessary. The domain in the iframe uses pretty much the same libraries and I was hoping to leech them off the parent if possible.

To be clear, I'm not asking how to make a cross-domain request. I'm asking how to get scripts from an iframe's parent, when the parent is on another domain.

I'm getting a permission error with this (trying jQuery here but same with my other libraries):

```<code>if (typeof(jQuery) == "undefined") {
  var iframebody = document.getElementsByTagName("body")[0];
  var jQuery = function (selector) { return parent.jQuery(selector, iframebody); };
  var $ = jQuery;
}
$("<h1>Hello World</h1>").appendTo("body");
</code>```

This would work if they were on the same domain.

I know this is cross-domain and is blocked for security reasons, but considering I control both domains and neither are security sensitive, I could set any policies as lax as I want to.

Can this be done?

答:
If you include the js from the same source in both pages, it will be just loaded once, but will be accessible on both sites:

```<code>//parent/main.html
<script src="jquery.js"></script>
<iframe src="http://other/iframe.html"></iframe>
<script>
  $(document.body).html("wohoo");
</script>

//other/iframe.html
 <script src="http://parent/jquery.js"></script>
<script>
  $(document.body).html("wohoo");
</script>
</code>```

So if theyre accessed in the iframe, the script is just loaded once, and if you access each of them without the other, it will still work too.

Body:
I control both domains and could set whatever policies necessary. The domain in the iframe uses pretty much the same libraries and I was hoping to leech them off the parent if possible.

To be clear, I'm not asking how to make a cross-domain request. I'm asking how to get scripts from an iframe's parent, when the parent is on another domain.

I'm getting a permission error with this (trying jQuery here but same with my other libraries):

if (typeof(jQuery) == "undefined") {
  var iframebody = document.getElementsByTagName("body")[0];
  var jQuery = function (selector) { return parent.jQuery(selector, iframebody); };
  var $ = jQuery;
}
$("
Hello World
").appendTo("body");

This would work if they were on the same domain.

I know this is cross-domain and is blocked for security reasons, but considering I control both domains and neither are security sensitive, I could set any policies as lax as I want to.

Can this be done?

Body:
If you include the js from the same source in both pages, it will be just loaded once, but will be accessible on both sites:

//parent/main.html
<script src="jquery.js"></script>
<iframe src="http://other/iframe.html"></iframe>
<script>
  $(document.body).html("wohoo");
</script>

//other/iframe.html
 <script src="http://parent/jquery.js"></script>
<script>
  $(document.body).html("wohoo");
</script>

So if theyre accessed in the iframe, the script is just loaded once, and if you access each of them without the other, it will still work too.


问:
Including Nuget Package details with TortoiseGit
Today I had some issues with my Nuget packages and had to update all of them.

Now I had a lot of unknown files coming up in my commit log. I added them and pushed as you can see:

Was that the right thing to do? Do we include Nuget package data files in source control ? Please let me know if you need for information.

Thank you.

答:
Normally you should exclude packages folder via .gitignore file

```<code># NuGet Packages
*.nupkg
packages/
</code>```

and exclude them to reduce repository size and get them via automatic package restore during build.

Body:
Normally you should exclude packages folder via .gitignore file

# NuGet Packages
*.nupkg
packages/

and exclude them to reduce repository size and get them via automatic package restore during build.


答:
I'm writing a program and have gotten a memory location that I have stored as a unsigned int

Do not do that.  Use void *, char *, or even [u]intptr_t.  Do not stuff a pointer into an unsigned int.  That is wrong.  Pointers are not int values and may not be properly represented by an int, which is why you get a warning.  Pointers are allowed to be converted to an int per the C standard - which is why you get a warning instead of an actual error - but there's no guarantee that the conversion back to a pointer value results in the same address.

and the length of the mapping as an unsigned int and I want to unmap this.

Do not do this either.  Use size_t:

```<code>typedef struct mapping{
  void *startAddr;
  size_t addrRange;
} mapping_t;
</code>```

You don't need endAddr as you have the start address and the size.  If you need the end address, you need to convert startAddr to a char * to compute the end address.

Title: Resolving munmap warning message

Body:
I'm writing a program and have gotten a memory location that I have stored as a unsigned int

Do not do that.  Use void *, char *, or even [u]intptr_t.  Do not stuff a pointer into an unsigned int.  That is wrong.  Pointers are not int values and may not be properly represented by an int, which is why you get a warning.  Pointers are allowed to be converted to an int per the C standard - which is why you get a warning instead of an actual error - but there's no guarantee that the conversion back to a pointer value results in the same address.

and the length of the mapping as an unsigned int and I want to unmap this.

Do not do this either.  Use size_t:

typedef struct mapping{
  void *startAddr;
  size_t addrRange;
} mapping_t;

You don't need endAddr as you have the start address and the size.  If you need the end address, you need to convert startAddr to a char * to compute the end address.


问:
PHP Array with implode not translating correctly inside php postgresql query
I have an array that when imploded with the appropriate syntax is formatted correctly. That is to say that it tests perfect in PGAdmin. However, when I try to display use the variable in my query it is changing the characters. Here is my code:

Posted from HTML Form:

```<code>$media= $_POST["userMedia"];
</code>```

implode:

```<code>$media_names = "'".implode( "%','", $media)."%'";
</code>```

dump of $media_names:

```<code>string(25) "'COMM_7029%','COMM_7030%'"
</code>```

What $media_names looks like in query error:

```<code> m.name LIKE any (array[''COMM_7029%','COMM_7030%''])
</code>```

I tried to eliminate the first " ' " from implode, but this was the resulting string dump:

```<code>string(24) "COMM_7029%','COMM_7030%'"
</code>```

The rest of the code:

User Form from which data is selected for POST:

```<code><select multiple name="userMedia" class="form-control" id="userMedia[]" style="height:350px;">
<?php
$conn = pg_connect("dblogin");

if (!$conn) {
echo "Did not connect.\n";
exit;
}
$sql = "SELECT medias.name FROM public.medias where medias.startdate >  '2015-01-01'";
$rs = pg_query($conn, $sql);

if (pg_num_rows($rs) > 0) {
// output data of each row
while($row = pg_fetch_assoc($rs)) {
$menu .= "<option value=".$row['name'].">" . $row['name']. "</option>";
}
}

echo $menu;

pg_close($conn);

?>
</select>
</code>```

PHP for Database Query:

```<code>$datea= $_POST["userDatea"];
$media= $_POST["userMedia"];
$datez= $_POST["userDatez"];
$media_names = "'".implode( "%','", $media)."%'";

var_dump($media_names);

 if( !empty($_SERVER['REQUEST_METHOD']) && (strcasecmp($_SERVER['REQUEST_METHOD'], 'post')===0)  ) {
// Create connection
$conn = pg_connect("dbconnect");

// Check connection
if (!$conn) {
echo "Did not connect.\n";
exit;
}
$result = pg_query($conn,
"SELECT
date (b.starttime),
Count(b.starttime) as Plays,
Count(distinct(b.playerid)) as Stores

FROM
public.billing b,
public.medias m,
public.players p

WHERE
b.mediaitemid = m.id and
p.id = b.playerid and
m.name LIKE any (array['$media_names']) and
b.starttime >= date('$datea') and
b.starttime < date('$datez')+1 and
m.startdate >  '2015-01-01'

GROUP BY
date (b.starttime)

ORDER BY
date (b.starttime);");

if (!$result) {
echo "Query failed.\n";
exit;
}
</code>```

答:
I removed the single quotes around $media_names in the query and it returned the data as expected.

Changed from:

```<code>m.name LIKE any (array['$media_names'])
</code>```

to this:

```<code>m.name LIKE any (array[$media_names])
</code>```

Body:
I have an array that when imploded with the appropriate syntax is formatted correctly. That is to say that it tests perfect in PGAdmin. However, when I try to display use the variable in my query it is changing the characters. Here is my code:

Posted from HTML Form:

$media= $_POST["userMedia"];

implode:

$media_names = "'".implode( "%','", $media)."%'";

dump of $media_names:

string(25) "'COMM_7029%','COMM_7030%'"

What $media_names looks like in query error:

 m.name LIKE any (array[''COMM_7029%','COMM_7030%''])

I tried to eliminate the first " ' " from implode, but this was the resulting string dump:

string(24) "COMM_7029%','COMM_7030%'"

The rest of the code:

User Form from which data is selected for POST:

<select multiple name="userMedia" class="form-control" id="userMedia[]" style="height:350px;">
<?php
$conn = pg_connect("dblogin");

if (!$conn) {
echo "Did not connect.\n";
exit;
}
$sql = "SELECT medias.name FROM public.medias where medias.startdate >  '2015-01-01'";
$rs = pg_query($conn, $sql);

if (pg_num_rows($rs) > 0) {
// output data of each row
while($row = pg_fetch_assoc($rs)) {
$menu .= "<option value=".$row['name'].">" . $row['name']. "</option>";
}
}

echo $menu;

pg_close($conn);

?>
</select>

PHP for Database Query:

$datea= $_POST["userDatea"];
$media= $_POST["userMedia"];
$datez= $_POST["userDatez"];
$media_names = "'".implode( "%','", $media)."%'";

var_dump($media_names);

 if( !empty($_SERVER['REQUEST_METHOD']) && (strcasecmp($_SERVER['REQUEST_METHOD'], 'post')===0)  ) {
// Create connection
$conn = pg_connect("dbconnect");

// Check connection
if (!$conn) {
echo "Did not connect.\n";
exit;
}
$result = pg_query($conn,
"SELECT
date (b.starttime),
Count(b.starttime) as Plays,
Count(distinct(b.playerid)) as Stores

FROM
public.billing b,
public.medias m,
public.players p

WHERE
b.mediaitemid = m.id and
p.id = b.playerid and
m.name LIKE any (array['$media_names']) and
b.starttime >= date('$datea') and
b.starttime < date('$datez')+1 and
m.startdate >  '2015-01-01'

GROUP BY
date (b.starttime)

ORDER BY
date (b.starttime);");

if (!$result) {
echo "Query failed.\n";
exit;
}

Body:
I removed the single quotes around $media_names in the query and it returned the data as expected.

Changed from:

m.name LIKE any (array['$media_names'])

to this:

m.name LIKE any (array[$media_names])


问:
How to pass parameters to callback?
Code callback in C#:

```<code>private void CallbackVisibleButton(IAsyncResult ar)
{
    AsynchronousVisibleButtonDelegate asyncDeleg = (AsynchronousVisibleButtonDelegate)ar.AsyncState;
    b.Visibility = asyncDeleg.EndInvoke(ar);// b - not see!
}
private delegate Visibility AsynchronousVisibleButtonDelegate(Button b);
private Visibility AsynchronousVisibleButton(Button b)
{
    Thread.Sleep(2000);
    return Visibility.Visible;
}
</code>```

and createted  (b is Button, 5 seconds after the button should be visible):

```<code>AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
AsyncCallback callback = new AsyncCallback(CallbackVisibleButton);
asyncDeleg.BeginInvoke(b, callback, asyncDeleg);
</code>```

problem: CallbackVisibleButton - does not see the button

答:
use the third parameter of the BeginInvoke to send extra information. then you can get it through the IAsyncResult.AsyncState property.

here is an example: http://progtutorials.tripod.com/C_Sharp.htm

ContentLicense: CC BY-SA 2.5

Title: How to pass parameters to callback?

Body:
Code callback in C#:

private void CallbackVisibleButton(IAsyncResult ar)
{
    AsynchronousVisibleButtonDelegate asyncDeleg = (AsynchronousVisibleButtonDelegate)ar.AsyncState;
    b.Visibility = asyncDeleg.EndInvoke(ar);// b - not see!
}
private delegate Visibility AsynchronousVisibleButtonDelegate(Button b);
private Visibility AsynchronousVisibleButton(Button b)
{
    Thread.Sleep(2000);
    return Visibility.Visible;
}

and createted  (b is Button, 5 seconds after the button should be visible):

AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);
AsyncCallback callback = new AsyncCallback(CallbackVisibleButton);
asyncDeleg.BeginInvoke(b, callback, asyncDeleg);

problem: CallbackVisibleButton - does not see the button


问:
Regex to match comma separated numbers or stop (Full match only)
I am trying to match comma separated numbers, but if any of the numbers is not valid stop regex and don't match it at all.

Here is an example that should be matched

```<code>3123123213212,3123123263212,3173123213212
</code>```

This string shouldn't be matched

```<code>3123123213212,3123123263212dad,3173123213212
</code>```

So at least one invalid number should lead to unmatched regex.

What I've tried is the following expression

```<code>(?:(\d+)(?=\,|\s|$))+
</code>```

Here is Regex101 link

https://regex101.com/r/JpuA5X/1

The problem that even if some number is invalid it matches other numbers, but this is not acceptable.

How can I modify my regex to get desired result ?

Thanks.

UPDATE

Sorry, I haven't mentioned, I need to group every single number.

答:
You don't need lookarounds for this. Anchors are sufficient:

```<code>/^\d+(?:,\d+)*$/
</code>```

Explanation:

^     # Start of string
\d+   # Match an integer number
(?:   # Start of non-capturing group
 ,    # Match a comma
 \d+  # Match an integer number
)*    # Repeat group any number of times (including 0)
$     # End of string
```

Body:
I am trying to match comma separated numbers, but if any of the numbers is not valid stop regex and don't match it at all.

Here is an example that should be matched

3123123213212,3123123263212,3173123213212

This string shouldn't be matched

3123123213212,3123123263212dad,3173123213212

So at least one invalid number should lead to unmatched regex.

What I've tried is the following expression

(?:(\d+)(?=\,|\s|$))+

Here is Regex101 link

https://regex101.com/r/JpuA5X/1

The problem that even if some number is invalid it matches other numbers, but this is not acceptable.

How can I modify my regex to get desired result ?

Thanks.

UPDATE

Sorry, I haven't mentioned, I need to group every single number.

Body:
You don't need lookarounds for this. Anchors are sufficient:

/^\d+(?:,\d+)*$/

Explanation:

^     # Start of string
\d+   # Match an integer number
(?:   # Start of non-capturing group
 ,    # Match a comma
 \d+  # Match an integer number
)*    # Repeat group any number of times (including 0)
$     # End of string


问:
GET request for specific id returning null
I'm attempting to build a simple CRUD application using express and mongodb. My GET request for all database entries is working and my POST request is working but I can't seem to figure out the problem with my GET request for individual entries.

Server.js GET request:

```<code>app.get('/api/:id', function (req, res) {
  var id = req.params.id;

  db.collection('api').findOne({_id: id}, (err, result) => {
    if (err){
      res.sendStatus(404);
      return console.log(err);
    }
    res.redirect('/');
    return console.log(result);

  });

});
</code>```

When I type 'url/api/593555074696601afa192d7f' which is an ID I know exists the console.log is returning null, I'm not sure if I'm doing something wrong?

答:
You should pass ObjectID instance in the query.

```<code>let ObjectID = require("mongodb").ObjectID;

app.get('/api/:id', function (req, res) {
  var id = req.params.id;

  db.collection('api').findOne({_id: ObjectID(id)}, (err, result) => {
    if (err){
      res.sendStatus(404);
      return console.log(err);
    }
    res.redirect('/');
    return console.log(result);

  });

});
</code>```

Give Mongoose a try. It might be of help if your models get complex.

Body:
I'm attempting to build a simple CRUD application using express and mongodb. My GET request for all database entries is working and my POST request is working but I can't seem to figure out the problem with my GET request for individual entries.

Server.js GET request:

app.get('/api/:id', function (req, res) {
  var id = req.params.id;

  db.collection('api').findOne({_id: id}, (err, result) => {
    if (err){
      res.sendStatus(404);
      return console.log(err);
    }
    res.redirect('/');
    return console.log(result);

  });

});

When I type 'url/api/593555074696601afa192d7f' which is an ID I know exists the console.log is returning null, I'm not sure if I'm doing something wrong?

Body:
You should pass ObjectID instance in the query.

let ObjectID = require("mongodb").ObjectID;

app.get('/api/:id', function (req, res) {
  var id = req.params.id;

  db.collection('api').findOne({_id: ObjectID(id)}, (err, result) => {
    if (err){
      res.sendStatus(404);
      return console.log(err);
    }
    res.redirect('/');
    return console.log(result);

  });

});

Give Mongoose a try. It might be of help if your models get complex.


问:
Identify, what Inno Setup tasks correspond to the items of TaskList (to show text on mouse over for certain tasks only)
So, I have these comtools tasks, which, as you can see, can have a different position in the tasks list, depending on which components were previously chosen. Moreover, they may not exist at all, if the user doesn't wish to install those components.
What I need is static text shown, but only when the cursor hovers over the  comtools tasks.

```<code>[Tasks]
Name: "acorig"; Description: "ac original"; GroupDescription: "Choose which version of ac to install:"; Flags: exclusive; Components: ac
Name: "acenh"; Description: "ac enhanced"; GroupDescription: "Choose which version of ac to install:"; Flags: exclusive unchecked; Components: ac
Name: "ac2comtools"; Description: "ac2"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: ac2
Name: "bccomtools"; Description: "bc"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc
Name: "bc2comtools"; Description: "bc2"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc
Name: "bc3comtools"; Description: "bc3"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc3
Name: "bc4comtools"; Description: "bc4"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc4
</code>```

Yes, I did see https://stackoverflow.com/a/37796528/3993104, but that ties the description to index, which is not practical here. Also, that code shows description for all items in TasksList.

Edit: So, the only change I made to the code after Martin's answer (aside from moving everything over to the tasks page) was adding Martin's function, and editing HoverComponentChanged like this:

procedure HoverComponentChanged(Index: Integer);
var
  Description: string;
begin
  case Index of
    -1: Description := '';
    LookupTask('ac2comtools'): Description := 'This is the description of AC2';
    LookupTask('bccomtools'): Description := 'This is the description of BC';
    LookupTask('bc2comtools'): Description := 'This is the description of BC2';
    LookupTask('bc3comtools'): Description := 'This is the description of BC3';
  else
    Description := '';
  end;
  TaskLabel.Caption := Description;
end;
```

-1 is a failsafe, since, when one of the components in deselected, then the index for the corresponding task is -1, which means you will see the description for the first deselected component in this list, when your cursor is outside of TasksList.

答:
There's really no straightforward way to identify, what tasks correspond to the items of TaskList.

Quick and dirty way is to use item description.

In this case, it's better to define the description using a custom message, so that you can refer to it in the code. And it's a must anyway, if your installer is localized.

[CustomMessages]
AC2ComTools=ac2

[Tasks]
Name: "ac2comtools"; Description: {cm:AC2ComTools}
```
<pre class="lang-pascal prettyprint-override"><code>[Code]

function LookupTask(TaskCustomMessage: string): Integer;
var
  Description: string;
begin
  Description := CustomMessage(TaskCustomMessage);
  Result := WizardForm.TasksList.Items.IndexOf(Description);
  Log(Format('Index of "%s" task is %d', [Description, Result]));
end;
</code>```

Use it like:

AC2ComToolsIndex := LookupTask('ac2comtools');
```
<hr />
<p>Another way is to reproduce the logic of Inno Setup for deciding, what tasks to show.</p>
<p>Use <code>WizardIsComponentSelected</code> function (<code>IsComponentSelected</code> before Inno Setup 6.0.2).</p>
<pre class="lang-pascal prettyprint-override"><code>// Before Inno Setup 6.0.2, use IsComponentSelected.
if WizardIsComponentSelected('ac2') then
begin
  if WizardIsComponentSelected('ac') then AC2ComToolsIndex := 4
    else AC2ComToolsIndex := 1;
end
  else AC2ComToolsIndex := -1;
</code>```

If you want to create a full mapping from task name to TaskList item index automatically, you can do something like this each time the task list changes, i.e. on call to CurPageChanged(wpSelectTasks):

Remember current task state

Check all task checkboxes

Read WizardSelectedTasks(False) to get names of all tasks

Generate the mapping

Restore previous task state.

This is relatively easy, when there are only checkboxes, not radio buttons (i.e. no task with exclusive flag).

var
  Tasks: TStringList;

procedure CurPageChanged(CurPageID: Integer);
var
  TasksChecked: array of Boolean;
  I: Integer;
begin
  if CurPageID = wpSelectTasks then
  begin
    SetArrayLength(TasksChecked, WizardForm.TasksList.Items.Count);
    // Remember current task state + Check all task checkboxes
    for I := 0 to WizardForm.TasksList.Items.Count - 1 do
    begin
      TasksChecked[I] := WizardForm.TasksList.Checked[I];
      WizardForm.TasksList.Checked[I] := True;
    end;
    Tasks := TStringList.Create;
    Tasks.CommaText := WizardSelectedTasks(False);
    for I := 0 to WizardForm.TasksList.Items.Count - 1 do
    begin
      // Insert blank items for "group descriptions"
      if WizardForm.TasksList.ItemObject[I] = nil then
        Tasks.Insert(I, '');
      // Restore previous task state
      WizardForm.TasksList.Checked[I] := TasksChecked[I];
    end;
  end;
end;
```
<p>Now you can use the <code>Tasks</code> to lookup corresponding task index:</p>
<pre class="lang-pascal prettyprint-override"><code>AC2ComToolsIndex := Tasks.IndexOf('ac2comtools');
</code>```

Though as you have exclusive tasks, you would need much more complicated code.

ContentLicense: CC BY-SA 4.0

Body:
So, I have these comtools tasks, which, as you can see, can have a different position in the tasks list, depending on which components were previously chosen. Moreover, they may not exist at all, if the user doesn't wish to install those components.
What I need is static text shown, but only when the cursor hovers over the  comtools tasks.

[Tasks]
Name: "acorig"; Description: "ac original"; GroupDescription: "Choose which version of ac to install:"; Flags: exclusive; Components: ac
Name: "acenh"; Description: "ac enhanced"; GroupDescription: "Choose which version of ac to install:"; Flags: exclusive unchecked; Components: ac
Name: "ac2comtools"; Description: "ac2"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: ac2
Name: "bccomtools"; Description: "bc"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc
Name: "bc2comtools"; Description: "bc2"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc
Name: "bc3comtools"; Description: "bc3"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc3
Name: "bc4comtools"; Description: "bc4"; GroupDescription: "Also install community-made tools (unsupported) for:"; Flags: unchecked; Components: bc4

Yes, I did see https://stackoverflow.com/a/37796528/3993104, but that ties the description to index, which is not practical here. Also, that code shows description for all items in TasksList.

Edit: So, the only change I made to the code after Martin's answer (aside from moving everything over to the tasks page) was adding Martin's function, and editing HoverComponentChanged like this:

procedure HoverComponentChanged(Index: Integer);
var
  Description: string;
begin
  case Index of
    -1: Description := '';
    LookupTask('ac2comtools'): Description := 'This is the description of AC2';
    LookupTask('bccomtools'): Description := 'This is the description of BC';
    LookupTask('bc2comtools'): Description := 'This is the description of BC2';
    LookupTask('bc3comtools'): Description := 'This is the description of BC3';
  else
    Description := '';
  end;
  TaskLabel.Caption := Description;
end;

-1 is a failsafe, since, when one of the components in deselected, then the index for the corresponding task is -1, which means you will see the description for the first deselected component in this list, when your cursor is outside of TasksList.

Body:
There's really no straightforward way to identify, what tasks correspond to the items of TaskList.

Quick and dirty way is to use item description.

In this case, it's better to define the description using a custom message, so that you can refer to it in the code. And it's a must anyway, if your installer is localized.

[CustomMessages]
AC2ComTools=ac2

[Tasks]
Name: "ac2comtools"; Description: {cm:AC2ComTools}

[Code]

function LookupTask(TaskCustomMessage: string): Integer;
var
  Description: string;
begin
  Description := CustomMessage(TaskCustomMessage);
  Result := WizardForm.TasksList.Items.IndexOf(Description);
  Log(Format('Index of "%s" task is %d', [Description, Result]));
end;

Use it like:

AC2ComToolsIndex := LookupTask('ac2comtools');

Another way is to reproduce the logic of Inno Setup for deciding, what tasks to show.

Use WizardIsComponentSelected function (IsComponentSelected before Inno Setup 6.0.2).

// Before Inno Setup 6.0.2, use IsComponentSelected.
if WizardIsComponentSelected('ac2') then
begin
  if WizardIsComponentSelected('ac') then AC2ComToolsIndex := 4
    else AC2ComToolsIndex := 1;
end
  else AC2ComToolsIndex := -1;

If you want to create a full mapping from task name to TaskList item index automatically, you can do something like this each time the task list changes, i.e. on call to CurPageChanged(wpSelectTasks):

Remember current task state

Check all task checkboxes

Read WizardSelectedTasks(False) to get names of all tasks

Generate the mapping

Restore previous task state.

This is relatively easy, when there are only checkboxes, not radio buttons (i.e. no task with exclusive flag).

var
  Tasks: TStringList;

procedure CurPageChanged(CurPageID: Integer);
var
  TasksChecked: array of Boolean;
  I: Integer;
begin
  if CurPageID = wpSelectTasks then
  begin
    SetArrayLength(TasksChecked, WizardForm.TasksList.Items.Count);
    // Remember current task state + Check all task checkboxes
    for I := 0 to WizardForm.TasksList.Items.Count - 1 do
    begin
      TasksChecked[I] := WizardForm.TasksList.Checked[I];
      WizardForm.TasksList.Checked[I] := True;
    end;
    Tasks := TStringList.Create;
    Tasks.CommaText := WizardSelectedTasks(False);
    for I := 0 to WizardForm.TasksList.Items.Count - 1 do
    begin
      // Insert blank items for "group descriptions"
      if WizardForm.TasksList.ItemObject[I] = nil then
        Tasks.Insert(I, '');
      // Restore previous task state
      WizardForm.TasksList.Checked[I] := TasksChecked[I];
    end;
  end;
end;

Now you can use the Tasks to lookup corresponding task index:

AC2ComToolsIndex := Tasks.IndexOf('ac2comtools');

Though as you have exclusive tasks, you would need much more complicated code.


问:
How to read file and save data On LISP programming language
I have a question about LISP Programming language

What I have to do is read a file and save data in the file.

To do this, I found the function like this and executed it.

```<code>(defun get-file (pathname)
  (with-open-file (stream pathname)
    (loop for line = (read-line stream nil)
          while line
          collect line)))

get-file("sample.txt")
</code>```

This printed "unbound variable". Why did the error happened?
(If I just defined the function and compiled, there was no error)

How do I write the pathname correctly?
(My data file (sample.txt) is in the same directory of LISP code file.)

And where the data had saved?

And how I can divide them (because the file is read line by line, the data with seperate attributes should be save in same line)

file data are saved like this

```<code>name 23.0 22 123 33  //(one string and four numbers)
name2 23.5 11 156 42 //(one string and four numbers)
name3 21.7 15 167 55 //(one string and four numbers)
</code>```

Please help me
I'am awkward in LISP Language because I'm fully adapted in C Language :(

Thanks a lot!!

答:
```<code>get-file
("sample.txt")
</code>```

Are two expressions.. One that evaluates the variable get-file since it is not used as a function. Then you have the expression ("sample.txt") which tries to take the string "sample.txt" and call it as if it was a function with no arguments.

The reason for this is that you are writing algol syntax, as if it was C or Java. You need to write lisp syntax when you are writing lisp, like this:

```<code>(get-file "sample.txt")
</code>```

The path name is relative to the path you start the program so if you start the program from the same directory as you lisp file it will open files there. If you were at your home directory the path is relative to that unless you use absolute path.

In order to save data you need to open a file to save to and output to that file. How it is now you just make a list of the lines and that is returned no screen in the REPL.

You may split the string by space. You can convert the strings that represent numbers to numbers by using parse-number. An unsafe way would be (read-from-string "3.0") ; ==> 3.0

You need to prepare yourself to learn a new language. It has different syntax than C, which is based on Algol. Almost all programming languages today are so if you know several languages you know perhaps several dialects of the same language. Give it time and you'll have a new favorite programming language soon..

Body:
I have a question about LISP Programming language

What I have to do is read a file and save data in the file.

To do this, I found the function like this and executed it.

(defun get-file (pathname)
  (with-open-file (stream pathname)
    (loop for line = (read-line stream nil)
          while line
          collect line)))

get-file("sample.txt")

This printed "unbound variable". Why did the error happened?
(If I just defined the function and compiled, there was no error)

How do I write the pathname correctly?
(My data file (sample.txt) is in the same directory of LISP code file.)

And where the data had saved?

And how I can divide them (because the file is read line by line, the data with seperate attributes should be save in same line)

file data are saved like this

name 23.0 22 123 33  //(one string and four numbers)
name2 23.5 11 156 42 //(one string and four numbers)
name3 21.7 15 167 55 //(one string and four numbers)

Please help me
I'am awkward in LISP Language because I'm fully adapted in C Language :(

Thanks a lot!!

Body:
get-file
("sample.txt")

Are two expressions.. One that evaluates the variable get-file since it is not used as a function. Then you have the expression ("sample.txt") which tries to take the string "sample.txt" and call it as if it was a function with no arguments.

The reason for this is that you are writing algol syntax, as if it was C or Java. You need to write lisp syntax when you are writing lisp, like this:

(get-file "sample.txt")

The path name is relative to the path you start the program so if you start the program from the same directory as you lisp file it will open files there. If you were at your home directory the path is relative to that unless you use absolute path.

In order to save data you need to open a file to save to and output to that file. How it is now you just make a list of the lines and that is returned no screen in the REPL.

You may split the string by space. You can convert the strings that represent numbers to numbers by using parse-number. An unsafe way would be (read-from-string "3.0") ; ==> 3.0

You need to prepare yourself to learn a new language. It has different syntax than C, which is based on Algol. Almost all programming languages today are so if you know several languages you know perhaps several dialects of the same language. Give it time and you'll have a new favorite programming language soon..


Title: Regex to match comma separated numbers or stop (Full match only)

Body:
You could look for start and end and the parts between.

var regex = /^(\d+,)*\d+$/;

console.log('3123123213212,3123123263212,3173123213212'.match(regex));
console.log('3123123213212,3123123263212abc,3173123213212'.match(regex));


问:
Place Snackbar at highest z order to avoid from being blocked by AutoCompleteTextView drop down
I have a Snackbar which is as follows:

However, if the drop down of the AutoCompleteTextView is too long, the drop down will block the Snackbar.

As you can see in the above image, the Snackbar is actually showing. However, its visibility is blocked by the long drop down. You can see from the above image

I try to use the following Snackbar code. Adding bringToFront() doesn't help much.

```<code>private void showSnackbar(String message) {
    Snackbar snackbar
            = Snackbar.make(getActivity().findViewById(R.id.content), message, Snackbar.LENGTH_LONG);
    snackbar.getView().bringToFront();
    snackbar.show();
}
</code>```

R.id.content is a CoordinatorLayout:

```<code>    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/content"
        android:background="?attr/MyActivityBackground"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?attr/headerShadow" />
</code>```

Is there any good way, to avoid Snackbar from being covered by AutoCompleteTextView's drop down?

答:
I might have a solution for that case. Of course, there are some assumptions but maybe the solution would suit you.

The key here is putting AutoCompleteTextView inside CoordinatorLayout and add custom CoordinatorLayout.Behavior to it.

Create appropriate Behavior for your class:

```<code>public class AutoCompleteTextViewBehaviour extends CoordinatorLayout.Behavior<AutoCompleteTextView> {

    public AutoCompleteTextViewBehaviour(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, AutoCompleteTextView child, View dependency) {
        return dependency instanceof Snackbar.SnackbarLayout;
    }
}
</code>```

Override a method layoutDependsOn:

```<code>@Override
public boolean layoutDependsOn(CoordinatorLayout parent, AutoCompleteTextView child, View dependency) {
    return dependency instanceof Snackbar.SnackbarLayout;
}
</code>```

Get reference to AutoCompleteTextView popup view:

Unfortunately I haven't found a simple solution for that. However can be done via reflection.

```<code>@Nullable
private View getPopupList(AutoCompleteTextView child) {
    try {
        Field popupField;
        Class clazz;
        if (child instanceof AppCompatAutoCompleteTextView) {
            clazz = child.getClass().getSuperclass();
        } else {
            clazz = child.getClass();
        }
        popupField = clazz.getDeclaredField("mPopup");
        popupField.setAccessible(true);
        ListPopupWindow popup = (ListPopupWindow) popupField.get(child);
        Field popupListViewField = popup.getClass().getDeclaredField("mDropDownList");
        popupListViewField.setAccessible(true);
        return (View) popupListViewField.get(popup);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

Override onDependentViewChanged method:

```<code>@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, final AutoCompleteTextView child, View dependency) {
    if (popupList == null) {
        popupList = getPopupList(child);
        if (popupList == null) {
            return super.onDependentViewChanged(parent, child, dependency);
        }
    }
    int dropdownBottom = child.getBottom() + child.getDropDownVerticalOffset() + popupList.getHeight();
    int snackBarTop = dependency.getTop();
    int difference = dropdownBottom - snackBarTop;
    if (difference > 0) {
        child.setDropDownHeight(popupList.getHeight() - difference);
        return true;
    } else {
        child.setDropDownHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    return super.onDependentViewChanged(parent, child, dependency);
}
</code>```

Apply the behavior to AutocompleteTextView in .xml:

```<code>app:layout_behavior="com.example.package.AutoCompleteTextViewBehaviour"/>
</code>```

Of course this is a very basic solution, that for example does not animate list height, but I think this is a good start. Here is the full gist.

Body:
I have a Snackbar which is as follows:

However, if the drop down of the AutoCompleteTextView is too long, the drop down will block the Snackbar.

As you can see in the above image, the Snackbar is actually showing. However, its visibility is blocked by the long drop down. You can see from the above image

I try to use the following Snackbar code. Adding bringToFront() doesn't help much.

private void showSnackbar(String message) {
    Snackbar snackbar
            = Snackbar.make(getActivity().findViewById(R.id.content), message, Snackbar.LENGTH_LONG);
    snackbar.getView().bringToFront();
    snackbar.show();
}

R.id.content is a CoordinatorLayout:

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/content"
        android:background="?attr/MyActivityBackground"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?attr/headerShadow" />

Is there any good way, to avoid Snackbar from being covered by AutoCompleteTextView's drop down?

Body:
I might have a solution for that case. Of course, there are some assumptions but maybe the solution would suit you.

The key here is putting AutoCompleteTextView inside CoordinatorLayout and add custom CoordinatorLayout.Behavior to it.

Create appropriate Behavior for your class:

public class AutoCompleteTextViewBehaviour extends CoordinatorLayout.Behavior<AutoCompleteTextView> {

    public AutoCompleteTextViewBehaviour(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, AutoCompleteTextView child, View dependency) {
        return dependency instanceof Snackbar.SnackbarLayout;
    }
}

Override a method layoutDependsOn:

@Override
public boolean layoutDependsOn(CoordinatorLayout parent, AutoCompleteTextView child, View dependency) {
    return dependency instanceof Snackbar.SnackbarLayout;
}

Get reference to AutoCompleteTextView popup view:

Unfortunately I haven't found a simple solution for that. However can be done via reflection.

@Nullable
private View getPopupList(AutoCompleteTextView child) {
    try {
        Field popupField;
        Class clazz;
        if (child instanceof AppCompatAutoCompleteTextView) {
            clazz = child.getClass().getSuperclass();
        } else {
            clazz = child.getClass();
        }
        popupField = clazz.getDeclaredField("mPopup");
        popupField.setAccessible(true);
        ListPopupWindow popup = (ListPopupWindow) popupField.get(child);
        Field popupListViewField = popup.getClass().getDeclaredField("mDropDownList");
        popupListViewField.setAccessible(true);
        return (View) popupListViewField.get(popup);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

Override onDependentViewChanged method:

@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, final AutoCompleteTextView child, View dependency) {
    if (popupList == null) {
        popupList = getPopupList(child);
        if (popupList == null) {
            return super.onDependentViewChanged(parent, child, dependency);
        }
    }
    int dropdownBottom = child.getBottom() + child.getDropDownVerticalOffset() + popupList.getHeight();
    int snackBarTop = dependency.getTop();
    int difference = dropdownBottom - snackBarTop;
    if (difference > 0) {
        child.setDropDownHeight(popupList.getHeight() - difference);
        return true;
    } else {
        child.setDropDownHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    return super.onDependentViewChanged(parent, child, dependency);
}

Apply the behavior to AutocompleteTextView in .xml:

app:layout_behavior="com.example.package.AutoCompleteTextViewBehaviour"/>

Of course this is a very basic solution, that for example does not animate list height, but I think this is a good start. Here is the full gist.


问:
Does Microsoft's CAPICOM ActiveX control support SHA-2?
Our company is switching over from using SHA-1 certificates to SHA-2 certificates.

I noticed that CAPICOM only has a CAPICOM_CERTIFICATE_FIND_SHA1_HASH find method.

Will switching over from SHA-1 to SHA-2 mean we will need to switch to an alternative to CAPICOM for verifiying/encrypting/decrypting using these certificates?

答:
CAPICOM_CERTIFICATE_FIND_SHA1_HASH - that's not about hash algorithm, used for signing, but about searching for certificate via fingerprint (i.e. hash of certificate data).
Since CAPICOM uses Microsoft crypto providers, which supports CALG_SHA_256, Capicom should support them as well.

However, you can use other commercial solution, there is a bunch of them, available on the market (BouncCastle, /n software, SecureBlackbox).


问:
Nuget: The remote server returned an error: (504) Gateway Timeout
I'm using Visual Studio 2015 preview CTP 5 and I'm having problems installing some packages.

If I use the NPM UI I get

```<code>The remote server returned an error: (504) Gateway Timeout.
</code>```

If I use the PM Console with Install-Package Ninject.MVC5 I get :

```<code>The source at nuget.org [https://www.nuget.org/api/v2/] is unreachable. Falling back to NuGet Local Cache at {userfolder}\AppData\Local\NuGet\Cache
Install-Package : Unable to find package 'Ninject.MVC5'.
</code>```

If I type: Install-Package Ninject.MVC5 -source nuget.org i get the same UI error :

```<code>Install-Package : The remote server returned an error: (504) Gateway Timeout.
</code>```

I tryied this from other sources that points to solution but none worked.
I see a similar problem on nuget but a code 'fix' was release according to the github repo on January, 15.

I'm not sure if this is on my end or a nuget server problem, tryied to reach them at twitter with no response still, don't know what else to try.

答: What worked for me: I had to change network type from "Shared Network / NAT" to "Bridged" when trying to run NuGet inside a virtual machine (Parallels and macOS).</p>

Body:
I'm using Visual Studio 2015 preview CTP 5 and I'm having problems installing some packages.

If I use the NPM UI I get

The remote server returned an error: (504) Gateway Timeout.

If I use the PM Console with Install-Package Ninject.MVC5 I get :

The source at nuget.org [https://www.nuget.org/api/v2/] is unreachable. Falling back to NuGet Local Cache at {userfolder}\AppData\Local\NuGet\Cache
Install-Package : Unable to find package 'Ninject.MVC5'.

If I type: Install-Package Ninject.MVC5 -source nuget.org i get the same UI error :

Install-Package : The remote server returned an error: (504) Gateway Timeout.

I tryied this from other sources that points to solution but none worked.
I see a similar problem on nuget but a code 'fix' was release according to the github repo on January, 15.

I'm not sure if this is on my end or a nuget server problem, tryied to reach them at twitter with no response still, don't know what else to try.


问:
EntityManager's Connection always returns fals when committing
I'm trying to execute a transaction the lowest level possible inside a symfony app:

```<code>$conn = $this->em->getConnection();
$conn->beginTransaction();
$success = $conn->commit();
</code>```

but $success is always false. Why is that?

答:
commit doesn't return a boolean value, It throw an exception if there is something wrong.
To be sure that the transaction success use a try catch like this:

```<code>try{
    $conn->commit();
} catch (\Exception $e) {
    $conn->rollBack();
    throw $e;
}
</code>```

Body:
I'm trying to execute a transaction the lowest level possible inside a symfony app:

$conn = $this->em->getConnection();
$conn->beginTransaction();
$success = $conn->commit();

but $success is always false. Why is that?

Body:
commit doesn't return a boolean value, It throw an exception if there is something wrong.
To be sure that the transaction success use a try catch like this:

try{
    $conn->commit();
} catch (\Exception $e) {
    $conn->rollBack();
    throw $e;
}


问:
Auto Scale TextView Text to Fit within Bounds
I'm looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I'm not simply looking for a way to wrap the text- I want to make sure it both wraps and is small enough to fit entirely on the screen.

I've seen a few cases on StackOverflow where auto resizing was needed, but they are either very special cases with hack solutions, have no solution, or involve re-drawing the TextView recursively until it is small enough (which is memory intense and forces the user to watch the text shrink step-by-step with every recursion).

But I'm sure somebody out there has found a good solution that doesn't involve what I'm doing: writing several heavy routines that parse and measure the text, resize the text, and repeat until a suitably small size has been found.

What routines does TextView use to wrap the text? Couldn't those be somehow used to predict whether text will be small enough?

tl;dr: is there a best-practice way to auto-resize a TextView to fit, wrapped, in its getHeight and getWidth bounds?

答:
If anyone needs it, here is the same code snippet but for Xamarin.Android.</p>

```<code>/**
 *               DO WHAT YOU WANT TO PUBLIC LICENSE
 *                    Version 1, December 2017
 *
 * Copyright (C) 2017 Nathan Westfall
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *  0. You just DO WHAT YOU WANT TO.
 */

using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.Util;
using Android.Text;

using Java.Lang;

namespace My.Text
{
    public class AutoResizeTextView : TextView
    {
        public const float MIN_TEXT_SIZE = 20;

        public interface OnTextResizeListener
        {
            void OnTextResize(TextView textView, float oldSize, float newSize);
        }

        private const string mEllipsis = "...";

        private OnTextResizeListener mTextResizeListener;

        private bool mNeedsResize = false;

        private float mTextSize;

        private float mMaxTextSize = 0;

        private float mMinTextSize = MIN_TEXT_SIZE;

        private float mSpacingMult = 1.0f;

        private float mSpacingAdd = 0.0f;

        public bool AddEllipsis { get; set; } = true;

        public AutoResizeTextView(Context context) : this(context, null) { }

        public AutoResizeTextView(Context context, IAttributeSet attrs) : this(context, attrs, 0) { }

        public AutoResizeTextView(Context context, IAttributeSet attrs, int defStyle): base(context, attrs, defStyle)
        {
            mTextSize = TextSize;
        }

        protected override void OnTextChanged(ICharSequence text, int start, int lengthBefore, int lengthAfter)
        {
            base.OnTextChanged(text, start, lengthBefore, lengthAfter);

            mNeedsResize = true;

            ResetTextSize();
        }

        protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
        {
            base.OnSizeChanged(w, h, oldw, oldh);

            if (w != oldw || h != oldh)
                mNeedsResize = true;
        }

        public void SetOnResizeListener(OnTextResizeListener listener)
        {
            mTextResizeListener = listener;
        }

        public override void SetTextSize([GeneratedEnum] ComplexUnitType unit, float size)
        {
            base.SetTextSize(unit, size);

            mTextSize = TextSize;
        }

        public override void SetLineSpacing(float add, float mult)
        {
            base.SetLineSpacing(add, mult);

            mSpacingMult = mult;
            mSpacingAdd = add;
        }

        public void SetMaxTextSize(float maxTextSize)
        {
            mMaxTextSize = maxTextSize;
            RequestLayout();
            Invalidate();
        }

        public float GetMaxTextSize()
        {
            return mMaxTextSize;
        }

        public void SetMinTextSize(float minTextSize)
        {
            mMinTextSize = minTextSize;
            RequestLayout();
            Invalidate();
        }

        public float GetMinTextSize()
        {
            return mMinTextSize;
        }

        public void ResetTextSize()
        {
            if(mTextSize > 0)
            {
                base.SetTextSize(ComplexUnitType.Px, mTextSize);
                mMaxTextSize = mTextSize;
            }
        }

        protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
        {
            if(changed || mNeedsResize)
            {
                int widthLimit = (right - left) - CompoundPaddingLeft - CompoundPaddingRight;
                int heightLimit = (bottom - top) - CompoundPaddingBottom - CompoundPaddingTop;
                ResizeText(widthLimit, heightLimit);
            }
            base.OnLayout(changed, left, top, right, bottom);

            base.OnLayout(changed, left, top, right, bottom);
        }

        public void ResizeText()
        {
            int heightLimit = Height - PaddingBottom - PaddingTop;
            int widthLimit = Width - PaddingLeft - PaddingRight;
            ResizeText(widthLimit, heightLimit);
        }

        public void ResizeText(int width, int height)
        {
            var text = TextFormatted;
            if (text == null || text.Length() == 0 || height <= 0 || width <= 0 || mTextSize == 0)
                return;

            if (TransformationMethod != null)
                text = TransformationMethod.GetTransformationFormatted(TextFormatted, this);

            TextPaint textPaint = Paint;

            float oldTextSize = textPaint.TextSize;
            float targetTextSize = mMaxTextSize > 0 ? System.Math.Min(mTextSize, mMaxTextSize) : mTextSize;

            int textHeight = GetTextHeight(text, textPaint, width, targetTextSize);

            while(textHeight > height && targetTextSize > mMinTextSize)
            {
                targetTextSize = System.Math.Max(targetTextSize - 2, mMinTextSize);
                textHeight = GetTextHeight(text, textPaint, width, targetTextSize);
            }

            if(AddEllipsis && targetTextSize == mMinTextSize && textHeight > height)
            {
                TextPaint paint = new TextPaint(textPaint);

                StaticLayout layout = new StaticLayout(text, paint, width, Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
                if(layout.LineCount > 0)
                {
                    int lastLine = layout.GetLineForVertical(height) - 1;
                    if (lastLine < 0)
                        SetText("", BufferType.Normal);
                    else
                    {
                        int start = layout.GetLineStart(lastLine);
                        int end = layout.GetLineEnd(lastLine);
                        float lineWidth = layout.GetLineWidth(lastLine);
                        float ellipseWidth = textPaint.MeasureText(mEllipsis);

                        while (width < lineWidth + ellipseWidth)
                            lineWidth = textPaint.MeasureText(text.SubSequence(start, --end + 1).ToString());
                        SetText(text.SubSequence(0, end) + mEllipsis, BufferType.Normal);
                    }
                }
            }

            SetTextSize(ComplexUnitType.Px, targetTextSize);
            SetLineSpacing(mSpacingAdd, mSpacingMult);

            mTextResizeListener?.OnTextResize(this, oldTextSize, targetTextSize);

            mNeedsResize = false;
        }

        private int GetTextHeight(ICharSequence source, TextPaint paint, int width, float textSize)
        {
            TextPaint paintCopy = new TextPaint(paint);
            paintCopy.TextSize = textSize;
            StaticLayout layout = new StaticLayout(source, paintCopy, width, Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
            return layout.Height;
        }
    }
}
</code>```

Body:
If anyone needs it, here is the same code snippet but for Xamarin.Android.

/**
 *               DO WHAT YOU WANT TO PUBLIC LICENSE
 *                    Version 1, December 2017
 *
 * Copyright (C) 2017 Nathan Westfall
 *
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 *
 *            DO WHAT YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 *
 *  0. You just DO WHAT YOU WANT TO.
 */

using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.Util;
using Android.Text;

using Java.Lang;

namespace My.Text
{
    public class AutoResizeTextView : TextView
    {
        public const float MIN_TEXT_SIZE = 20;

        public interface OnTextResizeListener
        {
            void OnTextResize(TextView textView, float oldSize, float newSize);
        }

        private const string mEllipsis = "...";

        private OnTextResizeListener mTextResizeListener;

        private bool mNeedsResize = false;

        private float mTextSize;

        private float mMaxTextSize = 0;

        private float mMinTextSize = MIN_TEXT_SIZE;

        private float mSpacingMult = 1.0f;

        private float mSpacingAdd = 0.0f;

        public bool AddEllipsis { get; set; } = true;

        public AutoResizeTextView(Context context) : this(context, null) { }

        public AutoResizeTextView(Context context, IAttributeSet attrs) : this(context, attrs, 0) { }

        public AutoResizeTextView(Context context, IAttributeSet attrs, int defStyle): base(context, attrs, defStyle)
        {
            mTextSize = TextSize;
        }

        protected override void OnTextChanged(ICharSequence text, int start, int lengthBefore, int lengthAfter)
        {
            base.OnTextChanged(text, start, lengthBefore, lengthAfter);

            mNeedsResize = true;

            ResetTextSize();
        }

        protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
        {
            base.OnSizeChanged(w, h, oldw, oldh);

            if (w != oldw || h != oldh)
                mNeedsResize = true;
        }

        public void SetOnResizeListener(OnTextResizeListener listener)
        {
            mTextResizeListener = listener;
        }

        public override void SetTextSize([GeneratedEnum] ComplexUnitType unit, float size)
        {
            base.SetTextSize(unit, size);

            mTextSize = TextSize;
        }

        public override void SetLineSpacing(float add, float mult)
        {
            base.SetLineSpacing(add, mult);

            mSpacingMult = mult;
            mSpacingAdd = add;
        }

        public void SetMaxTextSize(float maxTextSize)
        {
            mMaxTextSize = maxTextSize;
            RequestLayout();
            Invalidate();
        }

        public float GetMaxTextSize()
        {
            return mMaxTextSize;
        }

        public void SetMinTextSize(float minTextSize)
        {
            mMinTextSize = minTextSize;
            RequestLayout();
            Invalidate();
        }

        public float GetMinTextSize()
        {
            return mMinTextSize;
        }

        public void ResetTextSize()
        {
            if(mTextSize > 0)
            {
                base.SetTextSize(ComplexUnitType.Px, mTextSize);
                mMaxTextSize = mTextSize;
            }
        }

        protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
        {
            if(changed || mNeedsResize)
            {
                int widthLimit = (right - left) - CompoundPaddingLeft - CompoundPaddingRight;
                int heightLimit = (bottom - top) - CompoundPaddingBottom - CompoundPaddingTop;
                ResizeText(widthLimit, heightLimit);
            }
            base.OnLayout(changed, left, top, right, bottom);

            base.OnLayout(changed, left, top, right, bottom);
        }

        public void ResizeText()
        {
            int heightLimit = Height - PaddingBottom - PaddingTop;
            int widthLimit = Width - PaddingLeft - PaddingRight;
            ResizeText(widthLimit, heightLimit);
        }

        public void ResizeText(int width, int height)
        {
            var text = TextFormatted;
            if (text == null || text.Length() == 0 || height <= 0 || width <= 0 || mTextSize == 0)
                return;

            if (TransformationMethod != null)
                text = TransformationMethod.GetTransformationFormatted(TextFormatted, this);

            TextPaint textPaint = Paint;

            float oldTextSize = textPaint.TextSize;
            float targetTextSize = mMaxTextSize > 0 ? System.Math.Min(mTextSize, mMaxTextSize) : mTextSize;

            int textHeight = GetTextHeight(text, textPaint, width, targetTextSize);

            while(textHeight > height && targetTextSize > mMinTextSize)
            {
                targetTextSize = System.Math.Max(targetTextSize - 2, mMinTextSize);
                textHeight = GetTextHeight(text, textPaint, width, targetTextSize);
            }

            if(AddEllipsis && targetTextSize == mMinTextSize && textHeight > height)
            {
                TextPaint paint = new TextPaint(textPaint);

                StaticLayout layout = new StaticLayout(text, paint, width, Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
                if(layout.LineCount > 0)
                {
                    int lastLine = layout.GetLineForVertical(height) - 1;
                    if (lastLine < 0)
                        SetText("", BufferType.Normal);
                    else
                    {
                        int start = layout.GetLineStart(lastLine);
                        int end = layout.GetLineEnd(lastLine);
                        float lineWidth = layout.GetLineWidth(lastLine);
                        float ellipseWidth = textPaint.MeasureText(mEllipsis);

                        while (width < lineWidth + ellipseWidth)
                            lineWidth = textPaint.MeasureText(text.SubSequence(start, --end + 1).ToString());
                        SetText(text.SubSequence(0, end) + mEllipsis, BufferType.Normal);
                    }
                }
            }

            SetTextSize(ComplexUnitType.Px, targetTextSize);
            SetLineSpacing(mSpacingAdd, mSpacingMult);

            mTextResizeListener?.OnTextResize(this, oldTextSize, targetTextSize);

            mNeedsResize = false;
        }

        private int GetTextHeight(ICharSequence source, TextPaint paint, int width, float textSize)
        {
            TextPaint paintCopy = new TextPaint(paint);
            paintCopy.TextSize = textSize;
            StaticLayout layout = new StaticLayout(source, paintCopy, width, Layout.Alignment.AlignNormal, mSpacingMult, mSpacingAdd, false);
            return layout.Height;
        }
    }
}


问:
How to pass a function as argument for a class constructor in c++
I'm trying to implement an ordered multi map.
But I need to give a function to compare whatever the multimap contain.

Ex:

```<code>bool compare(string a, string b) { return a<b; }
bool compare2(string a, string b) { return a.size()<b.size(); }

class MultiMap
{
 private:
    toCompare( string a, string b);

 public:
    MultiMap(function) { toCompare = function };

}
</code>```

So I would like to make set the order in the multimap by a given function.

Is there a way, maybe some a pointer to a function.
Hope you understand what I want to do, if not feel free to ask.

Also, notice this is not the real code, is just something I've writen to give an idea.

答:
The easiest way is to use std::function, example:

```<code>class MultiMap
{
 private:
    std::function<bool(string,string)> toCompare;

 public:
    MultiMap(std::function<bool(string,string)> function) : toCompare(std::move(function)) {}

    bool compare(string a, string b) {
        return toCompare(a,b);
    }

};

int main(int argc, char** argv) {
 MultiMap mm(compare);
 mm.compare("asd", "Da");
}
</code>```

Or with function pointers:

```<code>// Define function type
using compare_func = bool(string,string);

class MultiMap
{
 private:
    compare_func* toCompare;
 public:
    // Constructor accepts pointer to functiontype
    MultiMap(compare_func* function) : toCompare(function) { }

    bool compare(string a, string b) {
        return toCompare(a,b);
    }

};

int main(int argc, char** argv) {
 MultiMap mm(compare);
 mm.compare("asd", "Da");
}
</code>```

Body:
I'm trying to implement an ordered multi map.
But I need to give a function to compare whatever the multimap contain.

Ex:

bool compare(string a, string b) { return a<b; }
bool compare2(string a, string b) { return a.size()<b.size(); }

class MultiMap
{
 private:
    toCompare( string a, string b);

 public:
    MultiMap(function) { toCompare = function };

}

So I would like to make set the order in the multimap by a given function.

Is there a way, maybe some a pointer to a function.
Hope you understand what I want to do, if not feel free to ask.

Also, notice this is not the real code, is just something I've writen to give an idea.

Body:
The easiest way is to use std::function, example:

class MultiMap
{
 private:
    std::function<bool(string,string)> toCompare;

 public:
    MultiMap(std::function<bool(string,string)> function) : toCompare(std::move(function)) {}

    bool compare(string a, string b) {
        return toCompare(a,b);
    }

};

int main(int argc, char** argv) {
 MultiMap mm(compare);
 mm.compare("asd", "Da");
}

Or with function pointers:

// Define function type
using compare_func = bool(string,string);

class MultiMap
{
 private:
    compare_func* toCompare;
 public:
    // Constructor accepts pointer to functiontype
    MultiMap(compare_func* function) : toCompare(function) { }

    bool compare(string a, string b) {
        return toCompare(a,b);
    }

};

int main(int argc, char** argv) {
 MultiMap mm(compare);
 mm.compare("asd", "Da");
}


问:
NameError: global name 'EventLoop' is not defined - pyglet
I am trying to have python play an audio file for me. I am writing my code in enthought canopy.

```<code>import pyglet

sound = pyglet.media.load('song.wav')
sound.play()
pyglet.app.run()
</code>```

When I run this I get an error: NameError: global name 'EventLoop' is not defined
Also, the audio file plays the first note before the program errors.

I have no idea what is going on.

p.s. Do I need the pylab backend to be interactive for pyglet?

OS - osx 10.12.1
pyglet version 1.1.4-3

Traceback

```<code>NameError                                 Traceback (most recent call last)
/Users/name/Documents/name/Arduino Projects/python/Audio Testing.py in <module>()
      3 sound = pyglet.media.load('s.wav')
      4 sound.play()
----> 5 pyglet.app.run()

/Users/name/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pyglet/app/__init__.pyc in run()
    262
    263     '''
--> 264     EventLoop().run()
    265
    266 def exit():

NameError: global name 'EventLoop' is not defined
</code>```

答:
I tried to reproduce the error but was unable to, although this library seems like it has a few other bugs too.

I did find that using the latest version of the library worked much better. My suggestion is to bump your version from 1.1.4 to 1.2.4.

```<code>pip uninstall pyglet
pip install pyglet==1.2.4
</code>```

Body:
I am trying to have python play an audio file for me. I am writing my code in enthought canopy.

import pyglet

sound = pyglet.media.load('song.wav')
sound.play()
pyglet.app.run()

When I run this I get an error: NameError: global name 'EventLoop' is not defined
Also, the audio file plays the first note before the program errors.

I have no idea what is going on.

p.s. Do I need the pylab backend to be interactive for pyglet?

OS - osx 10.12.1
pyglet version 1.1.4-3

Traceback

NameError                                 Traceback (most recent call last)
/Users/name/Documents/name/Arduino Projects/python/Audio Testing.py in <module>()
      3 sound = pyglet.media.load('s.wav')
      4 sound.play()
----> 5 pyglet.app.run()

/Users/name/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pyglet/app/__init__.pyc in run()
    262
    263     '''
--> 264     EventLoop().run()
    265
    266 def exit():

NameError: global name 'EventLoop' is not defined

Body:
I tried to reproduce the error but was unable to, although this library seems like it has a few other bugs too.

I did find that using the latest version of the library worked much better. My suggestion is to bump your version from 1.1.4 to 1.2.4.

pip uninstall pyglet
pip install pyglet==1.2.4


问:
Sprite buttons that expand when clicked in Cocos2D V3
I am trying to create a button that always uses the same sprite, and which scales up a little and back down again whenever it is tapped. Here's how I create the button:

```<code>CCSpriteFrame *sprite = [CCSpriteFrame frameWithImageNamed:@"my-sprite.png"];

CCButton *button = [CCButton buttonWithTitle:@""
                                 spriteFrame:sprite
                      highlightedSpriteFrame:sprite
                         disabledSpriteFrame:nil];

[button setTarget:self selector:@selector(onButtonPressed:)];

[self addChild:button];
</code>```

The button shows up and properly calls the selector, but it does not expand when clicked. What do I need to change in order to fix this?

答:
Use 2 images:

One for normal

Next for press (same canvas size of above but image scaled to < 100% )

Then use:

```<code>CCSpriteFrame *backButtonSprite = [CCSpriteFrame frameWithImageNamed:@"backButton.png"];
CCSpriteFrame *backButtonPressedSprite = [CCSpriteFrame
                                          frameWithImageNamed:@"backButtonPressed.png"];

CCButton *myButton = [CCButton buttonWithTitle:@""
                                    priteFrame:backButtonSprite
                        highlightedSpriteFrame:backButtonPressedSprite
                           disabledSpriteFrame:nil];

[myButton setTarget:self selector:@selector(myFunction:)];
myButton = ccp(100,100);
[self addChild:backButton];
</code>```

Keep Coding............... :)

Body:
I am trying to create a button that always uses the same sprite, and which scales up a little and back down again whenever it is tapped. Here's how I create the button:

CCSpriteFrame *sprite = [CCSpriteFrame frameWithImageNamed:@"my-sprite.png"];

CCButton *button = [CCButton buttonWithTitle:@""
                                 spriteFrame:sprite
                      highlightedSpriteFrame:sprite
                         disabledSpriteFrame:nil];

[button setTarget:self selector:@selector(onButtonPressed:)];

[self addChild:button];

The button shows up and properly calls the selector, but it does not expand when clicked. What do I need to change in order to fix this?

Body:
Use 2 images:

One for normal

Next for press (same canvas size of above but image scaled to < 100% )

Then use:

CCSpriteFrame *backButtonSprite = [CCSpriteFrame frameWithImageNamed:@"backButton.png"];
CCSpriteFrame *backButtonPressedSprite = [CCSpriteFrame
                                          frameWithImageNamed:@"backButtonPressed.png"];

CCButton *myButton = [CCButton buttonWithTitle:@""
                                    priteFrame:backButtonSprite
                        highlightedSpriteFrame:backButtonPressedSprite
                           disabledSpriteFrame:nil];

[myButton setTarget:self selector:@selector(myFunction:)];
myButton = ccp(100,100);
[self addChild:backButton];

Keep Coding............... :)


问:
Running application as windows service
I have an application that is running as window service and its running under a valid use account not under default system account ,now my worry is if in future use changes his password for that account will it effect this service??

Thanks

答:
Yes, if the password is changed for the user account, you need to update the stored password as well.
And to make this answer more programming related, this MSDN article shows you how to do it programmatically: Changing the Password on a Service's User Account</p>

Title: Running application as windows service