问:
Stop Karaf from generating new SSH keys on startup
I've noticed that Karaf keeps generating new SSH keys on each startup. It makes automatic scripts connecting via ssh useless, because new key must be manually accepted each time.

Is it possible to stop that behaviour and generate new keys only once per new installation?

More debug info: I've noticed, that 'etc/host.key' has not changed. However, after stopping and starting karaf I get the message:

ssh -p 8101 localhost -oHostKeyAlgorithms=+ssh-dss

```<code>Offending DSA key in ~/.ssh/known_hosts:5
  remove with:
  ssh-keygen -f "~/.ssh/known_hosts" -R [localhost]:8101
DSA host key for [localhost]:8101 has changed and you have requested strict checking.
Host key verification failed.
</code>```

The fact that DSA keys are generated doesn't match the log message from karaf.log as well:

INFO  | sshd-SshServer[20056f77]-nio2-thread-2 |
  SimpleGeneratorHostKeyProvider   | 48 - org.apache.sshd.core - 1.2.0 |
  generateKeyPair(RSA) generating host key - size=4096

My etc/org.apache.karaf.shell.cfg:

```<code>sshPort=8101
sshHost=0.0.0.0
sshRealm=karaf
hostKey=${karaf.etc}/host.key
algorithm=RSA
keySize=4096
</code>```

After digging in logs I've found out, that host.key file is not loaded properly:

2017-03-29T13:44:58,977 | WARN  |
  sshd-SshServer[18c17f90]-nio2-thread-1 |
  SimpleGeneratorHostKeyProvider   | 48 - org.apache.sshd.core - 1.2.0 |
  resolveKeyPair(~/karaf-docker/apache-karaf-4.1.0/etc/host.key) Failed
  (InvalidKeySpecException) to load: Missing classes:
  org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateCrtKey
  2017-03-29T13:45:00,340 | ERROR |
  sshd-SshServer[18c17f90]-nio2-thread-1 |
  SimpleGeneratorHostKeyProvider   | 48 - org.apache.sshd.core - 1.2.0 |
  Overwriting key (~/karaf-docker/apache-karaf-4.1.0/etc/host.key) is
  disabled: using throwaway ssh-dss:
  SHA256:3yWwxdzoymMvEBYIWMIguQ8G3J7kfapd+avCMoue2R4
  2017-03-29T13:45:00,342 | WARN  |
  sshd-SshServer[18c17f90]-nio2-thread-1 | ServerSessionImpl

The Apache SSHD reads/writes host.key using Java Serialization which might cause issues in OSGi (and, maybe even worse, redeploy of feature might turn the file useless).

答:
Karaf creates the server key when you first connect using ssh. It will then place the key in karaf home etc/host.key. So the key should only be created once for each karaf server.

You can also provide your own key there to avoid the overhead of the creation.

The key is generated by org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider. When it creates a key you should see this message in the log:

```<code>generateKeyPair(RSA) generating host key - size=4096
</code>```

Body:
I've noticed that Karaf keeps generating new SSH keys on each startup. It makes automatic scripts connecting via ssh useless, because new key must be manually accepted each time.

Is it possible to stop that behaviour and generate new keys only once per new installation?

More debug info: I've noticed, that 'etc/host.key' has not changed. However, after stopping and starting karaf I get the message:

ssh -p 8101 localhost -oHostKeyAlgorithms=+ssh-dss

Offending DSA key in ~/.ssh/known_hosts:5
  remove with:
  ssh-keygen -f "~/.ssh/known_hosts" -R [localhost]:8101
DSA host key for [localhost]:8101 has changed and you have requested strict checking.
Host key verification failed.

The fact that DSA keys are generated doesn't match the log message from karaf.log as well:

INFO  | sshd-SshServer[20056f77]-nio2-thread-2 |
  SimpleGeneratorHostKeyProvider   | 48 - org.apache.sshd.core - 1.2.0 |
  generateKeyPair(RSA) generating host key - size=4096

My etc/org.apache.karaf.shell.cfg:

sshPort=8101
sshHost=0.0.0.0
sshRealm=karaf
hostKey=${karaf.etc}/host.key
algorithm=RSA
keySize=4096

After digging in logs I've found out, that host.key file is not loaded properly:

2017-03-29T13:44:58,977 | WARN  |
  sshd-SshServer[18c17f90]-nio2-thread-1 |
  SimpleGeneratorHostKeyProvider   | 48 - org.apache.sshd.core - 1.2.0 |
  resolveKeyPair(~/karaf-docker/apache-karaf-4.1.0/etc/host.key) Failed
  (InvalidKeySpecException) to load: Missing classes:
  org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateCrtKey
  2017-03-29T13:45:00,340 | ERROR |
  sshd-SshServer[18c17f90]-nio2-thread-1 |
  SimpleGeneratorHostKeyProvider   | 48 - org.apache.sshd.core - 1.2.0 |
  Overwriting key (~/karaf-docker/apache-karaf-4.1.0/etc/host.key) is
  disabled: using throwaway ssh-dss:
  SHA256:3yWwxdzoymMvEBYIWMIguQ8G3J7kfapd+avCMoue2R4
  2017-03-29T13:45:00,342 | WARN  |
  sshd-SshServer[18c17f90]-nio2-thread-1 | ServerSessionImpl

The Apache SSHD reads/writes host.key using Java Serialization which might cause issues in OSGi (and, maybe even worse, redeploy of feature might turn the file useless).

Body:
Karaf creates the server key when you first connect using ssh. It will then place the key in karaf home etc/host.key. So the key should only be created once for each karaf server.

You can also provide your own key there to avoid the overhead of the creation.

The key is generated by org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider. When it creates a key you should see this message in the log:

generateKeyPair(RSA) generating host key - size=4096


来源: stackexchange

问:
Invalid mongo configuration, either uri or host/port/credentials must be specified
I'm getting this exception :

```<code>Caused by: java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials must be specified
    at org.springframework.boot.autoconfigure.mongo.MongoProperties.createMongoClient(MongoProperties.java:207)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration.mongo(MongoAutoConfiguration.java:73)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.CGLIB$mongo$1(<generated>)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896$$FastClassBySpringCGLIB$$c0338f6a.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.mongo(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 25 common frames omitted
</code>```

Here is my application.yml content :

```<code>spring:
  data:
    mongodb:
      uri: mongodb://develop:d3VeL0p$@<my_host>:27017/SHAM
</code>```

Here is my configuration class :

```<code>package com.me.service.testservice.config;

import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.me.service.testservice.repository"}, considerNestedRepositories = true)
public class SpringMongoConfiguration {

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(new MongoClient("<my_host>"), "SHAM");
    }
}
</code>```

Now I'm getting this stack trace when starting without failing, it looks like user develop doesn't have the right to connect:

```<code>Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server phelbwlabect003.karmalab.net:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
    at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
    at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:117)
    at com.mongodb.connection.SaslAuthenticator.access$000(SaslAuthenticator.java:37)
    at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:50)
    ... 9 common frames omitted
</code>```

答:
The issue was authentication-database was missing.

Here is now the working configuration :

```<code>spring:
  data:
    mongodb:
      host: <my_host>
      username: develop
      password: d3VeL0p$
      port: 27017
      database: SHAM
      repositories:
        enabled: true
      authentication-database: admin
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm getting this exception :

Caused by: java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials must be specified
    at org.springframework.boot.autoconfigure.mongo.MongoProperties.createMongoClient(MongoProperties.java:207)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration.mongo(MongoAutoConfiguration.java:73)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.CGLIB$mongo$1(<generated>)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896$$FastClassBySpringCGLIB$$c0338f6a.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.mongo(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 25 common frames omitted

Here is my application.yml content :

spring:
  data:
    mongodb:
      uri: mongodb://develop:d3VeL0p$@<my_host>:27017/SHAM

Here is my configuration class :

package com.me.service.testservice.config;

import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.me.service.testservice.repository"}, considerNestedRepositories = true)
public class SpringMongoConfiguration {

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(new MongoClient("<my_host>"), "SHAM");
    }
}

Now I'm getting this stack trace when starting without failing, it looks like user develop doesn't have the right to connect:

Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server phelbwlabect003.karmalab.net:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
    at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
    at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:117)
    at com.mongodb.connection.SaslAuthenticator.access$000(SaslAuthenticator.java:37)
    at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:50)
    ... 9 common frames omitted

Body:
The issue was authentication-database was missing.

Here is now the working configuration :

spring:
  data:
    mongodb:
      host: <my_host>
      username: develop
      password: d3VeL0p$
      port: 27017
      database: SHAM
      repositories:
        enabled: true
      authentication-database: admin


问:
Converting NSString to char byte array
In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

```<code>char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};
</code>```

How to convert my NSString to char byte array like this one?

Thanks!

答:
```<code> NSString *strCharData = @"AA010158AA7D385002";
 const char *characterRes = [strCharData cStringUsingEncoding:NSUTF8StringEncoding];

      or

 NSString *strCharData = @"AA010158AA7D385002";
 const char *characterRes = [strCharData UTF8String];
</code>```

Title: Converting NSString to char byte array

Body:
In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};

How to convert my NSString to char byte array like this one?

Thanks!


问:
Sorting two arrays (values,keys), then sorting the keys
I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

```<code>int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);
</code>```

Then the arrays would look like this:

```<code>values = {10,10,20,20,30};
keys = {4,1,2,3,5};
</code>```

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

```<code>keys = {1,4,2,3,5};
</code>```

Notice the 1 and 4 values are switched and the order of the value array has not changed.

答:
If an "in-place sorting" is not strictly necessary for you, I suggest to use OrderBy:

```<code>var sortedPairs = values.Select((x, i) => new { Value = x, Key = keys[i] })
                        .OrderBy(x => x.Value)
                        .ThenBy(x => x.Key)
                        .ToArray(); // this avoids sorting 2 times...
int[] sortedValues = sortedPairs.Select(x => x.Value).ToArray();
int[] sortedKeys = sortedPairs.Select(x => x.Key).ToArray();

// Result:
// sortedValues = {10,10,20,20,30};
// sortedKeys = {1,4,2,3,5};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have what seems to be a simple problem but I can't figure it out so far.

Say I have two arrays:

int[] values = {10,20,20,10,30};
int[] keys = {1,2,3,4,5};

Array.Sort(values,keys);

Then the arrays would look like this:

values = {10,10,20,20,30};
keys = {4,1,2,3,5};

Now, what I want to do is make it so that the keys are also sorted in second priority so the key array to look like this:

keys = {1,4,2,3,5};

Notice the 1 and 4 values are switched and the order of the value array has not changed.

Body:
If an "in-place sorting" is not strictly necessary for you, I suggest to use OrderBy:

var sortedPairs = values.Select((x, i) => new { Value = x, Key = keys[i] })
                        .OrderBy(x => x.Value)
                        .ThenBy(x => x.Key)
                        .ToArray(); // this avoids sorting 2 times...
int[] sortedValues = sortedPairs.Select(x => x.Value).ToArray();
int[] sortedKeys = sortedPairs.Select(x => x.Key).ToArray();

// Result:
// sortedValues = {10,10,20,20,30};
// sortedKeys = {1,4,2,3,5};


问:
cron job scripts for how to set it
I need to perform a daily download directly from the web server, then I thought to activate the cron function that is supported by the server. I put a script in php so

```<code><?php
$file = file_get_contents('http://www.example.com/donwload.txt');
?>
</code>```

When I call the script for the test, I expect to find in the folder where there is' the script, even the downloaded files but rather not waste anything, obviously I'm wrong, Aas I can do this?

答:
Someone asked the same thing here, so my suggestion was

If you are using PHP, you can create a function and will be invoked through CLI. Then you need to add it in the crontab.

example index.php

```<code><?php

//Get the data from the mysql table and process
</code>```

$data = getDataFromTable();

```<code> if ($data['user_defined_time'] == date('H') // Current Hour
    echo "Foo Bar"; //send email

    ?>
</code>```

To test this, open your terminal and run the command php -f index.php

Add this to the crontab. In your terminal type crontab -e and edit the line to :

Run your script every hour

0 * * * * php -f /location/of/php/file/index.php

Title: cron job scripts for how to set it

Body:
I need to perform a daily download directly from the web server, then I thought to activate the cron function that is supported by the server. I put a script in php so

<?php
$file = file_get_contents('http://www.example.com/donwload.txt');
?>

When I call the script for the test, I expect to find in the folder where there is' the script, even the downloaded files but rather not waste anything, obviously I'm wrong, Aas I can do this?

Body:
Someone asked the same thing here, so my suggestion was

If you are using PHP, you can create a function and will be invoked through CLI. Then you need to add it in the crontab.

example index.php

<?php

//Get the data from the mysql table and process

$data = getDataFromTable();

 if ($data['user_defined_time'] == date('H') // Current Hour
    echo "Foo Bar"; //send email

    ?>

To test this, open your terminal and run the command php -f index.php

Add this to the crontab. In your terminal type crontab -e and edit the line to :

Run your script every hour

0 * * * * php -f /location/of/php/file/index.php


问:
Memcache maximum key expiration time
What's memcached's maximum key expiration time?

If I don't provide an expiration time and the cache gets full, what happens?

答:
On laravel config.session.lifetime setting that if set to be an equivalent of 30days above, will be considered as a timestamp (this will give an error of token mismatch everytime assuming that memcached is used).

To answer, memcached expiration could be set anytime. (Laravel's default setting (on v5.0) will set you to an already expire timestamp). If you did not set it, the defualt will be used.

Title: Memcache maximum key expiration time


问:
boost shared_ptr factory function
I'm pretty new to the world of pointers and have run into a problem in my code.  I have a factory class that spits out shared_ptr's.  "Entity" is the base class for any type of shared_ptr that gets created from this method.

If I overwrite the pointer in the get_entity method, everything seems to work.  If i overwrite the pointer in the get_pointer method it doesn't.

```<code>//
// typedef boost::shared_ptr<Entity> EntityPtr;

Entity::EntityPtr EntityFactory::get_entity(int type) {

    // My default pointer if everything else falls through
    Entity::EntityPtr e = boost::make_shared<Entity>(type);
    std::cout << e->get_type() << std::endl; // Entity

    switch (type) {
    case 1:
        // This works
        e = boost::make_shared<TextEntity>(type);
        std::cout << e->get_type() << std::endl; // TextEntity
        break;
    case 2:
        // This doesn't work
        get_pointer(e, type);
        std::cout << e->get_type() << std::endl; // Entity
        break;
    }

    return e;

}

// This function can (possibly) overwrite the passed-in pointer
void EntityFactory::get_pointer(Entity::EntityPtr e, int type) {

    // ...

    e = boost::make_shared<TextEntity>(type);

    // ...
}
</code>```

My reasons for passing "e" into the get_pointer method was because i don't always need to modify the pointer.  In some cases get_pointer finishes without modifying the pointer at all.

I'm hoping someone can help shed some light on what i'm doing wrong here.  Thanks!

答:
I'm pretty darn confusuled about wtf you're trying to do since you pass in integers to make_shared.

Your problem may be solved by accepting a reference to Entity::EntityPtr in get_pointer.

Title: boost shared_ptr factory function

Body:
I'm pretty new to the world of pointers and have run into a problem in my code.  I have a factory class that spits out shared_ptr's.  "Entity" is the base class for any type of shared_ptr that gets created from this method.

If I overwrite the pointer in the get_entity method, everything seems to work.  If i overwrite the pointer in the get_pointer method it doesn't.

//
// typedef boost::shared_ptr<Entity> EntityPtr;

Entity::EntityPtr EntityFactory::get_entity(int type) {

    // My default pointer if everything else falls through
    Entity::EntityPtr e = boost::make_shared<Entity>(type);
    std::cout << e->get_type() << std::endl; // Entity

    switch (type) {
    case 1:
        // This works
        e = boost::make_shared<TextEntity>(type);
        std::cout << e->get_type() << std::endl; // TextEntity
        break;
    case 2:
        // This doesn't work
        get_pointer(e, type);
        std::cout << e->get_type() << std::endl; // Entity
        break;
    }

    return e;

}

// This function can (possibly) overwrite the passed-in pointer
void EntityFactory::get_pointer(Entity::EntityPtr e, int type) {

    // ...

    e = boost::make_shared<TextEntity>(type);

    // ...
}

My reasons for passing "e" into the get_pointer method was because i don't always need to modify the pointer.  In some cases get_pointer finishes without modifying the pointer at all.

I'm hoping someone can help shed some light on what i'm doing wrong here.  Thanks!


问:
External promises don't trigger Angular2 change detection (UPDATE: they do)
I'm working on an electron application, whose client side is written in Angular2.

I'm having the classic problem that a lot of people have encountered (eg. here and here), namely that I'm updating my component's data, but the view doesn't get updated because Angular doesn't know that the data has changed. The solutions people suggest (see above and also here) is to manually run change detection, either on the whole component tree, or part of it (similar to Angular 1's $rootScope.$digest and $scope.$digest).

However, I'd like to avoid wrapping all my data changes in zone.run() calls, as it slightly defeats the purpose of using Angular.

I'm pretty sure I know why this happens: I'm creating Bluebird Promises outside of Angular, in electron code (ie, the main process), and these aren't Zone aware, so they don't notify Angular of the changes.

I don't know how to solve it, though. What can I do to create Zone aware promises in my electron code, to avoid having to manually run change detection all the time? Can I convert my Bluebird Promises to Zone aware Promises somehow?

EDIT: I think I was wrong, Bluebird promises aren't Zone aware even if created within angular. They're just not Zone aware in general.

EDIT 2: I was completely wrong in the previous edit. Bluebird promises work just fine with zones. However, in the context of an electron application, creating a promise in the main electron process and using it in the renderer process (where Angular lives), doesn't work, as the returned promise isn't zone-aware. Creating the promise from Angular code worked.

答: As explained in EDIT #2, the problem was that creating a promise in the main electron process made the promise non-zone-aware. Creating the promise from Angular solved it.  </p>


问:
change all checkboxes in one table-row
I want to uncheck all checkboxes that are in one table row.
I have this HTML code :

```<code><tr id="unlosta_line_1">
     <td>
        <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  checked="checked" type="checkbox">
Feld 1
     </td>

     <td>
        <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2"  type="checkbox">
Feld 2
     </td>

     <td>
        <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3"  type="checkbox">
Feld 3
     </td>
     <td>...and so on
     <td>
</tr>
</code>```

What I have tried at now is this jquery code:

```<code>$("tr#unlosta_line_1").children("td").each(function(i) { $(i).prop("checked", false) } )
</code>```

答:
input is the children of the td

(function (){
$("#unlosta_line_1").children("td").each(function(i) {
      $(this).children('input').attr("checked", false)
      })
      })()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="unlosta_line_1">
  <td>
    <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  type="checkbox"> Feld 1
  </td>

  <td>
    <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2" type="checkbox"> Feld 2
  </td>

  <td>
    <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3" type="checkbox"> Feld 3
  </td>
  <td>...and so on
    <td>
</tr>
</table></code>```

Title: change all checkboxes in one table-row

Body:
I want to uncheck all checkboxes that are in one table row.
I have this HTML code :

        <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  checked="checked" type="checkbox">
Feld 1

        <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2"  type="checkbox">
Feld 2

        <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3"  type="checkbox">
Feld 3

     ...and so on

What I have tried at now is this jquery code:

$("tr#unlosta_line_1").children("td").each(function(i) { $(i).prop("checked", false) } )

Body:
input is the children of the td

(function (){
$("#unlosta_line_1").children("td").each(function(i) {
      $(this).children('input').attr("checked", false)
      })
      })()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="unlosta_line_1">
  <td>
    <input id="unlosta_prop_id_1" name="unlosta_prop_id[1]" value="1"  type="checkbox"> Feld 1
  </td>

  <td>
    <input id="unlosta_prop_id_2" name="unlosta_prop_id[2]" value="2" type="checkbox"> Feld 2
  </td>

  <td>
    <input id="unlosta_prop_id_3" name="unlosta_prop_id[3]" value="3" type="checkbox"> Feld 3
  </td>
  <td>...and so on
    <td>
</tr>
</table>


问:
Swift does not support multiple inheritance, How could be achieved?
The following code:

```<code>class City {
    var cityId : String?
    var cityName : String?
}

class Town {
    var townid : String?
    var townName : String?

}

class Address : City , Town {

    var house : String?
    var street: String?

}
</code>```

Generates a compile-time error:

Address.swift:38:24: Multiple inheritance from classes 'City' and 'Town'

How can I solve his kind of problem? What approach to follow?

答:
It seems you are overthinking things. Instead of inheritance, try to use more composition. An address should not inherit from City. Why? Because logically an address is not a type of city. Instead, city definition is part of the address:

```<code>class Address {
    var city: City?
    var town: Town?

    var house : String?
    var street: String?
}
</code>```

Body:
The following code:

class City {
    var cityId : String?
    var cityName : String?
}

class Town {
    var townid : String?
    var townName : String?

}

class Address : City , Town {

    var house : String?
    var street: String?

}

Generates a compile-time error:

Address.swift:38:24: Multiple inheritance from classes 'City' and 'Town'

How can I solve his kind of problem? What approach to follow?

Body:
It seems you are overthinking things. Instead of inheritance, try to use more composition. An address should not inherit from City. Why? Because logically an address is not a type of city. Instead, city definition is part of the address:

class Address {
    var city: City?
    var town: Town?

    var house : String?
    var street: String?
}


问:
Send E-Mail from Python with umlaut in the in recipient's or sender's name
I currently trying to send e-mails from a python script to a set of recipients that a got from a database (name + email address) and I want so send the mails such that their name is also included in the message header. But if the name includes an umlaut (äöü...) my script fails with (in case there is an ü inside the name):

```<code>UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 5: ordinal not in range(128)
</code>```

But in the content of the message all umlauts are correctly replaced with for example =C3=BC for the ü.

Here is the example code I used:

```<code>import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

msg = EmailMessage()
msg["Subject"] = "Python Test"
msg["From"] = Address("Max Müller" , addr_spec="maxmueller@localhost.localnet")
msg["To"] =  Address("Max Möller", addr_spec="moeller@localhost.localnet")

msg.set_content("""\
This is a test with umlauts. öäü
--- Max Müller """)
server = smtplib.SMTP('localhost', 25)
server.send_message(msg)
server.quit()
</code>```

I tried it with Python 3.5.2.

If replace

```<code>msg["From"] = Address("Max Müller" , addr_spec="maxmueller@localhost.localnet")
</code>```

by

```<code>msg["From"] = Address("Max Müller".encode("utf-8") , addr_spec="maxmueller@localhost.localnet")
</code>```

I got in my mail client as senders name b'Max M\xc3\xbcller' which is useless to the most e-mail clients.

So how do I get the umlauts in the recipient's and the sender's encoded as in the mail's content?

答:
Almost all was fine, but the send_message method is not really non-ASCII friendly, so you must use the good old sendmail. The problem is that send_message tries to use the content of the To and From headers to build the envelope addresses but unfortunately it is broken for addresses containing non ASCII characters even if they are in the name part.

So if you have only one recipient address, you code should simply be:

```<code>...
server.sendmail(msg["From"], msg["To"], msg.as_string())
</code>```

If you want to be able to process multiple recipient addresses, you must add an explicit processing:

```<code>def envelopeAddr(header):
    return [a.addr_spec for a in header.addresses]
</code>```

The sendmail command becomes:

```<code>server.sendmail(msg["From"], envelopeAddr(msg["To"]), msg.as_string())
</code>```

The good new is that it also works for a single dest address.

ContentLicense: CC BY-SA 4.0

Body:
I currently trying to send e-mails from a python script to a set of recipients that a got from a database (name + email address) and I want so send the mails such that their name is also included in the message header. But if the name includes an umlaut (äöü...) my script fails with (in case there is an ü inside the name):

UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 5: ordinal not in range(128)

But in the content of the message all umlauts are correctly replaced with for example =C3=BC for the ü.

Here is the example code I used:

import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

msg = EmailMessage()
msg["Subject"] = "Python Test"
msg["From"] = Address("Max Müller" , addr_spec="maxmueller@localhost.localnet")
msg["To"] =  Address("Max Möller", addr_spec="moeller@localhost.localnet")

msg.set_content("""\
This is a test with umlauts. öäü
--- Max Müller """)
server = smtplib.SMTP('localhost', 25)
server.send_message(msg)
server.quit()

I tried it with Python 3.5.2.

If replace

msg["From"] = Address("Max Müller" , addr_spec="maxmueller@localhost.localnet")

by

msg["From"] = Address("Max Müller".encode("utf-8") , addr_spec="maxmueller@localhost.localnet")

I got in my mail client as senders name b'Max M\xc3\xbcller' which is useless to the most e-mail clients.

So how do I get the umlauts in the recipient's and the sender's encoded as in the mail's content?

Body:
Almost all was fine, but the send_message method is not really non-ASCII friendly, so you must use the good old sendmail. The problem is that send_message tries to use the content of the To and From headers to build the envelope addresses but unfortunately it is broken for addresses containing non ASCII characters even if they are in the name part.

So if you have only one recipient address, you code should simply be:

...
server.sendmail(msg["From"], msg["To"], msg.as_string())

If you want to be able to process multiple recipient addresses, you must add an explicit processing:

def envelopeAddr(header):
    return [a.addr_spec for a in header.addresses]

The sendmail command becomes:

server.sendmail(msg["From"], envelopeAddr(msg["To"]), msg.as_string())

The good new is that it also works for a single dest address.


问:
What version of VS do I need to deploy to BizTalk 2013 R2 on a SQL Server 2012 database?
I am developing with BizTalk for the first time. I have created an extremely basic project in VS2103 which builds but fails to deploy with the output:

```<code>error DEPLOY: The database or the database version is incompatible with the installed version of this product.
</code>```

The BizTalk installation is BizTalk 2013 R2 on a SQL Server 2012 SP3 database.

My project is using VS2013 because I understand that VS2105 can't be used to target BizTalk 2013.

There is no further information in the output window. I have a valid login on the database and can perform CRUD operations on it through VS2013.

This page suggests I need "SQL Server Development Tools" - am I right in assuming this means "SQL Server Data Tools" because that's all I seem to get when I search for it.

Even a pointer to where I can find a more more informative error would be useful (perhaps unsurprisingly changing the build verbosity only affects the build output when what I'd like is a more informative deploy output!).

答: Apparently this issue is related to the OS - BizTalk 2013 (or some other element of my setup) isn't compatible with Windows Server 2012 R2. Downgrading to R1 isn't an option the security team will allow. Upgrading BizTalk means upgrading SQL Server means upgrading some other software we have running on it so that's not going to happen any time soon. Looks like it's time for me to move to Azure!</p>

Body:
I am developing with BizTalk for the first time. I have created an extremely basic project in VS2103 which builds but fails to deploy with the output:

error DEPLOY: The database or the database version is incompatible with the installed version of this product.

The BizTalk installation is BizTalk 2013 R2 on a SQL Server 2012 SP3 database.

My project is using VS2013 because I understand that VS2105 can't be used to target BizTalk 2013.

There is no further information in the output window. I have a valid login on the database and can perform CRUD operations on it through VS2013.

This page suggests I need "SQL Server Development Tools" - am I right in assuming this means "SQL Server Data Tools" because that's all I seem to get when I search for it.

Even a pointer to where I can find a more more informative error would be useful (perhaps unsurprisingly changing the build verbosity only affects the build output when what I'd like is a more informative deploy output!).


问:
Attach my app's icon to default Contacts app's Quick Action menu
The default Contacts app in Android has a very handy Quick Action menu when you tap on user's icon.

I would like to know whether anyone has been able to attach their own app to this menu and if so how they did it.

I would like to avoid writing my own contacts app just to provide a feature.

答: It's called the QuickContactBadge. You can't force your app's icon in there. If you make your App able to send SMS, the user can then choose your App as the default to send SMS (as an example). If they check the box to make yours the default, You'll see your icon there next time they open a contact's quickBadge instead of the default Messaging icon.   </p>


问:
SQL query using code igniter
How can I write this query to a code igniter query?

```<code>WHERE
  SmallVersion.ID =
  (
    SELECT ChildSmallVersionID AS ID FROM SmallVersion
    WHERE ID = $id
  )
</code>```

this is how is looks so far:

```<code>         ->where('SmallVersion.ID', ("SELECT `ChildSmallVersionID` AS ID
                  FROM `SmallVersion` WHERE ID = $id"));
</code>```

答:
There is no possibility to create brackets in Active Records but you can write it directly in your clause:

```<code>$where = "SmallVersion.ID =
  (
    SELECT ChildSmallVersionID AS ID FROM SmallVersion
    WHERE ID = $id
  )";
$this->db->where($where, NULL, FALSE);
</code>```

If third parameter is set to FALSE, CodeIgniter will not protect your query.

Documentation for active records:
https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data

Title: SQL query using code igniter

Body:
How can I write this query to a code igniter query?

WHERE
  SmallVersion.ID =
  (
    SELECT ChildSmallVersionID AS ID FROM SmallVersion
    WHERE ID = $id
  )

this is how is looks so far:

         ->where('SmallVersion.ID', ("SELECT `ChildSmallVersionID` AS ID
                  FROM `SmallVersion` WHERE ID = $id"));

Body:
There is no possibility to create brackets in Active Records but you can write it directly in your clause:

$where = "SmallVersion.ID =
  (
    SELECT ChildSmallVersionID AS ID FROM SmallVersion
    WHERE ID = $id
  )";
$this->db->where($where, NULL, FALSE);

If third parameter is set to FALSE, CodeIgniter will not protect your query.

Documentation for active records:
https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data


问:
VBA opening/closing workbooks on MAC throws error
The following macro has no problems on windows but throws a runtime error on a MAC. The problem is that I do not have a MAC to test this on. The code simply picks up the locations of 2 files (A & B) from cells on another sheet, opens them, copies the data into another sheet and does some calculations.

```<code>Sub Compile()
Application.ScreenUpdating = False

ThisBook = ActiveWorkbook.Name

'open A
Workbooks.Open (Sheets("Control").Range("C2"))
ABook = ActiveWorkbook.Name

'copy data from A
Workbooks(ThisBook).Sheets("Data").Cells.Clear
ActiveSheet.UsedRange.Copy Workbooks(ThisBook).Sheets("data").Range("A1")

'close A
Workbooks(ThisBook).Activate
Workbooks(ABook).Close False

'prep A
Sheets("data").Activate
C = Range("A" & Cells.Rows.Count).End(xlUp).Row

'some calculation

'open B
Workbooks.Open (Sheets("Control").Range("C5"))
BBook = ActiveWorkbook.Name

'prep B
D = ActiveSheet.Range("A" & Cells.Rows.Count).End(xlUp).Row

'some calculation

'copy B
Range("M2:M" & D).Copy Workbooks(ThisBook).Sheets("data").Range("O2")

'close B
Workbooks(ThisBook).Activate
Workbooks(BBook).Close False

'calculate
Sheets("data").Activate

'some more calculations

Application.ScreenUpdating = True
End Sub
</code>```

A version where the data is already in the same workbook on other sheets works fine. So it must be opening/closing/switching between the workbooks that isn't working.

答:
Depends on 2011 (: as separator) vs 2016 (Posix path) Office for Mac

http://www.rondebruin.nl/mac/mac017.htm

Body:
The following macro has no problems on windows but throws a runtime error on a MAC. The problem is that I do not have a MAC to test this on. The code simply picks up the locations of 2 files (A & B) from cells on another sheet, opens them, copies the data into another sheet and does some calculations.

Sub Compile()
Application.ScreenUpdating = False

ThisBook = ActiveWorkbook.Name

'open A
Workbooks.Open (Sheets("Control").Range("C2"))
ABook = ActiveWorkbook.Name

'copy data from A
Workbooks(ThisBook).Sheets("Data").Cells.Clear
ActiveSheet.UsedRange.Copy Workbooks(ThisBook).Sheets("data").Range("A1")

'close A
Workbooks(ThisBook).Activate
Workbooks(ABook).Close False

'prep A
Sheets("data").Activate
C = Range("A" & Cells.Rows.Count).End(xlUp).Row

'some calculation

'open B
Workbooks.Open (Sheets("Control").Range("C5"))
BBook = ActiveWorkbook.Name

'prep B
D = ActiveSheet.Range("A" & Cells.Rows.Count).End(xlUp).Row

'some calculation

'copy B
Range("M2:M" & D).Copy Workbooks(ThisBook).Sheets("data").Range("O2")

'close B
Workbooks(ThisBook).Activate
Workbooks(BBook).Close False

'calculate
Sheets("data").Activate

'some more calculations

Application.ScreenUpdating = True
End Sub

A version where the data is already in the same workbook on other sheets works fine. So it must be opening/closing/switching between the workbooks that isn't working.


问:
How to pass data to angular 2 router
I need to pass data to angular router outlet. It can be done using parameter or optional parameter (Query Parameter). But my question is there any other way to pass data to router outlet other than using parameter passing. what is the better way to accomplish this.</p>

答:
(1) You can use data property like below :

```<code>{path: 'user/:id', component: UserDetailComponent , data: [{userName: 'testname'}]}
</code>```

and consume in Component like :

```<code>export class UserDetailComponent {
  userId : string;
  userName: string;

  constructor(route: ActivatedRoute) {
    this.userId = route.snapshot.params['id'];
    this.userName = route.snapshot.data[0]['userName'];
  }
}
</code>```

(2) or you can create service which share data across. like :

```<code>@Injectable()
export class UserService{
private userData: IUserData;
  constructor(){}
  getUserData() : IUserData[] {
    return this.userData;
  }
setUserData(data) {
    this.userData = data;
  }
}
</code>```

further, inject the service in desired component :

```<code>constructor(private userService: UserService)
</code>```

Use localStorage to persist data., by importing it import { LocalStorageModule } from 'angular-2-local-storage';

Title: How to pass data to angular 2 router

Body:
(1) You can use data property like below :

{path: 'user/:id', component: UserDetailComponent , data: [{userName: 'testname'}]}

and consume in Component like :

export class UserDetailComponent {
  userId : string;
  userName: string;

  constructor(route: ActivatedRoute) {
    this.userId = route.snapshot.params['id'];
    this.userName = route.snapshot.data[0]['userName'];
  }
}

(2) or you can create service which share data across. like :

@Injectable()
export class UserService{
private userData: IUserData;
  constructor(){}
  getUserData() : IUserData[] {
    return this.userData;
  }
setUserData(data) {
    this.userData = data;
  }
}

further, inject the service in desired component :

constructor(private userService: UserService)

Use localStorage to persist data., by importing it import { LocalStorageModule } from 'angular-2-local-storage';


问:
How do I get Google refund orders ？
The Google Void Purchase API says:

The Google Play Voided Purchases API allows you to revoke access to
  in-app products that are associated with purchases that a user has
  voided. The user can void a purchase in the following ways:

The user requests a refund for their order.

The user cancels their order.

An order is charged back.

But when I  get this API's return, I found some purchases state are Charged.

Why Charged order is return by Google Void Purchases ?

How do I get all refund orders ?

答:
Finally I get the way to handle this, that is , recheck from google.

Just like when the purchase is paid, we check from google is this purchase really paid, and if we get a return from Void Purchase, we can use paid API
get the purchase STATE, if not CHARGED, I think the purchase is real void purchase, hope this help.

Title: How do I get Google refund orders ？


问:
List assignment
I have lists like this,

```<code>a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
b=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
c=['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 1']
</code>```

Here I am trying to replace each element of list 'a' one by one with the element of list 'c'.
I tried this code:

```<code>for i in range(len(a)):
    a[i]=c[i]
    print a
    a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
</code>```

With this code I am getting correct output which is:

```<code>['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 1']
</code>```

But when I replaced the last statement(assigning) as

```<code>for i in range(len(a)):
    a[i]=c[i]
    print a
    a=b
</code>```

list 'b' also updating. How can i achieve this with out assigning the entire list directly.

答:
You can try copy moduel in python</p>

```<code>from copy import deepcopy
a = deepcopy(b)
</code>```

Title: List assignment

Body:
I have lists like this,

a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
b=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
c=['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 1']

Here I am trying to replace each element of list 'a' one by one with the element of list 'c'.
I tried this code:

for i in range(len(a)):
    a[i]=c[i]
    print a
    a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']

With this code I am getting correct output which is:

['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 1']

But when I replaced the last statement(assigning) as

for i in range(len(a)):
    a[i]=c[i]
    print a
    a=b

list 'b' also updating. How can i achieve this with out assigning the entire list directly.

Body:
You can try copy moduel in python

from copy import deepcopy
a = deepcopy(b)


问:
Cant find a way to delete an item from sharedPreferences
I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.

```<code>public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;

//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
    this.context = context;
    this.userName = userName;
    //go to user shared preferences and fill the list
    getData();
    notifyDataSetChanged();

}
//how many item to display
@Override
public int getCount() {
    //return the myTasks size....
    return myTasks.size();
}

//return a specific item by index
@Override
public Object getItem(int i) {
    return myTasks.get(i);
}

//return index number
@Override
public long getItemId(int i) {
    return i;
}

//create our view
@Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
    //inflate the view inside view object -> viewInflated
    final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
    //set our inflated view behavior

    //set pointer for our inflated view

    //set pointer for task name....
    final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
    //set pointer for taskInfo
    final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
    //set pointer for task status....
    final Switch swTask = (Switch) viewInflated.findViewById(taskDone);

    //set task name, by the index of my myTasks collection
    txtTaskName.setText(myTasks.get(index).taskName);
    //set task info, by index of myTasks collection
    txtTaskInfo.setText(myTasks.get(index).taskInfo);
    //set task status , switch is getting true/false
    swTask.setChecked(myTasks.get(index).taskStatus);

    //show date and time dialog
    final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
    dtPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final AlertDialog.Builder ad = new AlertDialog.Builder(context);
            final AlertDialog aDialog = ad.create();
            final LinearLayout adLayout = new LinearLayout(context);
            adLayout.setOrientation(LinearLayout.VERTICAL);
            TextView txtTime = new TextView(context);
            txtTime.setText("Choose time");
            adLayout.addView(txtTime);

            final TimePicker tp = new TimePicker(context);
            adLayout.addView(tp);
            final DatePicker dp = new DatePicker(context);
            tp.setVisibility(View.GONE);
            adLayout.addView(dp);

            final Button btnNext = new Button(context);
            btnNext.setText("Next>");
            adLayout.addView(btnNext);
            btnNext.setGravity(1);

            Button btnCancel = new Button(context);
            btnCancel.setText("Cancel");
            adLayout.addView(btnCancel);
            btnCancel.setGravity(1);

            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    aDialog.cancel();
                }
            });
            btnNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int hour = tp.getHour();
                    final int min = tp.getMinute();

                    final String myHour = String.valueOf(hour);
                    final String myMin = String.valueOf(min);

                    calendar.set(Calendar.MONTH, dp.getMonth());
                    calendar.set(Calendar.YEAR, dp.getYear());
                    calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
                    dp.setVisibility(View.GONE);
                    tp.setVisibility(View.VISIBLE);
                    btnNext.setText("Finish");
                    btnNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                            calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
                            calendar.set(Calendar.MINUTE, tp.getMinute());
                            Intent my_intent = new Intent(context, RingtonePlayingService.class);
                            pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                            if(hour > 12){
                                String myHour = String.valueOf(hour - 12);
                            }

                            if(min < 10)
                            {
                                String myMin = "0"+String.valueOf(min);
                            }

                            Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
                            aDialog.cancel();
                        }
                    });
                }
            });
            aDialog.setView(adLayout);
            aDialog.show();
        }
    });

    //create listener event, when switch is pressed
    swTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //we using utlShared to update task status
            //create instance of utlShared
            utlShared myShared = new utlShared(context);
            //calling method of task, and giving userName(shared preferences, taskName, taskStatus)
            myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
            //we sending a message to the user, and inform him/her about the change
            Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();

        }
    });

    //return the view with the behavior.....
    return viewInflated;
}

private void getData() {
    //go to specific shared preferences by user name.....
    SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
    //create instance of our myTasks list
    myTasks = new ArrayList<>();

        Map<String, ?> tasks = taskPref.getAll();
        for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
            //insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
            for(int pos=0 ; pos<myTasks.size() ; pos++){
                myTasks.get(pos);
            }
            String[] str = oneTask.getValue().toString().split(",");
            myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
        }

}
</code>```

}

And my utlShared class is

```<code>public class utlShared {

//context to use later

Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;

public utlShared() {}

public utlShared(Context context)
{
    //get context to use it
    this.context=context;
    //declaretion of shared preferences with file name and file mode (private,public)
   userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
    //declaration of editor
   editor=userPref.edit();

}

//get user and password
public void addUser(String userName, String password)
{

    //stores in the phone device under data\data\package name
    //put in shared preferences user name and password
    editor.putString(userName,password);
    //commit (save/apply) the changes.
    editor.commit();
}

public boolean checkUser(String userName)
{
    //get name by key->userName
    String checkString = userPref.getString(userName,"na");
    //print to logcat a custom message.....
    Log.e("checkUser", "checkUser: "+checkString );
    //check if userName equals to responded data, if it's na, we don't have the user...
    return !checkString.equals("na");

}

public boolean checkUserPassword(String userName, String userPassword)
{
    String checkString = userPref.getString(userName,"na");
    return checkString.equals(userPassword);
}

public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
    //pointer to user task shared preferences
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    //create editor to change the specific shared preferences
    SharedPreferences.Editor taskEditor=taskPref.edit();

    //add new task -> if true write 1 else write 0
    if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }

}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    SharedPreferences.Editor tskEditor=taskPref.edit();
        tskEditor.clear();
        tskEditor.commit();

}
</code>```

}

This method is called from my Welcome class which is

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

String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;

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

}

private void setPointer()
{

    this.context=this;
    userName=getIntent().getStringExtra("userName");
    myUtl = new utlShared(context);
    taskList=(ListView)findViewById(R.id.taskList);
    setListData();
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
    Button btnBack = (Button)findViewById(R.id.btnBack);
    FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
            setListData();
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, MainActivity.class);
            startActivity(intent);
            finish();
        }
    });

}

private void setListData() {
    final TaskAdapter adapter = new TaskAdapter(context, userName);
    taskList.setAdapter(adapter);
}

public void addCustomTask(View view)
{
    //create builder
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    //set title
    builder.setTitle("Add new task!");

    //inflate view from layout ->custom layout,null,false as defualt values
    View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);

    final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
    final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

    builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

            String myTaskCustom = txtCustomTask.getText().toString();
            String myTaskLine = txtCustomLine.getText().toString();
                myUtl.task(userName, myTaskCustom, myTaskLine, false);
                setListData();
        }
    });

    //display our inflated view in screen
    builder.setView(viewInflated);
    //show the dialog
    builder.show();

}
</code>```

}

Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...

Thanks in advance guys, much appreciated!

答:
```<code>taskEditor.remove('item tag');
taskEditor.commit();
</code>```

Body:
I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.

public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;

//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
    this.context = context;
    this.userName = userName;
    //go to user shared preferences and fill the list
    getData();
    notifyDataSetChanged();

}
//how many item to display
@Override
public int getCount() {
    //return the myTasks size....
    return myTasks.size();
}

//return a specific item by index
@Override
public Object getItem(int i) {
    return myTasks.get(i);
}

//return index number
@Override
public long getItemId(int i) {
    return i;
}

//create our view
@Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
    //inflate the view inside view object -> viewInflated
    final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
    //set our inflated view behavior

    //set pointer for our inflated view

    //set pointer for task name....
    final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
    //set pointer for taskInfo
    final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
    //set pointer for task status....
    final Switch swTask = (Switch) viewInflated.findViewById(taskDone);

    //set task name, by the index of my myTasks collection
    txtTaskName.setText(myTasks.get(index).taskName);
    //set task info, by index of myTasks collection
    txtTaskInfo.setText(myTasks.get(index).taskInfo);
    //set task status , switch is getting true/false
    swTask.setChecked(myTasks.get(index).taskStatus);

    //show date and time dialog
    final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
    dtPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final AlertDialog.Builder ad = new AlertDialog.Builder(context);
            final AlertDialog aDialog = ad.create();
            final LinearLayout adLayout = new LinearLayout(context);
            adLayout.setOrientation(LinearLayout.VERTICAL);
            TextView txtTime = new TextView(context);
            txtTime.setText("Choose time");
            adLayout.addView(txtTime);

            final TimePicker tp = new TimePicker(context);
            adLayout.addView(tp);
            final DatePicker dp = new DatePicker(context);
            tp.setVisibility(View.GONE);
            adLayout.addView(dp);

            final Button btnNext = new Button(context);
            btnNext.setText("Next>");
            adLayout.addView(btnNext);
            btnNext.setGravity(1);

            Button btnCancel = new Button(context);
            btnCancel.setText("Cancel");
            adLayout.addView(btnCancel);
            btnCancel.setGravity(1);

            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    aDialog.cancel();
                }
            });
            btnNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int hour = tp.getHour();
                    final int min = tp.getMinute();

                    final String myHour = String.valueOf(hour);
                    final String myMin = String.valueOf(min);

                    calendar.set(Calendar.MONTH, dp.getMonth());
                    calendar.set(Calendar.YEAR, dp.getYear());
                    calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
                    dp.setVisibility(View.GONE);
                    tp.setVisibility(View.VISIBLE);
                    btnNext.setText("Finish");
                    btnNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                            calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
                            calendar.set(Calendar.MINUTE, tp.getMinute());
                            Intent my_intent = new Intent(context, RingtonePlayingService.class);
                            pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                            if(hour > 12){
                                String myHour = String.valueOf(hour - 12);
                            }

                            if(min < 10)
                            {
                                String myMin = "0"+String.valueOf(min);
                            }

                            Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
                            aDialog.cancel();
                        }
                    });
                }
            });
            aDialog.setView(adLayout);
            aDialog.show();
        }
    });

    //create listener event, when switch is pressed
    swTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //we using utlShared to update task status
            //create instance of utlShared
            utlShared myShared = new utlShared(context);
            //calling method of task, and giving userName(shared preferences, taskName, taskStatus)
            myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
            //we sending a message to the user, and inform him/her about the change
            Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();

        }
    });

    //return the view with the behavior.....
    return viewInflated;
}

private void getData() {
    //go to specific shared preferences by user name.....
    SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
    //create instance of our myTasks list
    myTasks = new ArrayList<>();

        Map<String, ?> tasks = taskPref.getAll();
        for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
            //insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
            for(int pos=0 ; pos<myTasks.size() ; pos++){
                myTasks.get(pos);
            }
            String[] str = oneTask.getValue().toString().split(",");
            myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
        }

}

}

And my utlShared class is

public class utlShared {

//context to use later

Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;

public utlShared() {}

public utlShared(Context context)
{
    //get context to use it
    this.context=context;
    //declaretion of shared preferences with file name and file mode (private,public)
   userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
    //declaration of editor
   editor=userPref.edit();

}

//get user and password
public void addUser(String userName, String password)
{

    //stores in the phone device under data\data\package name
    //put in shared preferences user name and password
    editor.putString(userName,password);
    //commit (save/apply) the changes.
    editor.commit();
}

public boolean checkUser(String userName)
{
    //get name by key->userName
    String checkString = userPref.getString(userName,"na");
    //print to logcat a custom message.....
    Log.e("checkUser", "checkUser: "+checkString );
    //check if userName equals to responded data, if it's na, we don't have the user...
    return !checkString.equals("na");

}

public boolean checkUserPassword(String userName, String userPassword)
{
    String checkString = userPref.getString(userName,"na");
    return checkString.equals(userPassword);
}

public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
    //pointer to user task shared preferences
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    //create editor to change the specific shared preferences
    SharedPreferences.Editor taskEditor=taskPref.edit();

    //add new task -> if true write 1 else write 0
    if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }

}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    SharedPreferences.Editor tskEditor=taskPref.edit();
        tskEditor.clear();
        tskEditor.commit();

}

}

This method is called from my Welcome class which is

public class Welcome extends AppCompatActivity {

String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;

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

}

private void setPointer()
{

    this.context=this;
    userName=getIntent().getStringExtra("userName");
    myUtl = new utlShared(context);
    taskList=(ListView)findViewById(R.id.taskList);
    setListData();
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
    Button btnBack = (Button)findViewById(R.id.btnBack);
    FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
            setListData();
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, MainActivity.class);
            startActivity(intent);
            finish();
        }
    });

}

private void setListData() {
    final TaskAdapter adapter = new TaskAdapter(context, userName);
    taskList.setAdapter(adapter);
}

public void addCustomTask(View view)
{
    //create builder
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    //set title
    builder.setTitle("Add new task!");

    //inflate view from layout ->custom layout,null,false as defualt values
    View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);

    final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
    final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

    builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

            String myTaskCustom = txtCustomTask.getText().toString();
            String myTaskLine = txtCustomLine.getText().toString();
                myUtl.task(userName, myTaskCustom, myTaskLine, false);
                setListData();
        }
    });

    //display our inflated view in screen
    builder.setView(viewInflated);
    //show the dialog
    builder.show();

}

}

Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...

Thanks in advance guys, much appreciated!


问:
Using Bootstrap Panel - How do I put form next to title?
I have tried at least three proposed solutions from searching on this site, but nothing worked. I got close, but was getting cheated on the panel defeault backround color. For some reason, the background wasn't showing its full height behind my elements. I want to put a form next to the heading. Here is what I have tried.

```<code><div class="panel panel-default">
    <div class="panel-heading">

      <div class="no-wrap">
        <h3 class="panel-title">My Title</h3>
      </div>

      <div class="no-wrap">
          <form>
            <div class="form-group">
              <select class="form-control" id="sel1">
              <option>1</option>
              <option>2</option>
              </select>
            </div>
          </form>
      </div>

</div> <!-- end panel-heading -->

<div class="panel-body">
    Body Text
</div>

</div> <!-- end panel -->
</code>```

All the class you see are bootstrap EXCEPT no-wrap. My css for no-wrap is

```<code>.no-wrap {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
 }
</code>```

So this was my most hopeful solution but it still doesn't work. The form sits below the h3.

I also tried using bootstrap columns inside the panel heading, but that's when the default gray background got obscured.

How can I get this form next to the h3 - all inside the panel heading?? Please note, you can assume that there is plenty of screen width. 99.9% of users will be using a laptop to access this page. The panel is being used to display business reports. Mobile responsiveness is not a priority.

Below is screenshot of what I do NOT want. I want the input form next to the heading.

答:
Use display: flex;

Demo jsfiddle

Body:
I have tried at least three proposed solutions from searching on this site, but nothing worked. I got close, but was getting cheated on the panel defeault backround color. For some reason, the background wasn't showing its full height behind my elements. I want to put a form next to the heading. Here is what I have tried.

My Title

          <form>

              <select class="form-control" id="sel1">
              <option>1</option>
              <option>2</option>
              </select>

          </form>

    Body Text

All the class you see are bootstrap EXCEPT no-wrap. My css for no-wrap is

.no-wrap {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
 }

So this was my most hopeful solution but it still doesn't work. The form sits below the h3.

I also tried using bootstrap columns inside the panel heading, but that's when the default gray background got obscured.

How can I get this form next to the h3 - all inside the panel heading?? Please note, you can assume that there is plenty of screen width. 99.9% of users will be using a laptop to access this page. The panel is being used to display business reports. Mobile responsiveness is not a priority.

Below is screenshot of what I do NOT want. I want the input form next to the heading.

Body:
Use display: flex;

Demo jsfiddle


问:
C#: DataTable getting only one row of the search result
I'm having a sudden and strange problem with DataTable. I'm using C# with MySQL database to develop a system, and I'm trying to export custom reports. The problem is that, somehow, my DataTable is getting only one result (I've tested my query on MySQL and should be something like 30 results on the xls file and the DataTable).
Strangely, these functions are used in other parts of the system to export other kinds of reports, and work perfectly. This is the select function that I'm using:

```<code>public DataTable selectBD(String tabela, String colunas) {
    var query = "SELECT " + colunas + " FROM " + tabela;
    var dt = new DataTable();

    Console.WriteLine("\n\n" + query + "\n\n");

    try
    {
        using (var command = new MySqlCommand(query, bdConn)) {
            MySqlDataReader reader = command.ExecuteReader();
            dt.Load(reader);
            reader.Close();
        }
    }
    catch (MySqlException) {
        return null;
    }
    bdConn.Close();

    return dt;
}
</code>```

And this is my query:

```<code>SELECT
    cpf_cnpj, nomeCliente, agenciaContrato, contaContrato,
    regionalContrato, carteiraContrato, contratoContrato,
    gcpjContrato, avalistaContrato, enderecoContrato,
    telefoneContrato, dataChegadaContrato, dataFatoGerContrato,
    dataPrimeiraParcelaContrato, dataEmissaoContrato, valorPlanilhaDebitoContrato
FROM
    precadastro
    INNER JOIN
    contrato
        ON precadastro.cpf_cnpj = contrato.FK_cpf_cnpj
    LEFT JOIN faseprocessual
        ON contrato.idContrato = faseprocessual.FK_idContrato
</code>```

And that is the result of the query on SQLyog

I've tested and the DataTable returned by the function only receive the one row, and it's not the first row of the MySQL results. Someone had this kind of problem before?

答:
DataTable load expects primary key from your data (supplied by DataReader) and tries to guess it from passed rows. Since there's no such key, Load method guesses it's the first column (cpf_cnpj). But, values in that column aren't unique so the each row gets overwritten by next one, and the result is just one row in your DataTable.
It's the issue that persist for years, and I'm not sure there's one solution to rule them all. :)

You can try:

change query so that some unique values get into first column (unfortunately, I can't see something unique in your screenshot) or concatenate two or more values to get unique value.

Prepare DataTable by yourself by creating columns (this mirroring structure of resultset) and then iterate through DataReader to copy data.

add some autoincrement value in your query (or make temporary table with auto_increment column then fill that table)

Last suggestion could be something like this (I haven't worked much with mySql, so this is some suggestion i have googled :)):

```<code>SELECT
    @i:=@i+1 AS id,
    cpf_cnpj, nomeCliente, agenciaContrato, contaContrato,
    regionalContrato, carteiraContrato, contratoContrato,
    gcpjContrato, avalistaContrato, enderecoContrato,
    telefoneContrato, dataChegadaContrato, dataFatoGerContrato,
    dataPrimeiraParcelaContrato, dataEmissaoContrato, valorPlanilhaDebitoContrato
FROM
    precadastro
    INNER JOIN
    contrato
        ON precadastro.cpf_cnpj = contrato.FK_cpf_cnpj
    LEFT JOIN faseprocessual
        ON contrato.idContrato = faseprocessual.FK_idContrato
    CROSS JOIN (SELECT @i:= 0) AS i
</code>```

here's answer on SO which uses auto number in query.

Body:
I'm having a sudden and strange problem with DataTable. I'm using C# with MySQL database to develop a system, and I'm trying to export custom reports. The problem is that, somehow, my DataTable is getting only one result (I've tested my query on MySQL and should be something like 30 results on the xls file and the DataTable).
Strangely, these functions are used in other parts of the system to export other kinds of reports, and work perfectly. This is the select function that I'm using:

public DataTable selectBD(String tabela, String colunas) {
    var query = "SELECT " + colunas + " FROM " + tabela;
    var dt = new DataTable();

    Console.WriteLine("\n\n" + query + "\n\n");

    try
    {
        using (var command = new MySqlCommand(query, bdConn)) {
            MySqlDataReader reader = command.ExecuteReader();
            dt.Load(reader);
            reader.Close();
        }
    }
    catch (MySqlException) {
        return null;
    }
    bdConn.Close();

    return dt;
}

And this is my query:

SELECT
    cpf_cnpj, nomeCliente, agenciaContrato, contaContrato,
    regionalContrato, carteiraContrato, contratoContrato,
    gcpjContrato, avalistaContrato, enderecoContrato,
    telefoneContrato, dataChegadaContrato, dataFatoGerContrato,
    dataPrimeiraParcelaContrato, dataEmissaoContrato, valorPlanilhaDebitoContrato
FROM
    precadastro
    INNER JOIN
    contrato
        ON precadastro.cpf_cnpj = contrato.FK_cpf_cnpj
    LEFT JOIN faseprocessual
        ON contrato.idContrato = faseprocessual.FK_idContrato

And that is the result of the query on SQLyog

I've tested and the DataTable returned by the function only receive the one row, and it's not the first row of the MySQL results. Someone had this kind of problem before?

Body:
DataTable load expects primary key from your data (supplied by DataReader) and tries to guess it from passed rows. Since there's no such key, Load method guesses it's the first column (cpf_cnpj). But, values in that column aren't unique so the each row gets overwritten by next one, and the result is just one row in your DataTable.
It's the issue that persist for years, and I'm not sure there's one solution to rule them all. :)

You can try:

change query so that some unique values get into first column (unfortunately, I can't see something unique in your screenshot) or concatenate two or more values to get unique value.

Prepare DataTable by yourself by creating columns (this mirroring structure of resultset) and then iterate through DataReader to copy data.

add some autoincrement value in your query (or make temporary table with auto_increment column then fill that table)

Last suggestion could be something like this (I haven't worked much with mySql, so this is some suggestion i have googled :)):

SELECT
    @i:=@i+1 AS id,
    cpf_cnpj, nomeCliente, agenciaContrato, contaContrato,
    regionalContrato, carteiraContrato, contratoContrato,
    gcpjContrato, avalistaContrato, enderecoContrato,
    telefoneContrato, dataChegadaContrato, dataFatoGerContrato,
    dataPrimeiraParcelaContrato, dataEmissaoContrato, valorPlanilhaDebitoContrato
FROM
    precadastro
    INNER JOIN
    contrato
        ON precadastro.cpf_cnpj = contrato.FK_cpf_cnpj
    LEFT JOIN faseprocessual
        ON contrato.idContrato = faseprocessual.FK_idContrato
    CROSS JOIN (SELECT @i:= 0) AS i

here's answer on SO which uses auto number in query.


问:
border-radius for circle left and right with unequal width and height and variable height
This is what I'm trying to achieve:

As width and height are not equal setting border-radius:50% gives an oval which is not what I meant to achieve.
Giving fixed size (like border-radius:20px) would work if the height was fixed but how can I get this to work with variable height?

答:
Just set the border-radius to 360px or higher:

    div {
      height:80px;
      width:400px;
      border-radius:360px;
      border:2px solid #333;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
</div></code>```

This way you will always have perfectly rounded corners.

source: link

Body:
Just set the border-radius to 360px or higher:

    div {
      height:80px;
      width:400px;
      border-radius:360px;
      border:2px solid #333;
    }

<div>
</div>

This way you will always have perfectly rounded corners.

source: link


问:
No such module PDKClient with Cocoapods
I have installed the Pinterest SDK with cocoapods successfully, but when I try to import PDKClient, it says "No such module PDKClient".

My podfile:

```<code>target 'MyPin3' do
pod "PinterestSDK", :git => "https://github.com/pinterest/ios-pdk.git"
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!

# Pods for MyPin3

end
</code>```

I definitely have my xcworkspace open and I have tried clean + build. I've looked up some other Stack Overflow answers (tried deleting framework search paths, etc.) with no luck.

Any help would be appreciated. Thank you.

答:
Rather than PDKClient, you should be importing PinterestSDK. Try this line and it should work:

```<code>import PinterestSDK
</code>```

Title: No such module PDKClient with Cocoapods

Body:
I have installed the Pinterest SDK with cocoapods successfully, but when I try to import PDKClient, it says "No such module PDKClient".

My podfile:

target 'MyPin3' do
pod "PinterestSDK", :git => "https://github.com/pinterest/ios-pdk.git"
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!

# Pods for MyPin3

end

I definitely have my xcworkspace open and I have tried clean + build. I've looked up some other Stack Overflow answers (tried deleting framework search paths, etc.) with no luck.

Any help would be appreciated. Thank you.

Body:
Rather than PDKClient, you should be importing PinterestSDK. Try this line and it should work:

import PinterestSDK


问:
Entries in .java.policy ignored
I'm developing a JAVA Applet that requires read and write access to a folder. When I add the following entry into the java.policy file within the JRE folder it works:

```<code> permission java.io.FilePermission "${user.home}${/}logtest${/}-", "read, write";
</code>```

However if I add the entry in the .java.policy file within the users home directory it does not work.

Investigating further I add another policy file mytest.policy containing the exact same permission above and modified java.security file with:

```<code>policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy
policy.url.3=file:${user.home}/mytest.policy
</code>```

The permissions are successfully applied.

Does anyone know why .java.policy permission entries don't work?

答:
Try to edit file
C:\Users\USERNAME\AppData\LocalLow\Sun\Java\Deployment\deployment.properties
and add to file next line:
deployment.security.use.user.home.java.policy=true</p>

Title: Entries in .java.policy ignored

Body:
I'm developing a JAVA Applet that requires read and write access to a folder. When I add the following entry into the java.policy file within the JRE folder it works:

 permission java.io.FilePermission "${user.home}${/}logtest${/}-", "read, write";

However if I add the entry in the .java.policy file within the users home directory it does not work.

Investigating further I add another policy file mytest.policy containing the exact same permission above and modified java.security file with:

policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy
policy.url.3=file:${user.home}/mytest.policy

The permissions are successfully applied.

Does anyone know why .java.policy permission entries don't work?


问:
Set a label on a marker with iOS map links api
I'm trying to set a label on a map marker using the map links api. According to apple's docs if I use the 'q' param with the 'address' param it will take the 'q' param as a label. But I can't make it to work.

Blockquote
  The q parameter can also be used as a label if the location is explicitly defined in the ll or address parameters docs.

This is the url I've tried

```<code>http://maps.apple.com/?address=San+Jose&q=Blah
</code>```

I want it to say 'Blah' as the marker's label.

Thanks.

答:
I just ran into this issue and submitted a bug report to Apple. According to their docs, the combination of the q and address parameters should set the marker label to the value of q.

In the meantime, you can get this working by using the ll parameter:

http://maps.apple.com/?q=Blah&ll=34.0836834,-118.3468481

More on the ll parameter:

A comma-separated pair of floating point values that represent latitude and longitude (in that order).

https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html#//apple_ref/doc/uid/TP40007899-CH5-SW1

Body:
I'm trying to set a label on a map marker using the map links api. According to apple's docs if I use the 'q' param with the 'address' param it will take the 'q' param as a label. But I can't make it to work.

Blockquote
  The q parameter can also be used as a label if the location is explicitly defined in the ll or address parameters docs.

This is the url I've tried

http://maps.apple.com/?address=San+Jose&q=Blah

I want it to say 'Blah' as the marker's label.

Thanks.


问:
docker-compose scale does not work with haproxy
I'm playing around with docker-compose haproxy and nginx.
What I'm trying to accomplish is that if I scale the nginx container to be

docker-compose scale nginx=2

the haproxy container also proxies the new nginx container. But somehow its not recognizing the new container.

Here are my configs:

docker-compose.yml:

```<code>version: '2.1'
services:

  nginx:
    image: 'bitnami/nginx:latest'
    healthcheck:
      test: "curl -f http://localhost/?healthcheck"
    expose:
      - "80"

  haproxy:
    image: haproxy
    restart: always
    depends_on:
      nginx:
        condition: service_healthy
    links:
      - nginx
    ports:
      - "80:80"
    volumes:
      - ./haproxy:/usr/local/etc/haproxy/
    expose:
      - "80"
</code>```

haproxy.cfg

```<code>global
  log 127.0.0.1 local0
  log 127.0.0.1 local1 notice

defaults
  log global
  mode http
  option httplog
  timeout connect 5000
  timeout client 10000
  timeout server 10000

frontend localnodes
  bind 0.0.0.0:80
  mode http
  default_backend nodes

backend nodes
  mode http
  option forwardfor
  balance roundrobin
  server nginx nginx:80 check
  option httpchk GET /?haproxyselfcheck
  http-check expect status 200
</code>```

What could I do to get haproxy to recognize the new container without just adding one more nginx into docker-compose file manually?

答:
After doing some reasearch I found a solution to work with docker swarm.
Docker swarm has its own load-balancer. But to reverse proxy to the services best fit seemed to be docker-flow-proxy from the legendary Victor Farcic https://github.com/vfarcic/docker-flow-proxy

One can then just add the new services to the proxy.

Body:
I'm playing around with docker-compose haproxy and nginx.
What I'm trying to accomplish is that if I scale the nginx container to be

docker-compose scale nginx=2

the haproxy container also proxies the new nginx container. But somehow its not recognizing the new container.

Here are my configs:

docker-compose.yml:

version: '2.1'
services:

  nginx:
    image: 'bitnami/nginx:latest'
    healthcheck:
      test: "curl -f http://localhost/?healthcheck"
    expose:
      - "80"

  haproxy:
    image: haproxy
    restart: always
    depends_on:
      nginx:
        condition: service_healthy
    links:
      - nginx
    ports:
      - "80:80"
    volumes:
      - ./haproxy:/usr/local/etc/haproxy/
    expose:
      - "80"

haproxy.cfg

global
  log 127.0.0.1 local0
  log 127.0.0.1 local1 notice

defaults
  log global
  mode http
  option httplog
  timeout connect 5000
  timeout client 10000
  timeout server 10000

frontend localnodes
  bind 0.0.0.0:80
  mode http
  default_backend nodes

backend nodes
  mode http
  option forwardfor
  balance roundrobin
  server nginx nginx:80 check
  option httpchk GET /?haproxyselfcheck
  http-check expect status 200

What could I do to get haproxy to recognize the new container without just adding one more nginx into docker-compose file manually?


问:
How do I get a list of connected sockets/clients with Socket.IO?
I'm trying to get a list of all the sockets/clients that are currently connected.

io.sockets does not return an array, unfortunately.

I know I could keep my own list using an array, but I don't think this is an optimal solution for two reasons:

Redundancy. Socket.IO already keeps a copy of this list.

Socket.IO provides method to set arbitrary field values for clients (i.e: socket.set('nickname', 'superman')), so I'd need to keep up with these changes if I were to maintain my own list.

What should I do?

答:
If the project has a socket.io cluster this means the socket.io-redis adapter is being used.

If the case is like the above, getting the all connected sockets id processes must be applied via the socket.io-redis adapter. The examples below might be used for this;

```<code>io.of('/').adapter.clients(function (err, clients) {
  console.log("clients: ", clients); // an array containing all connected socket ids
});

io.of('/').adapter.allRooms(function (err, rooms) {
  console.log("all rooms: ", rooms);
});
</code>```

Please visit socket.io-redis github page for more details.

Body:
If the project has a socket.io cluster this means the socket.io-redis adapter is being used.

If the case is like the above, getting the all connected sockets id processes must be applied via the socket.io-redis adapter. The examples below might be used for this;

io.of('/').adapter.clients(function (err, clients) {
  console.log("clients: ", clients); // an array containing all connected socket ids
});

io.of('/').adapter.allRooms(function (err, rooms) {
  console.log("all rooms: ", rooms);
});

Please visit socket.io-redis github page for more details.