问:
WCF Service returns Error when invoking method from client after changing from http to https "ContractFilter mismatch at the EndpointDispatcher"
I created a HTTP wcf service that will be consumed by a windows client and utilized. I had no issue until I was using HTTP. Now my customer wants to change the site to HTTPS. So for development purpose I have used IIS express certificate and setup the service. Now my service is up and running in IIS with iisexpress self signed certificate. I am able to browse my new https service via browser as well as wcf test client tool.

But when I try invoke the method from my windows application to new https wcf service. My service instance is created but only during invoking a method I get following error:

System.ServiceModel.ActionNotSupportedException was unhandled by user code
    HResult=-2146233087
    Message=The message with Action 'http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).

In service my binding config (config 3 is being used at https mode and config 2 was used during http mode) are as follows:

```<code>    <bindings>
  <wsHttpBinding>
    <binding name="wsHttpBinding_IPGPService">
      <!--config test 1 - start -->
      <!--<security mode="None">
        <transport clientCredentialType="None" />
        <message establishSecurityContext="false" />
      </security>-->
      <!--config test 1 - end -->
      <!--config test 2 - start -->
      <!--<security mode="None" />
            <reliableSession enabled="true" />-->
      <!--config test 2 - end -->
      <!--config test 3 - start -->
      <!--<security mode="Transport">
        <transport clientCredentialType="None" proxyCredentialType="None"/>
        <message clientCredentialType="Certificate" algorithmSuite="Default" />
      </security>-->
      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>
      <!--config test 3 - end -->
    </binding>
  </wsHttpBinding>
</bindings>

<services>
  <service name="PGPService.PGPService">
    <endpoint address="" binding="wsHttpBinding" contract="PGPService.IPGPService" bindingConfiguration="wsHttpBinding_IPGPService" />
    <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
  </service>
</services>

  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <!--<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <!--<serviceDebug includeExceptionDetailInFaults="false"/>-->
      <!--test config - start-->
      <serviceDebug includeExceptionDetailInFaults="True" />
      <!--test config - end-->
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</code>```

In client we use custom binding to create service instance.

```<code>                        url = "https://localhost:550/TestService/TestService.svc";
                    customBinding = new CustomBinding();
                    customBinding.Elements.Add(new ReliableSessionBindingElement());
                    customBinding.Elements.Add(new HttpsTransportBindingElement());
                    EndpointAddress endpointAdress = new EndpointAddress(url);
                    pgpServiceClientInstance = new PGPServiceClient(customBinding, endpointAdress);
                    pgpServiceClientInstance.ClientCredentials.ClientCertificate.SetCertificate(
                        StoreLocation.CurrentUser,
                        StoreName.Root,
                        X509FindType.FindByThumbprint,
                        "03815c894b62dcf2d17336ade2d9ca61ddb7f92c");
</code>```

After adding service reference the app.config generated on my Windows application is as follows:

```<code>        <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IPGPService">
                <security mode="Transport">
                    <transport clientCredentialType="None" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="https://localhost:550/TestService/TestService.svc"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPGPService"
            contract="PGPServiceReference.IPGPService" name="WSHttpBinding_IPGPService" />
    </client>
</code>```

So now I can see my service instance is getting successfully created. but on the time of invoking a method I get above error.

There is no code changed before and after moving to https on service end. It is the same service code. It was completely working fine on http but is broken on https.

I have completely removed the service reference and added it newly after making my wcf service https. IIS express self signed certificate is installed and available already on my system. Both service and client are running in same system as of now since it is development

I am suspecting I am having a configuration problem....but with less experience I could not figure out.

答:
Actually it was an additional binding during service instantiation that was causing the problem. Got it sorted by commenting below line in instantiation part.

```<code> url = "https://localhost:550/TestService/TestService.svc";
                customBinding = new CustomBinding();
                //customBinding.Elements.Add(new ReliableSessionBindingElement());
                customBinding.Elements.Add(new HttpsTransportBindingElement());
</code>```

This helped me to proceed with developing the entire service and client.
So that concludes my fix for above issue.

Further down the lane since i am a newbie to wcf service i faced following problems which i faced and solved. Someone who is struggling like me can use below step if you are facing my errors

Next my service had problems accessing folder
Fix: add seperate application pool with an service or administrator account with enough privileges.

To add wcf session to existing code.
Fix: This is where i am facing problem because i was using wshttpbinding with transport security. Then after browsing several materials and codes understood i have to make my config to custombinding with reliablesession and httpstransport to proceed further with development. so my config roughly appears as

```<code><customBinding abc of wcf>
  <reliableSession/>
  <httpsTransport/>
<\customBinding>
</code>```

And also uncommented above line of service instantiation after understanding its real purpose.No need for any values in reliable session tag and httpsTransport for basic support of security.

This solved my second issue.

However i am facing wsdl import error in wcf client test tool now which i am struggling now to solve. svcutil proxy generation option or add service refrence with uncheked assembly option doesnt seem to be working. Also i noticed that even if add my service refrence freshly to client there is no configurations generated to my app.config file surprisingly.....and above mentioned options dont help.....looking for experts ideas....
Fix : ??? Expolring....
Souls who read this are welcome to give answer/suggestion.

Body:
I created a HTTP wcf service that will be consumed by a windows client and utilized. I had no issue until I was using HTTP. Now my customer wants to change the site to HTTPS. So for development purpose I have used IIS express certificate and setup the service. Now my service is up and running in IIS with iisexpress self signed certificate. I am able to browse my new https service via browser as well as wcf test client tool.

But when I try invoke the method from my windows application to new https wcf service. My service instance is created but only during invoking a method I get following error:

System.ServiceModel.ActionNotSupportedException was unhandled by user code
    HResult=-2146233087
    Message=The message with Action 'http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).

In service my binding config (config 3 is being used at https mode and config 2 was used during http mode) are as follows:

    <bindings>
  <wsHttpBinding>
    <binding name="wsHttpBinding_IPGPService">

      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>

    </binding>
  </wsHttpBinding>
</bindings>

<services>
  <service name="PGPService.PGPService">
    <endpoint address="" binding="wsHttpBinding" contract="PGPService.IPGPService" bindingConfiguration="wsHttpBinding_IPGPService" />
    <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
  </service>
</services>

  <serviceBehaviors>
    <behavior>

      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />

      <serviceDebug includeExceptionDetailInFaults="True" />

    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

In client we use custom binding to create service instance.

                        url = "https://localhost:550/TestService/TestService.svc";
                    customBinding = new CustomBinding();
                    customBinding.Elements.Add(new ReliableSessionBindingElement());
                    customBinding.Elements.Add(new HttpsTransportBindingElement());
                    EndpointAddress endpointAdress = new EndpointAddress(url);
                    pgpServiceClientInstance = new PGPServiceClient(customBinding, endpointAdress);
                    pgpServiceClientInstance.ClientCredentials.ClientCertificate.SetCertificate(
                        StoreLocation.CurrentUser,
                        StoreName.Root,
                        X509FindType.FindByThumbprint,
                        "03815c894b62dcf2d17336ade2d9ca61ddb7f92c");

After adding service reference the app.config generated on my Windows application is as follows:

        <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_IPGPService">
                <security mode="Transport">
                    <transport clientCredentialType="None" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="https://localhost:550/TestService/TestService.svc"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPGPService"
            contract="PGPServiceReference.IPGPService" name="WSHttpBinding_IPGPService" />
    </client>

So now I can see my service instance is getting successfully created. but on the time of invoking a method I get above error.

There is no code changed before and after moving to https on service end. It is the same service code. It was completely working fine on http but is broken on https.

I have completely removed the service reference and added it newly after making my wcf service https. IIS express self signed certificate is installed and available already on my system. Both service and client are running in same system as of now since it is development

I am suspecting I am having a configuration problem....but with less experience I could not figure out.

Body:
Actually it was an additional binding during service instantiation that was causing the problem. Got it sorted by commenting below line in instantiation part.

 url = "https://localhost:550/TestService/TestService.svc";
                customBinding = new CustomBinding();
                //customBinding.Elements.Add(new ReliableSessionBindingElement());
                customBinding.Elements.Add(new HttpsTransportBindingElement());

This helped me to proceed with developing the entire service and client.
So that concludes my fix for above issue.

Further down the lane since i am a newbie to wcf service i faced following problems which i faced and solved. Someone who is struggling like me can use below step if you are facing my errors

Next my service had problems accessing folder
Fix: add seperate application pool with an service or administrator account with enough privileges.

To add wcf session to existing code.
Fix: This is where i am facing problem because i was using wshttpbinding with transport security. Then after browsing several materials and codes understood i have to make my config to custombinding with reliablesession and httpstransport to proceed further with development. so my config roughly appears as

<customBinding abc of wcf>
  <reliableSession/>
  <httpsTransport/>
<\customBinding>

And also uncommented above line of service instantiation after understanding its real purpose.No need for any values in reliable session tag and httpsTransport for basic support of security.

This solved my second issue.

However i am facing wsdl import error in wcf client test tool now which i am struggling now to solve. svcutil proxy generation option or add service refrence with uncheked assembly option doesnt seem to be working. Also i noticed that even if add my service refrence freshly to client there is no configurations generated to my app.config file surprisingly.....and above mentioned options dont help.....looking for experts ideas....
Fix : ??? Expolring....
Souls who read this are welcome to give answer/suggestion.


来源: stackexchange

问:
*.cs.aspx cannot access *.cs files in App_Code folder
This site was developed a few years ago. it was working 100%. I am re-deploying to my pc to make some changes and testing. Now it cannot find those classes in those files. I have always used 4.5 Framework. I have searched for a solution, unfortunately those have not resolved my issue. including coping it into main directory. It worked when I copied the actual code into one of the *.cs.aspx files. However there are more then 20 pages using this email file. Any advice would be welcome. I have been scratching around for days. Thx.

===================ERROR========================>
The error is as follows:The type or namespace name 'Emailer' could not be found (are you missing a using directive or an assembly reference?)

===================ERROR-DISPLAY================>
Source Error:

Heading

答: Go to class property window by right clicking on it. Look for build option here Change your class build option to compile. </p>

ContentLicense: CC BY-SA 3.0


问:
Setting Local Notifications on a new thread?
I need to know if it is possible to create a new thread to handle setting local notifications.

My app depends heavily on these notifications, so I want to make the app work while the phone sets the notifications.

Example:

(now)

you launch the app, the app hangs at the splash screen to set the local notifications, then it launches.

(I want)

The app launches and is usable while the Local notifications are set.

I need some sample code, too, please :)

(for the record, i am setting 60 local notifications each time the app enters foreground for my own reasons...)

Thanks!!

答:
Yes this can be done, I do it all the time:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Add the navigation controller's view to the window and display.
    [NSThread detachNewThreadSelector:@selector(scheduleLocalNotifications) toTarget:self withObject:nil];
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;
}

-(void) scheduleLocalNotifications
{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    for (int i = 0; i < 60; i++)
    {
        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
        NSLog(@"Sleepdate is: %@", sleepDate);

        localNotif.fireDate = sleepDate;

        NSLog(@"fireDate is %@",localNotif.fireDate);
        localNotif.timeZone = [NSTimeZone defaultTimeZone];
        localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"This is local notification %i"), i];

        localNotif.alertAction = NSLocalizedString(@"View Details", nil);
        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 1;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
        [localNotif release];

    }

    [pool release];
}
</code>```

Taken from a project I am working on now, I can confirm that It works as expected.

EDIT:

Example was leaking in scheduleLocalNotifications because handling the NSAutoreleasePool was missing – now it's added to the example.

ContentLicense: CC BY-SA 2.5

Body:
Yes this can be done, I do it all the time:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Add the navigation controller's view to the window and display.
    [NSThread detachNewThreadSelector:@selector(scheduleLocalNotifications) toTarget:self withObject:nil];
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;
}

-(void) scheduleLocalNotifications
{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    for (int i = 0; i < 60; i++)
    {
        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
        NSLog(@"Sleepdate is: %@", sleepDate);

        localNotif.fireDate = sleepDate;

        NSLog(@"fireDate is %@",localNotif.fireDate);
        localNotif.timeZone = [NSTimeZone defaultTimeZone];
        localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"This is local notification %i"), i];

        localNotif.alertAction = NSLocalizedString(@"View Details", nil);
        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 1;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
        [localNotif release];

    }

    [pool release];
}

Taken from a project I am working on now, I can confirm that It works as expected.

EDIT:

Example was leaking in scheduleLocalNotifications because handling the NSAutoreleasePool was missing – now it's added to the example.


问:
pg_query() - "Cannot set connection to blocking mode (Error No. 8)
Our application is inserting data from CSV files to Redshift using a COPY query.  It uploads c. 700 GB in total across c. 11000 files.  Each file maps to one database table.  We run a SELECT COUNT(*) FROM
 before and after each COPY for logging and sanity checking.

After a period of time (it seems to vary) the call to pg_query() returns this E_NOTICE PHP error:

```<code>pg_query() - "Cannot set connection to blocking mode (Error No. 8)
</code>```

This is returned for the SELECT COUNT(*) FROM
 query; our application propagates all PHP Errors to Exceptions.  Removing this propagation gives us this error message in addition to the E_NOTICE above on both the SELECT and the COPY:

```<code>Failed to run query: server closed the connection unexpectedly
    This probably means the server terminated abnormally
</code>```

The COPY query definitely does not actually insert the files.

Once present, this error happens on every attempt to insert a file.  It does not seem to resolve itself.

We initially had one database connection open (opened with pg_connect()) at the start of the script and re-used it for all following SELECTs and COPYs.  When we got the E_NOTICE above we then tried - just as an experiment - opening a fresh connection for each query.  This changed nothing.

our current pgsql settings in the PHP ini file are:

```<code>pgsql.allow_persistent = Off
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
</code>```

What could be causing this error and how could it be resolved?

Update - See the attached screen.  It seems we only have the default query queue with 'concurrency' set to 5 and the timeout set to 0 MS?

Also: we only have these DB users connected while the application is running (the one with 'username_removed' is the only one that is created by our application):

```<code>main=# select * from stv_sessions;
       starttime        | process |                     user_name                      |                      db_name
------------------------+---------+----------------------------------------------------+----------------------------------------------------
 2017-03-24 10:07:49.50 |   18263 | rdsdb                                              | dev
 2017-03-24 10:08:41.50 |   18692 | rdsdb                                              | dev
 2017-03-30 10:34:49.50 |   21197 | <username_removed>                              | main
 2017-03-24 10:09:39.50 |   18985 | rdsdb                                              | dev
 2017-03-30 10:36:40.50 |   21605 | root                                               | main
 2017-03-30 10:52:13.50 |   23516 | rdsdb                                              | dev
 2017-03-30 10:56:10.50 |   23886 | root                                               | main
</code>```

答:
Have you tried to change pg_connect to pg_pconnect? This will reuse an existent connection and will decrease the connections to your database and the server will run smoothly.

I would say to never do a count using *. You are forcing the database to create a hash for each register and count it. Use some value that is unique. If you don't have it, consider create a sequence and use it in an "auto_increment" field.
I see that you work with huge files and any performance improvement will help your work

You can also check your blocking mode config.

I got this searching the web, may work for you.
"From changing pgsql.auto_reset_persistent = Off to On and restarting Apache, this resolves the error."

My last advice is about transactions, if you are using transactions you can set your count Select to ignore locked rows and it will make your count run faster.

https://www.postgresql.org/docs/9.5/static/explicit-locking.html#LOCKING-ROWS

Body:
Our application is inserting data from CSV files to Redshift using a COPY query.  It uploads c. 700 GB in total across c. 11000 files.  Each file maps to one database table.  We run a SELECT COUNT(*) FROM
 before and after each COPY for logging and sanity checking.

After a period of time (it seems to vary) the call to pg_query() returns this E_NOTICE PHP error:

pg_query() - "Cannot set connection to blocking mode (Error No. 8)

This is returned for the SELECT COUNT(*) FROM
 query; our application propagates all PHP Errors to Exceptions.  Removing this propagation gives us this error message in addition to the E_NOTICE above on both the SELECT and the COPY:

Failed to run query: server closed the connection unexpectedly
    This probably means the server terminated abnormally

The COPY query definitely does not actually insert the files.

Once present, this error happens on every attempt to insert a file.  It does not seem to resolve itself.

We initially had one database connection open (opened with pg_connect()) at the start of the script and re-used it for all following SELECTs and COPYs.  When we got the E_NOTICE above we then tried - just as an experiment - opening a fresh connection for each query.  This changed nothing.

our current pgsql settings in the PHP ini file are:

pgsql.allow_persistent = Off
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0

What could be causing this error and how could it be resolved?

Update - See the attached screen.  It seems we only have the default query queue with 'concurrency' set to 5 and the timeout set to 0 MS?

Also: we only have these DB users connected while the application is running (the one with 'username_removed' is the only one that is created by our application):

main=# select * from stv_sessions;
       starttime        | process |                     user_name                      |                      db_name
------------------------+---------+----------------------------------------------------+----------------------------------------------------
 2017-03-24 10:07:49.50 |   18263 | rdsdb                                              | dev
 2017-03-24 10:08:41.50 |   18692 | rdsdb                                              | dev
 2017-03-30 10:34:49.50 |   21197 | <username_removed>                              | main
 2017-03-24 10:09:39.50 |   18985 | rdsdb                                              | dev
 2017-03-30 10:36:40.50 |   21605 | root                                               | main
 2017-03-30 10:52:13.50 |   23516 | rdsdb                                              | dev
 2017-03-30 10:56:10.50 |   23886 | root                                               | main


问:
add images to cache in service worker
A page I want to take offline loads images dynamically. I managed to obtain a list of all images on a page. but, I can't figure out a way to pass this list to the SW. before it loads cache.

I'm newbie in Web development sorry, If this question is childish.

答:
I used global variable in the .js file where I registered the SW. I pushed all the image's addresses to this array using document.imagesand then used window.arr (arr is array) in SW.js to access them.

I knew it!. This is just a childish question but, I want to keep it because may be a newbie in asp.net and SW find it helpful. Let me know if it's not the case.

Title: add images to cache in service worker


问:
Getting Data from automatically generates WTForms from MongoEngine models
How do I get the data from a WTForms form after submitting it?

Models:

```<code>class User(db.Document):
    name = db.StringField(required=True)
UserForm = model_form(User)
</code>```

Views:

```<code>@app.route('/submit', methods=('GET', 'POST'))
def add_user():
    form = UserForm()
    if form.form.validate_on_submit():
        print(form.name.data)
return render_template('user.html', form=form)
</code>```

And here's the form HTML:

```<code><form method="POST" action="">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name(size=20) }}
    <input type="submit">
</form>
</code>```

答:
Form Validation with WTForms</p>

```<code>@app.route('/submit', methods=('GET', 'POST'))
def add_user():
    form = UserForm(request.form)
    if request.method == 'POST' and form.validate():
        print(form.name.data)
return render_template('user.html', form=form)
</code>```

Body:
How do I get the data from a WTForms form after submitting it?

Models:

class User(db.Document):
    name = db.StringField(required=True)
UserForm = model_form(User)

Views:

@app.route('/submit', methods=('GET', 'POST'))
def add_user():
    form = UserForm()
    if form.form.validate_on_submit():
        print(form.name.data)
return render_template('user.html', form=form)

And here's the form HTML:

<form method="POST" action="">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name(size=20) }}
    <input type="submit">
</form>

Body:
Form Validation with WTForms

@app.route('/submit', methods=('GET', 'POST'))
def add_user():
    form = UserForm(request.form)
    if request.method == 'POST' and form.validate():
        print(form.name.data)
return render_template('user.html', form=form)


问:
Unable to get series vale for chart-click in angular stacked bar graph
```<code> <canvas class="chart chart-bar" chart-data="data" chart-labels="labels"
                  chart-options="options" chart-series="series" chart-click="onclick"></canvas>

'use strict';

var app = angular.module('examples', ['chart.js', 'ui.bootstrap']);

app.controller('StackedBarCtrl', ['$scope', function ($scope) {
    $scope.labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    $scope.type = 'StackedBar';
    $scope.series = ['2015', '2016'];
    $scope.options = {
      scales: {
        xAxes: [{
          stacked: true,
        }],
        yAxes: [{
          stacked: true
        }]
      }
    };

    $scope.onclick = function(points,evt)
    {
        console.log("evt "+points[0]["_modal"]["datasetLabel"]);
    }

    $scope.data = [
      [65, 59, 90, 81, 56, 55, 40],
      [28, 48, 40, 19, 96, 27, 100]
    ];
}]);
</code>```

If i click on bar  28 i am not getting the value 2016, because points array in onclick function return 2 objects on for each stack and i am unable to figure out how to get value 2016 as there is no flag to indicate which bar was clicked upon

答:
The second argument passed to your onclick callback contains array of active elements and each item in it contains _datasetIndex and _index

```<code>array[1]
[Element]
    _datasetIndex:0
    _index: 0
</code>```

Using these values you can obtain the value you need

```<code>$scope.onclick = function(event, elems)
{
    var datasetIndex = elems[0]._datasetIndex;
    console.log("evt " + $scope.series[datasetIndex]);
}
</code>```

Please, refer to chartjs docs and this issue related to your problem

UPDATE

Looks like it is a little tricky with stacked bar charts. The solution is to find the closest clicked bar using Chart.helpers

```<code>$scope.$on('chart-create', function(event, instance){
  // used to obtain chart instance
  $scope.chart = instance.chart;
});
$scope.onclick = function(elements,e)
{
  // helper function that translates an event to a position in canvas coordinates
  var pos = Chart.helpers.getRelativePosition(e, $scope.chart);

  // inRange is the function on the chart element that is used for hit testing
  var intersect = elements.find(function(element) {
    return element.inRange(pos.x, pos.y);
  });
  if(intersect){
    alert('You clicked ' + $scope.labels[intersect._index] + ' ' + $scope.series[intersect._datasetIndex]);
  }
}
</code>```

Here is the working plunkr

Body:
 <canvas class="chart chart-bar" chart-data="data" chart-labels="labels"
                  chart-options="options" chart-series="series" chart-click="onclick"></canvas>

'use strict';

var app = angular.module('examples', ['chart.js', 'ui.bootstrap']);

app.controller('StackedBarCtrl', ['$scope', function ($scope) {
    $scope.labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    $scope.type = 'StackedBar';
    $scope.series = ['2015', '2016'];
    $scope.options = {
      scales: {
        xAxes: [{
          stacked: true,
        }],
        yAxes: [{
          stacked: true
        }]
      }
    };

    $scope.onclick = function(points,evt)
    {
        console.log("evt "+points[0]["_modal"]["datasetLabel"]);
    }

    $scope.data = [
      [65, 59, 90, 81, 56, 55, 40],
      [28, 48, 40, 19, 96, 27, 100]
    ];
}]);

If i click on bar  28 i am not getting the value 2016, because points array in onclick function return 2 objects on for each stack and i am unable to figure out how to get value 2016 as there is no flag to indicate which bar was clicked upon

Body:
The second argument passed to your onclick callback contains array of active elements and each item in it contains _datasetIndex and _index

array[1]
[Element]
    _datasetIndex:0
    _index: 0

Using these values you can obtain the value you need

$scope.onclick = function(event, elems)
{
    var datasetIndex = elems[0]._datasetIndex;
    console.log("evt " + $scope.series[datasetIndex]);
}

Please, refer to chartjs docs and this issue related to your problem

UPDATE

Looks like it is a little tricky with stacked bar charts. The solution is to find the closest clicked bar using Chart.helpers

$scope.$on('chart-create', function(event, instance){
  // used to obtain chart instance
  $scope.chart = instance.chart;
});
$scope.onclick = function(elements,e)
{
  // helper function that translates an event to a position in canvas coordinates
  var pos = Chart.helpers.getRelativePosition(e, $scope.chart);

  // inRange is the function on the chart element that is used for hit testing
  var intersect = elements.find(function(element) {
    return element.inRange(pos.x, pos.y);
  });
  if(intersect){
    alert('You clicked ' + $scope.labels[intersect._index] + ' ' + $scope.series[intersect._datasetIndex]);
  }
}

Here is the working plunkr


答:
Without looking at the model in depth I would say that you should try to not train the embedding and reuse one of the downloadable matrix. Even if you cut that, you still have almost 10 times as many parameters as you have data points, So the model is bound to be overfitting.

It should be the other way around. for 800k parameters you should have 8M data points.

If you look at the graph, the validation loos goes down on the first (few) epoch and then goes up which is another indication of not having enough data.

Title: How to avoid overfitting in the given Convnet

Body:
I am trying to implement a CNN network for sentence classification; I am trying to follow the architecture proposed in the paper. I am using Keras (with tensor-flow) for that. The following is the summary of my model:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_4 (InputLayer)             (None, 56)            0
____________________________________________________________________________________________________
embedding (Embedding)            (None, 56, 300)       6510000
____________________________________________________________________________________________________
dropout_7 (Dropout)              (None, 56, 300)       0
____________________________________________________________________________________________________
conv1d_10 (Conv1D)               (None, 54, 100)       90100
____________________________________________________________________________________________________
conv1d_11 (Conv1D)               (None, 53, 100)       120100
____________________________________________________________________________________________________
conv1d_12 (Conv1D)               (None, 52, 100)       150100
____________________________________________________________________________________________________
max_pooling1d_10 (MaxPooling1D)  (None, 27, 100)       0
____________________________________________________________________________________________________
max_pooling1d_11 (MaxPooling1D)  (None, 26, 100)       0
____________________________________________________________________________________________________
max_pooling1d_12 (MaxPooling1D)  (None, 26, 100)       0
____________________________________________________________________________________________________
flatten_10 (Flatten)             (None, 2700)          0
____________________________________________________________________________________________________
flatten_11 (Flatten)             (None, 2600)          0
____________________________________________________________________________________________________
flatten_12 (Flatten)             (None, 2600)          0
____________________________________________________________________________________________________
concatenate_4 (Concatenate)      (None, 7900)          0
____________________________________________________________________________________________________
dropout_8 (Dropout)              (None, 7900)          0
____________________________________________________________________________________________________
dense_7 (Dense)                  (None, 50)            395050
____________________________________________________________________________________________________
dense_8 (Dense)                  (None, 5)             255
====================================================================================================
Total params: 7,265,605.0
Trainable params: 7,265,605.0
Non-trainable params: 0.0

With the given architecture I am experiencing serious overfitting. The following are my results:

I am unable to understand what is the reason for the overfitting please suggest me some changes to the architecture for avoiding that. If you need some more information then please let me know.

Source code:

if model_type in ['CNN-non-static', 'CNN-static']:
    embedding_wts = train_word2vec( np.vstack((x_train, x_test, x_valid)),
                                    ind_to_wrd, num_features = embedding_dim)
    if model_type == 'CNN-static':
        x_train = embedding_wts[0][x_train]
        x_test  = embedding_wts[0][x_test]
        x_valid = embedding_wts[0][x_valid]

elif model_type == 'CNN-rand':
    embedding_wts = None

else:
    raise ValueError("Unknown model type")

batch_size   = 50
filter_sizes = [3,4,5]
num_filters  = 75
dropout_prob = (0.5, 0.8)
hidden_dims  = 50

l2_reg = 0.3

# Deciding dimension of input based on the model
input_shape = (max_sent_len, embedding_dim) if model_type == "CNN-static" else (max_sent_len,)
model_input = Input(shape = input_shape)

# Static model do not have embedding layer
if model_type == "CNN-static":
    z = Dropout(dropout_prob[0])(model_input)
else:
    z = Embedding(vocab_size, embedding_dim, input_length = max_sent_len, name="embedding")(model_input)
    z = Dropout(dropout_prob[0])(z)

# Convolution layers
z1 = Conv1D(    filters=num_filters, kernel_size=3,
                padding="valid", activation="relu",
                strides=1)(z)
z1 = MaxPooling1D(pool_size=2)(z1)
z1 = Flatten()(z1)

z2 = Conv1D(    filters=num_filters, kernel_size=4,
                padding="valid", activation="relu",
                strides=1)(z)
z2 = MaxPooling1D(pool_size=2)(z2)
z2 = Flatten()(z2)

z3 = Conv1D(    filters=num_filters, kernel_size=5,
                padding="valid", activation="relu",
                strides=1)(z)
z3 = MaxPooling1D(pool_size=2)(z3)
z3 = Flatten()(z3)

# Concatenate the output of all convolution layers
z = Concatenate()([z1, z2, z3])
z = Dropout(dropout_prob[1])(z)

# Dense(64, input_dim=64, kernel_regularizer=regularizers.l2(0.01), activity_regularizer=regularizers.l1(0.01))

z = Dense(hidden_dims, activation="relu", kernel_regularizer=regularizers.l2(0.01))(z)
model_output = Dense(N_category, activation="sigmoid")(z)

model = Model(model_input, model_output)
model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adadelta(lr=1, decay=0.005), metrics=["accuracy"])
model.summary()


问:
Avoiding the rounding of double numbers
I'm trying to write a function that calculates the regression line from a data sheet with the least squares methode, but I encountered some serious problem with my code.

My first issue is that I don't know why my "linear regression" function is rounding the result of the iterations, even when I'm trying to use other "bigger" types.

My second issue is that the last part of my code is giving me the wrong results for the y intercept (b) and the slope (a), and I think that it could be a problem of conversion but I'm not really sure. If it is the case what should I do to avoid it?

```<code>void RegLin (const vector<double>& valuesX, const vector<double>& valuesY, vector<double>& PenOrd) {

unsigned int N=valuesX.size();

long double SomXi{0};
    for (unsigned i=0; i<N; ++i){
    SomXi+=valuesX.at(i);
    }

long double SomXiXi{0};
    for (unsigned i=0; i<N; ++i){              //Here is a problem (number rounded) Expected value: 937352,25 / Given value: 937352
    SomXiXi+=(valuesX.at(i))*(valuesX.at(i));
    }

long double SomYi{0};
    for (unsigned i=0; i<N; ++i){
    SomYi+=valuesY.at(i);
    }

long double SomXiYi{0};
    for (unsigned i=0; i<N; ++i){              //Here is the same problem Excepted value: 334107,41 / Given value: 334107
    SomXiYi+=(valuesX.at(i))*(valuesY.at(i));
    }

long double a=(SomYi*SomXiXi-SomXi*SomXiYi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

long double b=(N*SomXiYi-SomYi*SomXi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

PenOrd.push_back(a);
PenOrd.push_back(b);

return;
}
</code>```

Thank you in advance for your support

P.S: I'm using g++ and the 2011 C++ standard.

答:
The first rule of numerical calculations with floating point says: "Work only with values of the same order".

Floating point mathematics works pretty simple in case of e.g. addition (float) :

```<code>1e6 + 1e-6 = 1000000 + 0.000001 = 1000000.000001 = 1000000 = 1e6
                                            ^
                                     precision limit
</code>```

So, as you see, result is "rounded".

Title: Avoiding the rounding of double numbers

Body:
I'm trying to write a function that calculates the regression line from a data sheet with the least squares methode, but I encountered some serious problem with my code.

My first issue is that I don't know why my "linear regression" function is rounding the result of the iterations, even when I'm trying to use other "bigger" types.

My second issue is that the last part of my code is giving me the wrong results for the y intercept (b) and the slope (a), and I think that it could be a problem of conversion but I'm not really sure. If it is the case what should I do to avoid it?

void RegLin (const vector<double>& valuesX, const vector<double>& valuesY, vector<double>& PenOrd) {

unsigned int N=valuesX.size();

long double SomXi{0};
    for (unsigned i=0; i<N; ++i){
    SomXi+=valuesX.at(i);
    }

long double SomXiXi{0};
    for (unsigned i=0; i<N; ++i){              //Here is a problem (number rounded) Expected value: 937352,25 / Given value: 937352
    SomXiXi+=(valuesX.at(i))*(valuesX.at(i));
    }

long double SomYi{0};
    for (unsigned i=0; i<N; ++i){
    SomYi+=valuesY.at(i);
    }

long double SomXiYi{0};
    for (unsigned i=0; i<N; ++i){              //Here is the same problem Excepted value: 334107,41 / Given value: 334107
    SomXiYi+=(valuesX.at(i))*(valuesY.at(i));
    }

long double a=(SomYi*SomXiXi-SomXi*SomXiYi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

long double b=(N*SomXiYi-SomYi*SomXi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

PenOrd.push_back(a);
PenOrd.push_back(b);

return;
}

Thank you in advance for your support

P.S: I'm using g++ and the 2011 C++ standard.

Body:
The first rule of numerical calculations with floating point says: "Work only with values of the same order".

Floating point mathematics works pretty simple in case of e.g. addition (float) :

1e6 + 1e-6 = 1000000 + 0.000001 = 1000000.000001 = 1000000 = 1e6
                                            ^
                                     precision limit

So, as you see, result is "rounded".


问:
Visual Studio 2012 ALT+Number Sendkeys Doesn't Work
Hello I am making a vs2012 project where when the timer reaches 10 seconds the program will send ALT+2. the F1 alone worked with sendkeys but wont work with ALT TAB or ALT+Number. Here are some codes i tried so far that doesn't work.

```<code>    If mintCount = 16 Then SendKeys.Send("%2")
    If mintCount = 16 Then SendKeys.Send("%(2)")
    If mintCount = 16 Then SendKeys.Send("(%2)")
    If mintCount = 16 Then SendKeys.Send("%{2}")
    If mintCount = 16 Then SendKeys.Send("%{TAB}")
</code>```

any suggestion or tip would be appreciated thank you so much..

答:
use keyboard.sendkeys instead:

My.Computer.Keyboard.SendKeys("%{TAB}", True)

this should send alt tab to the active window and the boolean specifies whether to pause the application till the keystrokes have been processed or not.

Body:
Hello I am making a vs2012 project where when the timer reaches 10 seconds the program will send ALT+2. the F1 alone worked with sendkeys but wont work with ALT TAB or ALT+Number. Here are some codes i tried so far that doesn't work.

    If mintCount = 16 Then SendKeys.Send("%2")
    If mintCount = 16 Then SendKeys.Send("%(2)")
    If mintCount = 16 Then SendKeys.Send("(%2)")
    If mintCount = 16 Then SendKeys.Send("%{2}")
    If mintCount = 16 Then SendKeys.Send("%{TAB}")

any suggestion or tip would be appreciated thank you so much..


问:
Turn multiple folders with Java code into runnable jar file
I have some Java code on my machine that I run from the command line. I want to create a runnable .jar file from this code so that I can distribute my application more easily.

The code is in four folders, called fol_a, fol_b, fol_c, and fol_d. Each of these contains a /bin subfolder, containing the .class files, and two of them (fol_a and fol_b) also contain a /lib folder, containing some .jar files that the code needs.

fol_d contains the class to run, Demo, which is in a package called machineLearning. The full path to the class is

```<code>fol_d/bin/machineLearning/Demo
</code>```

I currently run the code from the command line as follows:

```<code>$ cd fol_d/bin
$ java -cp ".:../../fol_a/bin:../../fol_a/lib/*:../../fol_b/bin:../../fol_b/lib/*:../../fol_c/bin" machineLearning.Demo <param_1> <param_2> ... <param_5>
</code>```

where <param_1> to <param_5> are the arguments given to the Main method in Demo.

What I want is to create one single .jar file that contains all the code that is necessary to execute Demo successfully, i.e., the code in fol_a through fol_d. I then want to be able to run this .jar file from the command line, giving it the arguments that go to the Main method in Demo. Something like this:

```<code>$ java -jar MyApplication.jar <param_1> ... <param_5>
</code>```

Is this possible? How would I do this? I've been trying to find an answer online, but the amount of information confuses me.

UPDATE

Right! So it seems that all I needed to do was this:

copy the contents of the bin directories to a new dir myapp

make a manifest.txt file that specifies the main class to run, as well as the classpath

jar myapp: $ jar cmf manifest.txt myapp.jar -C myapp/ .

execute the jar: $ java -jar myapp.jar <arg_1> <arg_2> ... <arg_n>

答:
Yes it is possible.

Use "cp -R" to copy all 4 folders' bin directories into one directory ... preserving the subdirectory structures.  (Read man cp if you don't understand how.  Install the manual entries if they are not installed.)

Use the jar command to create the JAR file from the consolidated directory.

UPDATE

When you create the JAR file, the paths within the JAR (i.e. in the JAR file index) must match the respective classes fully qualified names.

If you are creating an executable JAR, the Main Class attribute must specify the fully qualified class name.

If you misname the JAR file entries then either java won't find the classes, or it will refuse to load them because the pathname and classname don't match.

These requirements apply for all JARs, but from your comments it seems that you have overlooked this.

In your comment, you seem to have used the wrong classname in the Main Class attribute ... unless you declared the class in the fol_d.bin package!

UPDATE 2

Here is an example to illustrate my point about fully qualified classnames

```<code>package foo.bar;

public class Main {
   ...
}
</code>```

The simple class name is Main.  The fully qualified classname is foo.bar.Main.  If you put the ".class" file for this class into a JAR, the pathname in the JAR file for the class must be:

```<code>/foo/bar/Main.class
</code>```

The package name (foo.bar) maps to the directory path in the JAR file index; i.e. "/foo/bar".

If the pathname in the JAR file isn't that, then the classloader won't find it.

Body:
I have some Java code on my machine that I run from the command line. I want to create a runnable .jar file from this code so that I can distribute my application more easily.

The code is in four folders, called fol_a, fol_b, fol_c, and fol_d. Each of these contains a /bin subfolder, containing the .class files, and two of them (fol_a and fol_b) also contain a /lib folder, containing some .jar files that the code needs.

fol_d contains the class to run, Demo, which is in a package called machineLearning. The full path to the class is

fol_d/bin/machineLearning/Demo

I currently run the code from the command line as follows:

$ cd fol_d/bin
$ java -cp ".:../../fol_a/bin:../../fol_a/lib/*:../../fol_b/bin:../../fol_b/lib/*:../../fol_c/bin" machineLearning.Demo <param_1> <param_2> ... <param_5>

where <param_1> to <param_5> are the arguments given to the Main method in Demo.

What I want is to create one single .jar file that contains all the code that is necessary to execute Demo successfully, i.e., the code in fol_a through fol_d. I then want to be able to run this .jar file from the command line, giving it the arguments that go to the Main method in Demo. Something like this:

$ java -jar MyApplication.jar <param_1> ... <param_5>

Is this possible? How would I do this? I've been trying to find an answer online, but the amount of information confuses me.

UPDATE

Right! So it seems that all I needed to do was this:

copy the contents of the bin directories to a new dir myapp

make a manifest.txt file that specifies the main class to run, as well as the classpath

jar myapp: $ jar cmf manifest.txt myapp.jar -C myapp/ .

execute the jar: $ java -jar myapp.jar <arg_1> <arg_2> ... <arg_n>

Body:
Yes it is possible.

Use "cp -R" to copy all 4 folders' bin directories into one directory ... preserving the subdirectory structures.  (Read man cp if you don't understand how.  Install the manual entries if they are not installed.)

Use the jar command to create the JAR file from the consolidated directory.

UPDATE

When you create the JAR file, the paths within the JAR (i.e. in the JAR file index) must match the respective classes fully qualified names.

If you are creating an executable JAR, the Main Class attribute must specify the fully qualified class name.

If you misname the JAR file entries then either java won't find the classes, or it will refuse to load them because the pathname and classname don't match.

These requirements apply for all JARs, but from your comments it seems that you have overlooked this.

In your comment, you seem to have used the wrong classname in the Main Class attribute ... unless you declared the class in the fol_d.bin package!

UPDATE 2

Here is an example to illustrate my point about fully qualified classnames

package foo.bar;

public class Main {
   ...
}

The simple class name is Main.  The fully qualified classname is foo.bar.Main.  If you put the ".class" file for this class into a JAR, the pathname in the JAR file for the class must be:

/foo/bar/Main.class

The package name (foo.bar) maps to the directory path in the JAR file index; i.e. "/foo/bar".

If the pathname in the JAR file isn't that, then the classloader won't find it.


问:
send data from js function to a modal in the same file
I have 3 variables declared in a js function and i want to send them to my modal to display their data

js:

```<code> function consulter_salle(id)
        {
               $.ajax({
                url : "<?php echo site_url('index.php/batiment/list_salle')?>/"+id,
                type: "POST",
                dataType: "JSON",
                success: function(data)
                {
                   var table_header = "<table>";
                   var table_footer = "</table>";
                var html ="";

                for (var row in data)
                {
                    html += "<tr><td>"+ data.id+"</td><td>"+data.libelle +"</td></tr>";
                }

       $('#modal_list').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Test');

                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error displaying data');
                }
            });

        }
</code>```

my modal :

```<code><div class="modal fade" id="modal_list" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h3 class="modal-title">Liste des salles</h3>
          </div>
          <div class="modal-body form">
            <form action="#" id="form" class="form-horizontal">

              <div class="form-body">

                     </form>
              </div>
              <div class="modal-footer">
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
              </div>
            </div><!-- /.modal-content -->
          </div><!-- /.modal-dialog -->
        </div>
      </body>
    </html>
</code>```

the data is a list that i sent it by my controller,and it been verified that the data is recieved , but i can't find a way to send it to the modal.
I wonder what to write in the modal-body section!
Thank you .

答:
Here is working example.

 // Example result, JS Object
 var result = {
  id: 12,
  title: 'My title',
  content: '
My example content
'

 }

 // your ajax success method
 function ajaxSuccess(result) {
  var modal = $('#modal_list');
  modal.modal('show');

  modal.find('.modal-title').html(result.title);
  modal.find('.modal-body').html(result.content);
 }

 ajaxSuccess(result);
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="modal fade" id="modal_list" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h3 class="modal-title">Liste des salles</h3>
            </div>
            <div class="modal-body form">
                <form action="#" id="form" class="form-horizontal">

                    <div class="form-body">

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
            </div>
        </div>
            <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div></code>```

Body:
I have 3 variables declared in a js function and i want to send them to my modal to display their data

js:

 function consulter_salle(id)
        {
               $.ajax({
                url : "<?php echo site_url('index.php/batiment/list_salle')?>/"+id,
                type: "POST",
                dataType: "JSON",
                success: function(data)
                {
                   var table_header = "
";
                   var table_footer = "
";
                var html ="";

                for (var row in data)
                {
                    html += "
"+ data.id+"	"+data.libelle +"
";
                }

       $('#modal_list').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Test');

                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error displaying data');
                }
            });

        }

my modal :

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

Liste des salles

            <form action="#" id="form" class="form-horizontal">

                     </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

the data is a list that i sent it by my controller,and it been verified that the data is recieved , but i can't find a way to send it to the modal.
I wonder what to write in the modal-body section!
Thank you .

Body:
Here is working example.

 // Example result, JS Object
 var result = {
  id: 12,
  title: 'My title',
  content: '<div>My example content</div>'

 }

 // your ajax success method
 function ajaxSuccess(result) {
  var modal = $('#modal_list');
  modal.modal('show');

  modal.find('.modal-title').html(result.title);
  modal.find('.modal-body').html(result.content);
 }

 ajaxSuccess(result);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="modal fade" id="modal_list" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h3 class="modal-title">Liste des salles</h3>
            </div>
            <div class="modal-body form">
                <form action="#" id="form" class="form-horizontal">

                    <div class="form-body">

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
            </div>
        </div>
            <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>


问:
Android Studio stuck on gradle resolving dependencies
I'm new to Android Studio and while creating a new project it stuck at resolving dependencies :app:_debugCompile.

I waited for sometime and even tried to create a new project, but that didn't work. Here's a screenshot of the window:

Here's the contents of build.gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

答:
Check Your gradle.properties file it might be having some system Properties enables. Remove them, you may don't need them

```<code>-systemProp.http.proxyPassword=password
-systemProp.http.proxyHost=172.18.**.**
-systemProp.http.proxyUser=user.name
-systemProp.http.proxyPort=80
</code>```

Invalidate cache and restart Android studio.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Android Studio and while creating a new project it stuck at resolving dependencies :app:_debugCompile.

I waited for sometime and even tried to create a new project, but that didn't work. Here's a screenshot of the window:

Here's the contents of build.gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Body:
Check Your gradle.properties file it might be having some system Properties enables. Remove them, you may don't need them

-systemProp.http.proxyPassword=password
-systemProp.http.proxyHost=172.18.**.**
-systemProp.http.proxyUser=user.name
-systemProp.http.proxyPort=80

Invalidate cache and restart Android studio.


问:
How to compile (make) in a directory with a hashtag in its name?
(TL;DR at the bottom)

I have a c++ project which I am able to compile successfully using

```<code>mkdir build && cd build
cmake ..
make
</code>```

However, because I didn't want my cloud-synchronization program to sync this, I named this folder not build, but _#build instead. this caused make to output this:

```<code>/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file make: ***
[Makefile:190: cmake_check_build_system] Error 1
</code>```

After experimenting around with different names for the build folder - `~build~ seems to work for example - I noticed that cmake's output differs by one line when the dirname contains a hashtag (#) sign.

-- Detecting CXX compile features - failed

Without the hashtag, it says "done" instead of "failed".

For this specific case, I just told my sync tool to also ignore directories that are named "build" and just used the dirname "build", but I am still wondering how I could workaround this if I wanted to keep the hashtag in the name. This is my question: How could I run make successfully within a directory that contains # in its name?

Please note that this happened on cygwin and I am not sure whether this would also happen on a native bash shell.

First Edit

As suggested by Patrick Kelly, I tried to replace all occurences in the paths within the Makefile from _#build to _\#build. I did so manually, and after making sure there were no other occurences also using sed.
This did not work when I then tried to run make, so I tried to just replace every occurence of _#build in any file in any subfolder - I figure there won't be any occurences outside of paths. Just to make sure there's nothing left unchanged. So what I did was:

$ grep --null -l '_#build' -r . | xargs -0 sed -i 's/_#build/_\\#build/g'

I don't really understand why I had to escape the backslash, I thought single quotes didn't evaluate it. But anyways, this also didn't work. Short explanation of this command: grep lists all filenames (-l) of the found occurrences in any subfolder (-r) and separates them with nullcharacteres (--null) such that xargs applies sed to all of these files. the sed command itself does the replacement for all occurences in a file.

The problem now:

```<code>make

Call Stack (most recent call first):
  /usr/share/cmake-3.6.2/Modules/CMakeSystemSpecificInformation.cmake:36 (include)
  CMakeLists.txt:5 (PROJECT)

-- Configuring incomplete, errors occurred!
See also "/cygdrive/c/Users/myUser/Documents/temp/_#build/CMakeFiles/CMakeOutput.log".
See also "/cygdrive/c/Users/myUser/Documents/temp/_#build/CMakeFiles/CMakeError.log".
make: *** [Makefile:190: cmake_check_build_system] Error 1
</code>```

And CMakeError.log contains for "Run Build Command" and for "Detecting CXX [-std=c++14] compiler features ..." the following (not pasting the whole thing).
Detecting CXX [-std=c++14] compiler features failed to compile with the following output:

```<code>Change Dir: /cygdrive/c/Users/myUser/Documents/temp/_\#build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make.exe" "cmTC_1dcec/fast"
/usr/bin/make -f CMakeFiles/cmTC_1dcec.dir/build.make CMakeFiles/cmTC_1dcec.dir/build
make[1]: Entering directory '/cygdrive/c/Users/myUser/Documents/temp/_\#build/CMakeFiles/CMakeTmp'
make[1]: *** No rule to make target '/cygdrive/c/Users/myUser/Documents/temp/_', needed by 'CMakeFiles/cmTC_1dcec.dir/feature_tests.cxx.o'.  Stop.
</code>```

So apparently, I inserted the backslash at too many places, huh?
The simple solution: I didn't need to change all occurences in my Makefile. What I had to replace:

```<code>CMAKE_BINARY_DIR = "/cygdrive/c/Users/myUser/Documents/temp/_\#build"
</code>```

What I had to leave as it was:

```<code>all: cmake_check_build_system
    $(CMAKE_COMMAND) -E cmake_progress_start "/cygdrive/c/Users/myUser/Documents/temp/t/_#build/CMakeFiles" "/cygdrive/c/Users/myUser/Documents/temp/t/_#build/CMakeFiles/progress.marks"
    $(MAKE) -f CMakeFiles/Makefile2 all
    $(CMAKE_COMMAND) -E cmake_progress_start "/cygdrive/c/Users/Eric/Documents/temp/t/_#build/CMakeFiles" 0
</code>```

Also, no need to change any other files than the Makefile.

TL;DR

Only change the line with CMAKE_BINARY_DIR to CMAKE_BINARY_DIR =
  "/cygdrive/c/Users/myUser/Documents/temp/_\#build"

Because the path I needed to replace was the first occurrence in the Makefile, the following bash command did the trick for me to automatize it.

```<code>sed -i 's/_#build/_\\#build/' Makefile
</code>```

答:
The problem is the fact that make uses the # sign for comments.  When cmake creates your Makefile, one of the lines generated will set the build directory for you.  Something like this:

```<code>CMAKE_BINARY_DIR = "/home/Patrick/TEMP/_#build"
</code>```

But since the # sign is for comments, and make does not use all of the same escape rules that your shell does, it ignores the build" part of that line.  This creates an non-terminated string. There is no CMake mechanism that will let you fix this automatically.  The user cannot override the definition for CMAKE_BINARY_DIR from the CMakeLists.txt file. That's a special variable that cmake generates and manages. So the only way to make this work is to manually edit Makefile after you run cmake, and add an escape character before the # sign:

```<code>CMAKE_BINARY_DIR = "/home/Patrick/TEMP/_\#build"
</code>```

If you're willing to manually edit after the cmake command, you can make it work.  Or if you're really motivated, you could write your own shell script to make that change to Makefile for you, and run the command after cmake.  Something like:

```<code>mkdir _#build && cd _#build
cmake ..
fix_makefile.sh
make
</code>```

Body:
(TL;DR at the bottom)

I have a c++ project which I am able to compile successfully using

mkdir build && cd build
cmake ..
make

However, because I didn't want my cloud-synchronization program to sync this, I named this folder not build, but _#build instead. this caused make to output this:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file make: ***
[Makefile:190: cmake_check_build_system] Error 1

After experimenting around with different names for the build folder - `~build~ seems to work for example - I noticed that cmake's output differs by one line when the dirname contains a hashtag (#) sign.

-- Detecting CXX compile features - failed

Without the hashtag, it says "done" instead of "failed".

For this specific case, I just told my sync tool to also ignore directories that are named "build" and just used the dirname "build", but I am still wondering how I could workaround this if I wanted to keep the hashtag in the name. This is my question: How could I run make successfully within a directory that contains # in its name?

Please note that this happened on cygwin and I am not sure whether this would also happen on a native bash shell.

First Edit

As suggested by Patrick Kelly, I tried to replace all occurences in the paths within the Makefile from _#build to _\#build. I did so manually, and after making sure there were no other occurences also using sed.
This did not work when I then tried to run make, so I tried to just replace every occurence of _#build in any file in any subfolder - I figure there won't be any occurences outside of paths. Just to make sure there's nothing left unchanged. So what I did was:

$ grep --null -l '_#build' -r . | xargs -0 sed -i 's/_#build/_\\#build/g'

I don't really understand why I had to escape the backslash, I thought single quotes didn't evaluate it. But anyways, this also didn't work. Short explanation of this command: grep lists all filenames (-l) of the found occurrences in any subfolder (-r) and separates them with nullcharacteres (--null) such that xargs applies sed to all of these files. the sed command itself does the replacement for all occurences in a file.

The problem now:

make

Call Stack (most recent call first):
  /usr/share/cmake-3.6.2/Modules/CMakeSystemSpecificInformation.cmake:36 (include)
  CMakeLists.txt:5 (PROJECT)

-- Configuring incomplete, errors occurred!
See also "/cygdrive/c/Users/myUser/Documents/temp/_#build/CMakeFiles/CMakeOutput.log".
See also "/cygdrive/c/Users/myUser/Documents/temp/_#build/CMakeFiles/CMakeError.log".
make: *** [Makefile:190: cmake_check_build_system] Error 1

And CMakeError.log contains for "Run Build Command" and for "Detecting CXX [-std=c++14] compiler features ..." the following (not pasting the whole thing).
Detecting CXX [-std=c++14] compiler features failed to compile with the following output:

Change Dir: /cygdrive/c/Users/myUser/Documents/temp/_\#build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make.exe" "cmTC_1dcec/fast"
/usr/bin/make -f CMakeFiles/cmTC_1dcec.dir/build.make CMakeFiles/cmTC_1dcec.dir/build
make[1]: Entering directory '/cygdrive/c/Users/myUser/Documents/temp/_\#build/CMakeFiles/CMakeTmp'
make[1]: *** No rule to make target '/cygdrive/c/Users/myUser/Documents/temp/_', needed by 'CMakeFiles/cmTC_1dcec.dir/feature_tests.cxx.o'.  Stop.

So apparently, I inserted the backslash at too many places, huh?
The simple solution: I didn't need to change all occurences in my Makefile. What I had to replace:

CMAKE_BINARY_DIR = "/cygdrive/c/Users/myUser/Documents/temp/_\#build"

What I had to leave as it was:

all: cmake_check_build_system
    $(CMAKE_COMMAND) -E cmake_progress_start "/cygdrive/c/Users/myUser/Documents/temp/t/_#build/CMakeFiles" "/cygdrive/c/Users/myUser/Documents/temp/t/_#build/CMakeFiles/progress.marks"
    $(MAKE) -f CMakeFiles/Makefile2 all
    $(CMAKE_COMMAND) -E cmake_progress_start "/cygdrive/c/Users/Eric/Documents/temp/t/_#build/CMakeFiles" 0

Also, no need to change any other files than the Makefile.

TL;DR

Only change the line with CMAKE_BINARY_DIR to CMAKE_BINARY_DIR =
  "/cygdrive/c/Users/myUser/Documents/temp/_\#build"

Because the path I needed to replace was the first occurrence in the Makefile, the following bash command did the trick for me to automatize it.

sed -i 's/_#build/_\\#build/' Makefile

Body:
The problem is the fact that make uses the # sign for comments.  When cmake creates your Makefile, one of the lines generated will set the build directory for you.  Something like this:

CMAKE_BINARY_DIR = "/home/Patrick/TEMP/_#build"

But since the # sign is for comments, and make does not use all of the same escape rules that your shell does, it ignores the build" part of that line.  This creates an non-terminated string. There is no CMake mechanism that will let you fix this automatically.  The user cannot override the definition for CMAKE_BINARY_DIR from the CMakeLists.txt file. That's a special variable that cmake generates and manages. So the only way to make this work is to manually edit Makefile after you run cmake, and add an escape character before the # sign:

CMAKE_BINARY_DIR = "/home/Patrick/TEMP/_\#build"

If you're willing to manually edit after the cmake command, you can make it work.  Or if you're really motivated, you could write your own shell script to make that change to Makefile for you, and run the command after cmake.  Something like:

mkdir _#build && cd _#build
cmake ..
fix_makefile.sh
make


问:
AsyncCalls AsyncCallEx E2036 Variable required
Delphi 10.1 Berlin

I am unable to understood why I am getting error.

I get the error message when compile this (while TestRec is simple function - all is ok):

```<code>type
  TData = record
    Value: string;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    function TestRec(var Data: TData): Integer;
  end;

...

function TForm1.TestRec(var Data: TData): Integer;
begin
  Data.Value := 'TestOut';

  Result := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  MyData: TData;

  a: IAsyncCall;
begin
  MyData.Value := 'TestIn';

  a := AsyncCallEx(@TestRec, MyData); //[dcc32 Error] Unit1.pas(47): E2036 Variable required
end;
</code>```

Error Shown:
[dcc32 Error] Unit1.pas(47): E2036 Variable required

答:
Correct example code, thahk to @LU RD:</p>

```<code>type
  TData = record
    Value: string;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    MyData: TData; //Global variable

    procedure {function} TestRec(var Data){: Integer}; //procedure or function
  end;

...

uses AsyncCalls;

...

procedure {function} TForm1.TestRec(var Data){: Integer}; //untyped parameters
begin
  TData(Data).Value := 'TestOut'; //cast to type

  //Result := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  a: IAsyncCall;
begin
  MyData.Value := 'TestIn';

  a := AsyncCallEx(TestRec, MyData); //without @ !!!
end;
</code>```

Body:
Delphi 10.1 Berlin

I am unable to understood why I am getting error.

I get the error message when compile this (while TestRec is simple function - all is ok):

type
  TData = record
    Value: string;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    function TestRec(var Data: TData): Integer;
  end;

...

function TForm1.TestRec(var Data: TData): Integer;
begin
  Data.Value := 'TestOut';

  Result := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  MyData: TData;

  a: IAsyncCall;
begin
  MyData.Value := 'TestIn';

  a := AsyncCallEx(@TestRec, MyData); //[dcc32 Error] Unit1.pas(47): E2036 Variable required
end;

Error Shown:
[dcc32 Error] Unit1.pas(47): E2036 Variable required

Body:
Correct example code, thahk to @LU RD:

type
  TData = record
    Value: string;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    MyData: TData; //Global variable

    procedure {function} TestRec(var Data){: Integer}; //procedure or function
  end;

...

uses AsyncCalls;

...

procedure {function} TForm1.TestRec(var Data){: Integer}; //untyped parameters
begin
  TData(Data).Value := 'TestOut'; //cast to type

  //Result := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  a: IAsyncCall;
begin
  MyData.Value := 'TestIn';

  a := AsyncCallEx(TestRec, MyData); //without @ !!!
end;


问:
Differences btw Gtk.Table and Gtk.Grid
Althought Gtk.table is deprecated, I am getting better results with it, instead of the recommended Gtk.Grid.

It is probably my mistake, but I couldn't find the problem.

My aim is to create a Gtk window with a notebook at the top and two buttons below. These buttons should be horizontally aligned.

My code with table, works as expected:

uses Gtk

class TestWindow : Window
    init
        // General characteristics of the window
        title = "Gtk Containers"
        default_height = 250
        default_width = 250
        window_position = WindowPosition.CENTER
        destroy.connect(Gtk.main_quit)

        // Now building the notebook
        var notebook = new Gtk.Notebook()
        var label1 = new Gtk.Label("Page one")
        var label2 = new Gtk.Label("Page two")
        var child1 = new Gtk.Label("Go to page 2 for the answer")
        var child2 = new Gtk.Label("Go to page 1 for the answer")
        notebook.append_page(child1, label1)
        notebook.append_page(child2, label2)

        // Now building the table
        var table = new Table(2,2,true)
        var button1 = new Gtk.Button.with_mnemonic("Button_1")
        var button2 = new Button.with_mnemonic("Button_2")

        // Attaching all elements into the table
        table.attach_defaults(notebook, 0,2,0,1)
        table.attach_defaults(button1, 0,1,1,2)
        table.attach_defaults(button2, 1,2,1,2)
        add(table)

init
    Gtk.init (ref args)
    var test = new TestWindow ()
    test.show_all ()
    Gtk.main ()
```
<p>However, the same code with the recommended Gtk.Grid gives me the two buttons without the notebook:</p>
<pre class="lang-py prettyprint-override"><code>uses Gtk

class TestWindow : Window
    init
        // General characteristics of the window
        title = "Gtk Containers"
        default_height = 250
        default_width = 250
        window_position = WindowPosition.CENTER
        destroy.connect(Gtk.main_quit)

        // Now building the notebook
        var notebook = new Gtk.Notebook()
        var label1 = new Gtk.Label("Page one")
        var label2 = new Gtk.Label("Page two")
        var child1 = new Gtk.Label("Go to page 2 for the answer")
        var child2 = new Gtk.Label("Go to page 1 for the answer")
        notebook.append_page(child1, label1)
        notebook.append_page(child2, label2)

        // Now building the grid
        var grid = new Grid()
        var button1 = new Gtk.Button.with_mnemonic("Button_1")
        var button2 = new Button.with_mnemonic("Button_2")

        // Attaching all elements into the grid
        grid.attach(notebook, 0,2,0,1)
        grid.attach(button1, 0,1,1,2)
        grid.attach(button2, 1,2,1,2)

init
    Gtk.init (ref args)
    var test = new TestWindow ()
    test.show_all ()
    Gtk.main ()
</code>```

How to achieve the aim using Grid instead of Tables? Not asking for code, just a pointer.

答:
andlabs's explanation is correct, although his conversion adding 1 to grid.attach right and bottom values didn't work well to me. As I had to convert many of these values, I've prepared a python script to ease this process, HTH:

import sys

if len(sys.argv) < 2: raise Exception('Argument not provided')

args = ''.join([str(x) for x in sys.argv[1:]]).split(',')

if len(args) != 4: raise Exception('Please provide 4 attach arguments')

left, right, top, bottom = map(lambda a: int(a), args)
print("{}, {}, {}, {}".format(left, top, right - left, bottom - top))
```

Title: Differences btw Gtk.Table and Gtk.Grid

Body:
Althought Gtk.table is deprecated, I am getting better results with it, instead of the recommended Gtk.Grid.

It is probably my mistake, but I couldn't find the problem.

My aim is to create a Gtk window with a notebook at the top and two buttons below. These buttons should be horizontally aligned.

My code with table, works as expected:

uses Gtk

class TestWindow : Window
    init
        // General characteristics of the window
        title = "Gtk Containers"
        default_height = 250
        default_width = 250
        window_position = WindowPosition.CENTER
        destroy.connect(Gtk.main_quit)

        // Now building the notebook
        var notebook = new Gtk.Notebook()
        var label1 = new Gtk.Label("Page one")
        var label2 = new Gtk.Label("Page two")
        var child1 = new Gtk.Label("Go to page 2 for the answer")
        var child2 = new Gtk.Label("Go to page 1 for the answer")
        notebook.append_page(child1, label1)
        notebook.append_page(child2, label2)

        // Now building the table
        var table = new Table(2,2,true)
        var button1 = new Gtk.Button.with_mnemonic("Button_1")
        var button2 = new Button.with_mnemonic("Button_2")

        // Attaching all elements into the table
        table.attach_defaults(notebook, 0,2,0,1)
        table.attach_defaults(button1, 0,1,1,2)
        table.attach_defaults(button2, 1,2,1,2)
        add(table)

init
    Gtk.init (ref args)
    var test = new TestWindow ()
    test.show_all ()
    Gtk.main ()

However, the same code with the recommended Gtk.Grid gives me the two buttons without the notebook:

uses Gtk

class TestWindow : Window
    init
        // General characteristics of the window
        title = "Gtk Containers"
        default_height = 250
        default_width = 250
        window_position = WindowPosition.CENTER
        destroy.connect(Gtk.main_quit)

        // Now building the notebook
        var notebook = new Gtk.Notebook()
        var label1 = new Gtk.Label("Page one")
        var label2 = new Gtk.Label("Page two")
        var child1 = new Gtk.Label("Go to page 2 for the answer")
        var child2 = new Gtk.Label("Go to page 1 for the answer")
        notebook.append_page(child1, label1)
        notebook.append_page(child2, label2)

        // Now building the grid
        var grid = new Grid()
        var button1 = new Gtk.Button.with_mnemonic("Button_1")
        var button2 = new Button.with_mnemonic("Button_2")

        // Attaching all elements into the grid
        grid.attach(notebook, 0,2,0,1)
        grid.attach(button1, 0,1,1,2)
        grid.attach(button2, 1,2,1,2)

init
    Gtk.init (ref args)
    var test = new TestWindow ()
    test.show_all ()
    Gtk.main ()

How to achieve the aim using Grid instead of Tables? Not asking for code, just a pointer.


问:
How to stop a self hosted Kestrel application?
I have the canonical code to self host an asp.net mvc application, inside a task:

```<code>            Task hostingtask = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("hosting ffoqsi");
                IWebHost host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseApplicationInsights()
                    .Build();

                host.Run();
            }, canceltoken);
</code>```

When I cancel this task, an ObjectDisposedException throws. How can I gracefully shut down the host?

答:
Found the most obvious way to cancel Kestrel. Run has an overload accepting a cancellation Token.

```<code>  public static class WebHostExtensions
  {
    /// <summary>
    /// Runs a web application and block the calling thread until host shutdown.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    public static void Run(this IWebHost host);
    /// <summary>
    /// Runs a web application and block the calling thread until token is triggered or shutdown is triggered.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    /// <param name="token">The token to trigger shutdown.</param>
    public static void RunAsync(this IWebHost host, CancellationToken token);
  }
</code>```

So passing the cancellation token to

```<code>host.Run(ct);
</code>```

solves it.

Body:
I have the canonical code to self host an asp.net mvc application, inside a task:

            Task hostingtask = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("hosting ffoqsi");
                IWebHost host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseApplicationInsights()
                    .Build();

                host.Run();
            }, canceltoken);

When I cancel this task, an ObjectDisposedException throws. How can I gracefully shut down the host?

Body:
Found the most obvious way to cancel Kestrel. Run has an overload accepting a cancellation Token.

  public static class WebHostExtensions
  {
    /// <summary>
    /// Runs a web application and block the calling thread until host shutdown.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    public static void Run(this IWebHost host);
    /// <summary>
    /// Runs a web application and block the calling thread until token is triggered or shutdown is triggered.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    /// <param name="token">The token to trigger shutdown.</param>
    public static void RunAsync(this IWebHost host, CancellationToken token);
  }

So passing the cancellation token to

host.Run(ct);

solves it.


问:
android list view clickable problem
i have this customized list. each row contains an image and two lines of text one below the other. i want to open a new activity when any list item is clicked. but i am not able to do so, even after implementing the setOnItemClickListener(). please correct me if i am wrong. the below is the code for the list.
PS: This is an normal activity and not list activity.</p>

```<code>l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));
   //l1 = getListView();
   l1.setClickable(true);
   l1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1,
      int position, long arg3) {
     Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
     Bundle b = new Bundle();
     b.putString("event", eventTitleArray[position]);
     intent.putExtras(bundle);
     startActivity(intent);

     Toast.makeText(getApplicationContext(), "Opening detailed view for:"+eventTitleArray[position], Toast.LENGTH_SHORT).show();

    }
   });
</code>```

答:
I think there is a bug in the SDK that prevents the onItemClickListeners from firing when there are focusable views in the View of your items.

So you should try to do a setFocusable(false) on all the Views of your items.

The problem is described here

Title: android list view clickable problem

Body:
i have this customized list. each row contains an image and two lines of text one below the other. i want to open a new activity when any list item is clicked. but i am not able to do so, even after implementing the setOnItemClickListener(). please correct me if i am wrong. the below is the code for the list.
PS: This is an normal activity and not list activity.

l1.setAdapter(new EfficientAdapter(this,eventTitleArray,eventDateArray,eventImageLinkArray));
   //l1 = getListView();
   l1.setClickable(true);
   l1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1,
      int position, long arg3) {
     Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
     Bundle b = new Bundle();
     b.putString("event", eventTitleArray[position]);
     intent.putExtras(bundle);
     startActivity(intent);

     Toast.makeText(getApplicationContext(), "Opening detailed view for:"+eventTitleArray[position], Toast.LENGTH_SHORT).show();

    }
   });


问:
vb.net: can't store multiple urls in different buttons using a function
so basically that's a browser code, I'm facing a problem when trying to save links of favorite sites in a favorite button. Problem is When i Click the button btnFav1 or btnFav2, type in the name, type it the url i wanna store It appears perfect. but when i click it for the second time it doesn't take me to the site, instead (About:blank) appears in the url bar. </p>

```<code>Public Class Form1
Dim UrlF1,UrlF2,UrlF3,UrlF4,UrlF5 As string
Function FavUrl
    Dim Url As string = Inputbox("Enter Url")
    Return Url
End Function
sub fav(a As object,b As object,c As string)

    If a.text = "" then
        a.Text = FavName
        c = FavUrl
        b.Visible = true
    Else
        txtURL.text = c
        btnGo.PerformClick
    End If

End sub
Function FavName
    Dim Name As String = InputBox("What do you wanna call it?")
    Return Name
End Function
Sub NavBar
    txtURL.Text = UrlReturn
End sub
Function UrlReturn
    Return WB.Document.Url.AbsoluteUri
End Function
Private Sub btnFavs_Click(sender As Object, e As EventArgs) Handles btnFavs1.Click
    fav(btnfavs1,btnfavs2,UrlF1)
End Sub
Private Sub btnFavs2_Click(sender As Object, e As EventArgs) Handles btnFavs2.Click
    fav(btnfavs2,btnfavs3,UrlF2)

End Sub
</code>```

答:
This would be an alternative way of achieving your goal without all the fuss:</p>

```<code>  Private Sub ButtonClickHandler(sender As Object, e As EventArgs) Handles btnFavs1.Click, btnFavs2.Click, btnFavs3.Click

        Try
            Dim thisBtn As Button = DirectCast(sender, Button)

            If thisBtn.Text.Length = 0 Then
                thisBtn.Text = InputBox("What do you want to call it?")
                thisBtn.Tag = InputBox("The URL") 'WB.Document.Url.AbsoluteUri
            Else
                txtURL.Text = thisBtn.Tag.ToString
                btnGo.PerformClick()
            End If

        Catch ex As Exception
            MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
        End Try

    End Sub
</code>```

Body:
so basically that's a browser code, I'm facing a problem when trying to save links of favorite sites in a favorite button. Problem is When i Click the button btnFav1 or btnFav2, type in the name, type it the url i wanna store It appears perfect. but when i click it for the second time it doesn't take me to the site, instead (About:blank) appears in the url bar.

Public Class Form1
Dim UrlF1,UrlF2,UrlF3,UrlF4,UrlF5 As string
Function FavUrl
    Dim Url As string = Inputbox("Enter Url")
    Return Url
End Function
sub fav(a As object,b As object,c As string)

    If a.text = "" then
        a.Text = FavName
        c = FavUrl
        b.Visible = true
    Else
        txtURL.text = c
        btnGo.PerformClick
    End If

End sub
Function FavName
    Dim Name As String = InputBox("What do you wanna call it?")
    Return Name
End Function
Sub NavBar
    txtURL.Text = UrlReturn
End sub
Function UrlReturn
    Return WB.Document.Url.AbsoluteUri
End Function
Private Sub btnFavs_Click(sender As Object, e As EventArgs) Handles btnFavs1.Click
    fav(btnfavs1,btnfavs2,UrlF1)
End Sub
Private Sub btnFavs2_Click(sender As Object, e As EventArgs) Handles btnFavs2.Click
    fav(btnfavs2,btnfavs3,UrlF2)

End Sub

Body:
This would be an alternative way of achieving your goal without all the fuss:

  Private Sub ButtonClickHandler(sender As Object, e As EventArgs) Handles btnFavs1.Click, btnFavs2.Click, btnFavs3.Click

        Try
            Dim thisBtn As Button = DirectCast(sender, Button)

            If thisBtn.Text.Length = 0 Then
                thisBtn.Text = InputBox("What do you want to call it?")
                thisBtn.Tag = InputBox("The URL") 'WB.Document.Url.AbsoluteUri
            Else
                txtURL.Text = thisBtn.Tag.ToString
                btnGo.PerformClick()
            End If

        Catch ex As Exception
            MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
        End Try

    End Sub


问:
What's the best way to manage the EF context in a three layer architecture with WebApi 2.0?
I'm trying to create an API architecture using WebApi 2.0 and Entity Framework 6.0 and I want to be near to the best practices so here is what I have atm.

API is an Azure API template and have references to BusinessLogic and Domain

BusinessLogic is a Class Library and have references to DataAccess and Domain

DataAccess is a Class Library and have a reference to Domain (also there are here the EF references)

I have edited the T4 template in DataAccess to generate POCO classes in Domain project and alterated the namespaces generation to acomplish that.
At this point it's all ok but my big concern is related to the layer independence regarding this architecture and EF model context.

What I know (let me know if I'm wrong in anyone):

Have a shared model context (singleton pattern) with the EF context in a WebApi is a bad practice.

The only place where I should have EF context object is in Domain

Any request to the API who generate a db interaction should create its independent EF Model context (independent from other request) but try to use the same context along the all db interactions at this particular request.

So thinking on that, what's the best way to manage the EF context in a three layer architecture with WebApi 2.0

答:
The DataAccess layer has the purpose of abstract the domain of the data persistence. EF is an ORM, so the EF itself is a kind of DataAccess library. Maybe you could still have the separations having repository implementations for you domain objects inside DataAccess project.

About your questions:

1) Yes, DbContext is a transient object.

2) EF POCO classes as Domain Objects is a bad practice. Domain objects shouldn't be anemic. They need to have logic. In the other hand, mix the domain objects with additional properties, sometimes required by ORMs (NHibernate, EF) seems like you data access technology is leaked your domain model.

Why not use memento pattern (or state object) to avoid this leaks and use some kind of mapper library (maybe Automapper) between the communication of your layes using DTOs?

Another alternative is handle the translation between your Domain object and your persistence object be a responsability of your Repository, but this solution could be a violation of Single Responsability Principle. So you need to trade between have that responsability in the Domain object itself, move to repository, or have specific classes for that duty.

A third alternative could be the use of Interfaces.

The memento and Interface approaches are explained here

3) In you introduce IoC pattern. Using Dependency Injection you could move the responsability of create a DbContext outside of both, your Domain project and your Data Access project. This kind of design allows you to do interesting things in your composition root, you could have a DbContext per Http Request.