问:
Ionic ng-repeat returning one undefined
I am attempting to filter a list of items the code below worded fine in angular js on the web but we can't expect Ionic to work now can we?

```<code><ion-list *ngIf="items.length">
      {{items[0].title}}
      <ion-item ng-repeat="item in items | filter:searchLog">
        {{item == undefined}}
        <!--<ion-icon name="clipboard" item-left></ion-icon>
        <h2><b>Title: {{item.title}}</b></h2>
        <h3><b>Caller: {{item.caller.name}} - {{item.caller.number}}</b></h3>
        <h3><b>Location: {{item.caller.location}}</b></h3>
        <h3><i>Dispatcher: </i>{{item.dispatcher.name}} at {{item.timeStamp}}</h3>
        <h3><b>Dropped: {{item.canceled}}</b></h3>
        <h3 style="white-space: normal;"><i>Details:</i> {{item.details}}</h3>-->
      </ion-item>
    </ion-list>
</code>```

This is what my screen shows:

```<code>car out of gas

true
</code>```

For the life of me I cannot understand this because if I print {{ items[0].title }} it works fine in the repeat list meaning that it is not giving me this item object back from the ng-repeat call. What is even weirder is that *ngFor works but I cannot filter it :-( Please help

TL;DR: ng-repeat in angular is returning one undefined object.

答:
Use *ngFor with pipe (i.e. filter). If it is still not working then there is some problem with your pipe (filter). Code should look like below:

```<code><ion-list *ngIf="items.length">
      {{items[0].title}}

     <ion-item *ngFor="let item of items | searchLog">

        <ion-icon name="clipboard" item-left></ion-icon>
        <h2><b>Title: {{item.title}}</b></h2>
        <h3><b>Caller: {{item.caller.name}} - {{item.caller.number}}</b></h3>
        <h3><b>Location: {{item.caller.location}}</b></h3>
        <h3><i>Dispatcher: </i>{{item.dispatcher.name}} at {{item.timeStamp}}</h3>
        <h3><b>Dropped: {{item.canceled}}</b></h3>
        <h3 style="white-space: normal;"><i>Details:</i> {{item.details}}</h3>
    </ion-item>
</ion-list>
</code>```

Title: Ionic ng-repeat returning one undefined

Body:
I am attempting to filter a list of items the code below worded fine in angular js on the web but we can't expect Ionic to work now can we?

<ion-list *ngIf="items.length">
      {{items[0].title}}
      <ion-item ng-repeat="item in items | filter:searchLog">
        {{item == undefined}}

      </ion-item>
    </ion-list>

This is what my screen shows:

car out of gas

true

For the life of me I cannot understand this because if I print {{ items[0].title }} it works fine in the repeat list meaning that it is not giving me this item object back from the ng-repeat call. What is even weirder is that *ngFor works but I cannot filter it :-( Please help

TL;DR: ng-repeat in angular is returning one undefined object.

Body:
Use *ngFor with pipe (i.e. filter). If it is still not working then there is some problem with your pipe (filter). Code should look like below:

<ion-list *ngIf="items.length">
      {{items[0].title}}

     <ion-item *ngFor="let item of items | searchLog">

        <ion-icon name="clipboard" item-left></ion-icon>
        <h2><b>Title: {{item.title}}</b></h2>
        <h3><b>Caller: {{item.caller.name}} - {{item.caller.number}}</b></h3>
        <h3><b>Location: {{item.caller.location}}</b></h3>
        <h3><i>Dispatcher: </i>{{item.dispatcher.name}} at {{item.timeStamp}}</h3>
        <h3><b>Dropped: {{item.canceled}}</b></h3>
        <h3 style="white-space: normal;"><i>Details:</i> {{item.details}}</h3>
    </ion-item>
</ion-list>


来源: stackexchange

问:
How to convert this python code to Javascript
I don't want to run the Python code inside Javascript, I want to turn it completely into JS code. I have no idea about python, Can body can help me on this. Thank you. </p>

```<code>print ("Please input the # of books you've read this year")
BooksAlready=int(input())
print ("Please input the # of weeks that have already passed this year")
WeeksAlready=int(input())
x=(78/52)
c=x*WeeksAlready-BooksAlready
if (BooksAlready/WeeksAlready)>x:
  print ("You're on point, go have some fun!")
else:
  print ("Go read, you piece of uneducated crap")
  print ("You have")
  print (c)
  print ("books left to read this week to get on point")
</code>```

答:
Please check below links to know more about converters from python to js.

http://www.infoworld.com/article/3033047/javascript/4-tools-to-convert-python-to-javascript-and-back-again.html

ContentLicense: CC BY-SA 3.0

Body:
I don't want to run the Python code inside Javascript, I want to turn it completely into JS code. I have no idea about python, Can body can help me on this. Thank you.

print ("Please input the # of books you've read this year")
BooksAlready=int(input())
print ("Please input the # of weeks that have already passed this year")
WeeksAlready=int(input())
x=(78/52)
c=x*WeeksAlready-BooksAlready
if (BooksAlready/WeeksAlready)>x:
  print ("You're on point, go have some fun!")
else:
  print ("Go read, you piece of uneducated crap")
  print ("You have")
  print (c)
  print ("books left to read this week to get on point")

ContentLicense: CC BY-SA 4.0


问:
Registering asp:button click event handler
I have multiple asp:button that I created dynamically with jQuery.

For each of them, I have OnClick="ibtn_Click" .

But on the code behind, I have to manually register each one of them on Page_Load..like.. button.Click += new EventHandler(this.ibtn_Click); .

Is there a way I can register this handler automatically? Or is it possible to register it with ajax jquery?

Thanks!

答:
You can't add ASP.NET web controls in the client's browser. ASP.NET transforms those <asp:button> tags into regular HTML, something like this:

```<code><input type="submit" name="Button1" value="Ok" id="Button1" />
</code>```

When a user clicks one of these submit controls, the browser sends a POST request, which includes the button's name as part of the posted data (which you can access via the Form collection in ASP.NET):

```<code>if (this.IsPostBack && Request.Form["Button1"] != null) {
    // do something if the user clicked Button1
}
</code>```

ASP.NET automatically binds server control clicks to the methods specified in the OnClick attribute. It calls the method after Page.Load completes (for the gory details, see "ASP.NET Page Life Cycle Overview").

If you're adding the buttons on the client, you can do all this yourself. For example you could "bind" the dynamically generated button in Page_PreRender:

```<code>protected void Page_PreRender(object sender, EventArgs e) {
    if (this.IsPostBack && Request.Form["Button1"] != null) {
        // Call another method on the page
    }
}
</code>```

Finally, in this day and age, if it's appropriate, you should definitely consider just calling page methods via jQuery's ajax. See this excellent Encosia article for an introduction to that technique.

ContentLicense: CC BY-SA 2.5

Body:
You can't add ASP.NET web controls in the client's browser. ASP.NET transforms those <asp:button> tags into regular HTML, something like this:

<input type="submit" name="Button1" value="Ok" id="Button1" />

When a user clicks one of these submit controls, the browser sends a POST request, which includes the button's name as part of the posted data (which you can access via the Form collection in ASP.NET):

if (this.IsPostBack && Request.Form["Button1"] != null) {
    // do something if the user clicked Button1
}

ASP.NET automatically binds server control clicks to the methods specified in the OnClick attribute. It calls the method after Page.Load completes (for the gory details, see "ASP.NET Page Life Cycle Overview").

If you're adding the buttons on the client, you can do all this yourself. For example you could "bind" the dynamically generated button in Page_PreRender:

protected void Page_PreRender(object sender, EventArgs e) {
    if (this.IsPostBack && Request.Form["Button1"] != null) {
        // Call another method on the page
    }
}

Finally, in this day and age, if it's appropriate, you should definitely consider just calling page methods via jQuery's ajax. See this excellent Encosia article for an introduction to that technique.


问:
Testflight internal tester installed app exceeds 10 device limit
Apple clearly mentioned on their page here

"Each app can be tested by up to 25 members of your team who have been assigned the Developer or Admin role in iTunes Connect. Each member can test on up to 10 devices."

But surprisingly one of our internal testers invited to test 2 apps. He installed the First app in 3 devices.

But the second app he is able to install in 11 devices.

Can anyone please tell me what exactly limits and constraints of test flight internal tester?

Here is the Tester Profile:

答: You're right, according to Apple, you can install in up to 10 devices. I think that maybe he installed the app twice in the same device</p>


问:
How to combine hash in PHP
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

```<code>checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345
</code>```

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

答:
Just invoke openssl with system() or exec()

```<code><?php
$checksum = system( "openssl dgst -sha256 -binary hash12" );
?>
</code>```

Title: How to combine hash in PHP

Body:
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

Body:
Just invoke openssl with system() or exec()

<?php
$checksum = system( "openssl dgst -sha256 -binary hash12" );
?>


问:
Phone Number not echoing fully in HTML Form
I'm simply echoing a user's info in an HTML form as "value=". Everything is working perfectly except the phone number. Here is my current code:

```<code> <div class="sign-in-btn">
            <input type="phoneNumber" data-mask="(000) 000-0000" name='User_phonenumber' id='User_phonenumber' value=<?php echo $phone;?> />
          </div>
</code>```

Only the area code appears - ie (908). The phone number is formatted in the db as (xxx) xxx-xxxx.

I feel it has something to do with the form because it echos perfectly when done outside the form. For example, the full number (with formatting) echos perfectly in this :

```<code><h3 class="sign-in-header">Your phone number is <?php echo $phone;?> </h3>
</code>```

Steps I've taken:

removed "type" in the form attributes - no success

removed "data-type" in the form - no success

echoed $phone in other form fields (first name, etc) - same issue.

Any ideas guys and gals?!

Thanks!!

答:
your problem is here this

```<code>value=<?php echo $phone;?>
</code>```

should be

```<code>value="<?php echo $phone;?>"
</code>```

you forgot the quotes

Body:
I'm simply echoing a user's info in an HTML form as "value=". Everything is working perfectly except the phone number. Here is my current code:

            <input type="phoneNumber" data-mask="(000) 000-0000" name='User_phonenumber' id='User_phonenumber' value=<?php echo $phone;?> />

Only the area code appears - ie (908). The phone number is formatted in the db as (xxx) xxx-xxxx.

I feel it has something to do with the form because it echos perfectly when done outside the form. For example, the full number (with formatting) echos perfectly in this :

Your phone number is <?php echo $phone;?>

Steps I've taken:

removed "type" in the form attributes - no success

removed "data-type" in the form - no success

echoed $phone in other form fields (first name, etc) - same issue.

Any ideas guys and gals?!

Thanks!!

Body:
your problem is here this

value=<?php echo $phone;?>

should be

value="<?php echo $phone;?>"

you forgot the quotes


问:
modified coin toss program won't run
So I have to complete an assignment in which a coin toss is simulated and the number of flips, tails, and heads must be counted.

My first problem was that I could not get the number of heads or tails to display, fixed that, but then it was doubling(ex: I request 50 flips and the total amount of heads and tails would equate to 100), figured out that I had accidentally made it so it was counting up twice instead of once per flip, when I changed that the program just doesn't seem to run.

When I input the amount of times I would like the coin to flip and hit enter it just does nothing and goes to the next line on my terminal. I have removed all white space off my program in case of infinite looping other than that I cannot figure out what is causing this.

Thank you for any help.

答:
The issue is that you increment your count variable, alongside your head and tails counts. So you are in a while loop aiming for a moving target. I am not attempting to compete with Ravi for the accepted answer, but here is a simplified version of your code.

You needn't use a while loop, as you know how many iterations you will do. In this case a for loop is the appropriate tool.

```<code>from random import choice

heads = tails = 0
count = int(input('how many flips? '))

for _ in range(count):
    if choice([True, False]):
        heads += 1
    else:
        tails += 1

print('you flipped %d times' % count)
print('you flipped %d heads and %d tails' % (heads, tails))
</code>```

Title: modified coin toss program won't run

Body:
The issue is that you increment your count variable, alongside your head and tails counts. So you are in a while loop aiming for a moving target. I am not attempting to compete with Ravi for the accepted answer, but here is a simplified version of your code.

You needn't use a while loop, as you know how many iterations you will do. In this case a for loop is the appropriate tool.

from random import choice

heads = tails = 0
count = int(input('how many flips? '))

for _ in range(count):
    if choice([True, False]):
        heads += 1
    else:
        tails += 1

print('you flipped %d times' % count)
print('you flipped %d heads and %d tails' % (heads, tails))


问:
What is the Regex for decimal numbers in Java?
I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

```<code>String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";
</code>```

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

```<code>String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());
</code>```

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.

答: There are actually 2 ways to match a literal .. One is using backslash-escaping like you do there \\., and the other way is to enclose it inside a character class  or the square brackets like [.]. Most of the special characters become literal characters inside the square brackets including .. So use \\. shows your intention clearer than [.] if all you want is to match a literal dot .. Use [] if you need to match multiple things which represents match this or that for example this regex [\\d.] means match a single digit or a literal dot

Body:
I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.


问:
artisan migrate command doesn't migrate, produces no output
I am working on my first Laravel project. I'm trying to create database migrations and run them with artisan migrate. The migrations aren't running and the command returns no output.

Key facts:

I used artisan make:migration to create the migration file with the proper filepath.

The first time I ran the command, it created the migration table in the database. So I know that it is hitting the database and at least doing something right.

When I have no files in the database/migrations folder, I get the Nothing to migrate command.

Beyond these two messages, I have received no output at all from the command. No errors, nothing. Furthermore, there are no records in the migration table in the database.

artisan migrate --verbose also returns no output.

The permissions on storage/logs is drwxrwxrwx. I am the owner of the directory.

storage/logs/laravel.log doesn't contain anything pertaining to the migrations.

I've included the code for my first migration below.

This question is different from this question in that the previous user didn't use the proper naming convention. That question contains a detailed answer about the migration process. It's not helpful because I'm not getting any output. I also reviewed the questions suggested by SO as I entered this question.

Perhaps I have something configured incorrectly? What do I need to do to get these migrations running?

2017_01_17_151638_user.php

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

// Create the classes associated with user management.

class UserMigration extends Migration
{
    public function up()
    {
      Schema::create('tblUser', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->string('email')->unique();
          $table->string('password');
          $table->rememberToken();
          $table->timestamps();
      });

      Schema::create('tblUserPasswordReset', function (Blueprint $table) {
          $table->string('email')->index();
          $table->string('token')->index();
          $table->timestamp('create_date')->nullable();
      });
    }

    public function down()
    {
      Schema::dropIfExists('tblUserPasswordReset');
      Schema::dropIfExists('tblUser');
    }
}
</code>```

答:
Had this exact problem with none of the listed solutions changing anything. The unmentioned solution that works in this case for me was </p>

```<code>composer update --no-scripts
</code>```

<p>I had wiped out everything and was starting from scratch, forgot to re init composer and install everything. </p>

Body:
I am working on my first Laravel project. I'm trying to create database migrations and run them with artisan migrate. The migrations aren't running and the command returns no output.

Key facts:

I used artisan make:migration to create the migration file with the proper filepath.

The first time I ran the command, it created the migration table in the database. So I know that it is hitting the database and at least doing something right.

When I have no files in the database/migrations folder, I get the Nothing to migrate command.

Beyond these two messages, I have received no output at all from the command. No errors, nothing. Furthermore, there are no records in the migration table in the database.

artisan migrate --verbose also returns no output.

The permissions on storage/logs is drwxrwxrwx. I am the owner of the directory.

storage/logs/laravel.log doesn't contain anything pertaining to the migrations.

I've included the code for my first migration below.

This question is different from this question in that the previous user didn't use the proper naming convention. That question contains a detailed answer about the migration process. It's not helpful because I'm not getting any output. I also reviewed the questions suggested by SO as I entered this question.

Perhaps I have something configured incorrectly? What do I need to do to get these migrations running?

2017_01_17_151638_user.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

// Create the classes associated with user management.

class UserMigration extends Migration
{
    public function up()
    {
      Schema::create('tblUser', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->string('email')->unique();
          $table->string('password');
          $table->rememberToken();
          $table->timestamps();
      });

      Schema::create('tblUserPasswordReset', function (Blueprint $table) {
          $table->string('email')->index();
          $table->string('token')->index();
          $table->timestamp('create_date')->nullable();
      });
    }

    public function down()
    {
      Schema::dropIfExists('tblUserPasswordReset');
      Schema::dropIfExists('tblUser');
    }
}

Body:
Had this exact problem with none of the listed solutions changing anything. The unmentioned solution that works in this case for me was

composer update --no-scripts

I had wiped out everything and was starting from scratch, forgot to re init composer and install everything.


问:
HyperV VMs in BackingUp status during R1Soft Backup task run time
I have a HyperV installed on windows server 2016. VMs are created and running successfully. Setup a R1soft policy in my Backup server to backup the entire image of HyperV server which includes the disk drive stores vhdx files of VMs.

Now my problem is when the r1soft policy rans, all VMs in the server will be backing up stage, and I am not able to manage VMs (like start,stop etc) during the period of r1soft backup task runs. backing up status will only change to normal either backup task completes or cancel the backup task.

Any idea why this behavior happening?.  When I googled the same, I see comments like it may related to enabled volume shadow copy of disk or hypverV integration service or due to volume shadow copy service requester service.

But not sure what exactly need to be checked.  Any valuable comments will be much appreciated.

答:
What worked for me as a work around was to restart hyper v virtual Machine management service from services.msc

If the service went to mode stopping I kill the pid by issuing the command:

```<code>sc queryex vmms : note pid

taskkill /f /pid pidnumber from above command
</code>```

Then start the service hyper v virtual Machine management.

Body:
What worked for me as a work around was to restart hyper v virtual Machine management service from services.msc

If the service went to mode stopping I kill the pid by issuing the command:

sc queryex vmms : note pid

taskkill /f /pid pidnumber from above command

Then start the service hyper v virtual Machine management.


问:
"Jmeter - Cannot record Facebook/Messenger - 501 method not implemented"
I want to record some talk on Facebook Messenger to measure the response time, but i when i'm using HTTP Recorder with Proxy on Facebook, this error appears:

501 Method not implemented

Service not implemented. Probably used https instead of http. To
  record https requests, see HTTP(S) Test Script Recorder documentation

I already installed the JMeter certificate and i don't know what i can do to record something on Facebook.

Thanks for the help

答:
If you are trying to record scripts on mobile Facebook messenger in Jmeter, you can try blazemeter recorder.

Blazemeter script recorder

Hope this helps you..


问:
SQL, combine two aggregates of same table
I have the following table, which contains number of operations performed by operator of a specific department in a specific date for each target_type. sum1 and sum2 are the number of operation 1 and operation 2 on the specific day, the interpretation of operations in question is indicated by the operation_type column.

```<code>statistic_id | department | operator | operation_type | target_type | sum1 | sum2 | date |
</code>```

I would query the table to collect statistics for operation_type 1 on a department 1 in a specific time period grouped by operator and operation_type as follows

```<code>SELECT operator, target_type, SUM(sum1) AS op1, SUM(sum2) AS op2 FROM statistics
WHERE
  department = 1 AND
  operation_type = 1 AND
  (date BETWEEN in_start_date AND in_end_date)
GROUP BY operator, target_type
ORDER BY operator, target_type;
</code>```

As well, I would query the table to collect statistics for operation_type 2 on the same department and time interval grouped by the same criteria

```<code>SELECT operator, target_type, SUM(sum1) AS op3, SUM(sum2) AS op4 FROM statistics
WHERE
  department = 1 AND
  operation_type = 2 AND
  (date BETWEEN in_start_date AND in_end_date)
GROUP BY operator, target_type
ORDER BY operator, target_type;
</code>```

I would like to combine the query results, so I would get result like

```<code>operator | target_type | op1 | op2 | op3 | op4
</code>```

How do I join the table with itself via aggregating different columns based on some common and some diverse criteria, yet grouping by the same set of columns?

答:
Use conditional aggregation in your sums:

```<code>SELECT operator,
       target_type,
       SUM(CASE WHEN operation_type = 1 THEN sum1 ELSE 0 END) AS op1,
       SUM(CASE WHEN operation_type = 1 THEN sum2 ELSE 0 END) AS op2,
       SUM(CASE WHEN operation_type = 2 THEN sum1 ELSE 0 END) AS op3,
       SUM(CASE WHEN operation_type = 2 THEN sum2 ELSE 0 END) AS op4
FROM statistics
WHERE department = 1 AND
      date BETWEEN in_start_date AND in_end_date
GROUP BY operator, target_type
ORDER BY operator, target_type
</code>```

This makes a single pass across the entire table, and conditionally takes the sums you want depending on whether the operation_type be 1 or 2.  Note that the CASE expressions only include the operation_type and not the department or date.  The reason this works is because both of your original intended queries share these same WHERE conditions, hence we don't need to move them.

Body:
I have the following table, which contains number of operations performed by operator of a specific department in a specific date for each target_type. sum1 and sum2 are the number of operation 1 and operation 2 on the specific day, the interpretation of operations in question is indicated by the operation_type column.

statistic_id | department | operator | operation_type | target_type | sum1 | sum2 | date |

I would query the table to collect statistics for operation_type 1 on a department 1 in a specific time period grouped by operator and operation_type as follows

SELECT operator, target_type, SUM(sum1) AS op1, SUM(sum2) AS op2 FROM statistics
WHERE
  department = 1 AND
  operation_type = 1 AND
  (date BETWEEN in_start_date AND in_end_date)
GROUP BY operator, target_type
ORDER BY operator, target_type;

As well, I would query the table to collect statistics for operation_type 2 on the same department and time interval grouped by the same criteria

SELECT operator, target_type, SUM(sum1) AS op3, SUM(sum2) AS op4 FROM statistics
WHERE
  department = 1 AND
  operation_type = 2 AND
  (date BETWEEN in_start_date AND in_end_date)
GROUP BY operator, target_type
ORDER BY operator, target_type;

I would like to combine the query results, so I would get result like

operator | target_type | op1 | op2 | op3 | op4

How do I join the table with itself via aggregating different columns based on some common and some diverse criteria, yet grouping by the same set of columns?

Body:
Use conditional aggregation in your sums:

SELECT operator,
       target_type,
       SUM(CASE WHEN operation_type = 1 THEN sum1 ELSE 0 END) AS op1,
       SUM(CASE WHEN operation_type = 1 THEN sum2 ELSE 0 END) AS op2,
       SUM(CASE WHEN operation_type = 2 THEN sum1 ELSE 0 END) AS op3,
       SUM(CASE WHEN operation_type = 2 THEN sum2 ELSE 0 END) AS op4
FROM statistics
WHERE department = 1 AND
      date BETWEEN in_start_date AND in_end_date
GROUP BY operator, target_type
ORDER BY operator, target_type

This makes a single pass across the entire table, and conditionally takes the sums you want depending on whether the operation_type be 1 or 2.  Note that the CASE expressions only include the operation_type and not the department or date.  The reason this works is because both of your original intended queries share these same WHERE conditions, hence we don't need to move them.


问:
C++ operator's optimization via templates
So, I have a C++ Matrix class, and there are some overloaded operators(like +, *, %, - atc...), they look like this:

```<code>Matrix operator*(const Matrix& b) const;
</code>```

They are returning the TMP object of type Matrix, and then it's being copied, whinch decreaces the performance.

If I do something like

```<code>Matrix some = a*b + c*d - (i+j)*m*b; //[1]
</code>```

There are something about 6 copy constructors being called.

So, I saw ppl doing some template metaprogramming, to expand the [1] to something like:

```<code>Matrix some = ((a*b)+=(c*d))-=(((i+j)*=m)*=b); //[2]
</code>```

The code at [2] gonna call somewhere around 3 copy constructors.(*=, += writing the results to left operand and returns the link for it)

Can you guys pls explain me, how do I do that via templates, or what should I read to understand how to do that.

答:
So, as I saw in comments, compiller optimize it by itself, but, there are also some moments exists, that can be optimized.

Lets start.

First of all, usually, we save the result of overloaded operators via operator=, and if we add a couple of fields in it {bool tmp, bool copied} we can skip the memory coping, its should be looks like this.

.

```<code>...freeing memory, if needed...
if(!(tmp && !copied)
{
    ...memcpy actions...
}else
{
    ...assigning a pointers to allocated data right to our objects pointers...
    this->arr = a.arr;
    a.copied = true;
}
...other post actions...
</code>```

also we need to change a deconctructor

```<code>~SomeClass()
{
    if( !(tmp && copied) )//If its not a tmp and not copied then freeing
    {
        ...freeing a memory...
    }//otherwise just skeep
}
</code>```

In operators we usually calling an constructor for a result object, but, if one of our objects is tmp, why not to save data inside it, if its possible?

.

```<code>SomeClass operator+(SomeClass a)
{
    ...some code...
    if(!(tmp || a.tmp))//if there is no tmp object, doing the same, as usual.
    {
        SomeClass res;
        ...some usual code
        res.tmp = true;
        res.copied = false;
        return res;
    }else
    {
        if(tmp)
        {
            ...doing operations and storing them in this...
            return *this;
        }else //"a" is tmp
        {
            ...doing operations and storing them in "a"...
            return a;
        }
    }
}
</code>```

so... by those actions we are decreasing the amounght of operations being called, we are saving a memory that would be allocated otherwise, also we are not copying memory from the operator results.

Now, code like this:

```<code>res = a * n + b * t - k;
</code>```

will allocate memory only for a "a * n" and "b * t", then everything gonna be stored inside tmp objects of those operators results. And finally, we are not coping memory(values) from the tmp object to the "res", we are just simply assigning the pointers to a "tmp" memory(whinch is not gonna be freed).

Body:
So, I have a C++ Matrix class, and there are some overloaded operators(like +, *, %, - atc...), they look like this:

Matrix operator*(const Matrix& b) const;

They are returning the TMP object of type Matrix, and then it's being copied, whinch decreaces the performance.

If I do something like

Matrix some = a*b + c*d - (i+j)*m*b; //[1]

There are something about 6 copy constructors being called.

So, I saw ppl doing some template metaprogramming, to expand the [1] to something like:

Matrix some = ((a*b)+=(c*d))-=(((i+j)*=m)*=b); //[2]

The code at [2] gonna call somewhere around 3 copy constructors.(*=, += writing the results to left operand and returns the link for it)

Can you guys pls explain me, how do I do that via templates, or what should I read to understand how to do that.

Body:
So, as I saw in comments, compiller optimize it by itself, but, there are also some moments exists, that can be optimized.

Lets start.

First of all, usually, we save the result of overloaded operators via operator=, and if we add a couple of fields in it {bool tmp, bool copied} we can skip the memory coping, its should be looks like this.

.

...freeing memory, if needed...
if(!(tmp && !copied)
{
    ...memcpy actions...
}else
{
    ...assigning a pointers to allocated data right to our objects pointers...
    this->arr = a.arr;
    a.copied = true;
}
...other post actions...

also we need to change a deconctructor

~SomeClass()
{
    if( !(tmp && copied) )//If its not a tmp and not copied then freeing
    {
        ...freeing a memory...
    }//otherwise just skeep
}

In operators we usually calling an constructor for a result object, but, if one of our objects is tmp, why not to save data inside it, if its possible?

.

SomeClass operator+(SomeClass a)
{
    ...some code...
    if(!(tmp || a.tmp))//if there is no tmp object, doing the same, as usual.
    {
        SomeClass res;
        ...some usual code
        res.tmp = true;
        res.copied = false;
        return res;
    }else
    {
        if(tmp)
        {
            ...doing operations and storing them in this...
            return *this;
        }else //"a" is tmp
        {
            ...doing operations and storing them in "a"...
            return a;
        }
    }
}

so... by those actions we are decreasing the amounght of operations being called, we are saving a memory that would be allocated otherwise, also we are not copying memory from the operator results.

Now, code like this:

res = a * n + b * t - k;

will allocate memory only for a "a * n" and "b * t", then everything gonna be stored inside tmp objects of those operators results. And finally, we are not coping memory(values) from the tmp object to the "res", we are just simply assigning the pointers to a "tmp" memory(whinch is not gonna be freed).


问:
Android bluetooth get connected devices
How can I get a list of all connected bluetooth devices for Android regardless of profile?

Alternatively, I see that you can get all connected devices for a specific profile via BluetoothManager.getConnectedDevices.

And I guess I could see which devices are connected by listening for connections/disconnections via ACTION_ACL_CONNECTED/ACTION_ACL_DISCONNECTED...seems error prone.

But I'm wondering if there's a simpler way to get the list of all connected bluetooth devices.

答:
To see a complete list, this is a 2-step operation:

get list of currently paired devices

scan for, or discover, all others in range

To get a list of, and iterate, the currently paired devices:

```<code>Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() > 0) {
    for (BluetoothDevice d: pairedDevices) {
        String deviceName = d.getName();
        String macAddress = d.getAddress();
        Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress);
        // do what you need/want this these list items
    }
}
</code>```

Discovery is a little bit more of a complex operation.  To do this, you'll need to tell the BluetoothAdapter to start scanning/discovering.  As it finds things, it sends out Intents that you'll need to receive with a BroadcastReceiver.

First, we'll set up the receiver:

```<code>private void setupBluetoothReceiver()
{
    BroadcastRecevier btReceiver = new BroadcastReciver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            handleBtEvent(context, intent);
        }
    };
    IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    // this is not strictly necessary, but you may wish
    //  to know when the discovery cycle is done as well
    eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    myContext.registerReceiver(btReceiver, eventFilter);
}

private void handleBtEvent(Context context, Intent intent)
{
    String action = intent.getAction();
    Log.d(LOGTAG, "action received: " + action);

    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.i(LOGTAG, "found device: " + device.getName());
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        Log.d(LOGTAG, "discovery complete");
    }
}
</code>```

Now all that is left is to tell the BluetoothAdapter to start scanning:

```<code>BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
// if already scanning ... cancel
if (btAdapter.isDiscovering()) {
    btAdapter.cancelDiscovery();
}

btAdapter.startDiscovery();
</code>```

Title: Android bluetooth get connected devices

Body:
To see a complete list, this is a 2-step operation:

get list of currently paired devices

scan for, or discover, all others in range

To get a list of, and iterate, the currently paired devices:

Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() > 0) {
    for (BluetoothDevice d: pairedDevices) {
        String deviceName = d.getName();
        String macAddress = d.getAddress();
        Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress);
        // do what you need/want this these list items
    }
}

Discovery is a little bit more of a complex operation.  To do this, you'll need to tell the BluetoothAdapter to start scanning/discovering.  As it finds things, it sends out Intents that you'll need to receive with a BroadcastReceiver.

First, we'll set up the receiver:

private void setupBluetoothReceiver()
{
    BroadcastRecevier btReceiver = new BroadcastReciver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            handleBtEvent(context, intent);
        }
    };
    IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    // this is not strictly necessary, but you may wish
    //  to know when the discovery cycle is done as well
    eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    myContext.registerReceiver(btReceiver, eventFilter);
}

private void handleBtEvent(Context context, Intent intent)
{
    String action = intent.getAction();
    Log.d(LOGTAG, "action received: " + action);

    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.i(LOGTAG, "found device: " + device.getName());
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        Log.d(LOGTAG, "discovery complete");
    }
}

Now all that is left is to tell the BluetoothAdapter to start scanning:

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
// if already scanning ... cancel
if (btAdapter.isDiscovering()) {
    btAdapter.cancelDiscovery();
}

btAdapter.startDiscovery();


问:
Is it necessary to provide "Audio-only" stream when I use HLS(Http live streaming)?
I read this document and I'm not sure I need to add audio only stream.
https://developer.apple.com/library/content/qa/qa1767/_index.html

App store review guideline was changed like following.

Video streaming content over a cellular network longer than 10 minutes must use HTTP Live Streaming and include a baseline 64 kbps audio-only HTTP Live stream
=> Video streaming content over a cellular network longer than 10 minutes must use HTTP Live Streaming and include a baseline 192 kbps or lower HTTP Live stream

When I have a audio-only stream, and user entered that stream, It looks bug, because there is still image. And It is little bit late recorvered from that stream.
So I just want to prepare minimum bitrate with video(video 100Kbps, audio 92Kbps).

Is it possible to use 192kbps video for minimum bitrate without audio-only bitrate?

Thanks.

答:
Apple basically moved the answer to that into the linked Technical Note TN2224.

If your app uses HTTP Live Streaming over cellular networks, you are required to provide at least one stream at 192 kb/s or lower bandwidth. The low-bandwidth stream may be audio-only, or audio with a still image, but you should strive to have video in your 192kbps stream.

You should be fine now if your lowest stream is according to their restrictions and it must no longer be audio-only.


问:
How to zoom whole RecyclerView in android
I've created a zoom function which is working zooming for LinearLayout and FrameLayout but not working for RecyclerView.

XML file :

```<code><com.nm.esign.entities.ZoomLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/zoom_main1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fl_zoom"
    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view_template_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="30dp"

            android:scrollbars="vertical" />

    </LinearLayout>

     </com.nm.esign.entities.ZoomLayout>
</code>```

Main activity:

```<code>  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_view_template);

        //  prevBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentPrev_temp);
        // nextBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentNxt_temp);
    RecyclerView    recyclerView = (RecyclerView) findViewById(R.id.recycler_view_template_img);

    LinearLayout    fl_zoom=(LinearLayout)findViewById(R.id.fl_zoom)

        ZoomLayout myZoomView = new ZoomLayout(ViewTemplate.this);

      fl_zoom.addView(myZoomView); // working fine
// recyclerView.addView(myZoomView); // not working

....................................

}
</code>```

ZoomLayout class:

```<code>/**
 * Created by Lenovo5 on 3/16/2017.
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Layout that provides pinch-zooming of content. This view should have exactly one child
 * view containing the content.
 */
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector.OnScaleGestureListener {

    private enum Mode {
        NONE,
        DRAG,
        ZOOM
    }

    private static final String TAG = "ZoomLayout";
    private static final float MIN_ZOOM = 1.0f;
    private static final float MAX_ZOOM = 4.0f;

    private Mode mode = Mode.NONE;
    private float scale = 1.0f;
    private float lastScaleFactor = 0f;

    // Where the finger first  touches the screen
    private float startX = 0f;
    private float startY = 0f;

    // How much to translate the canvas
    private float dx = 0f;
    private float dy = 0f;
    private float prevDx = 0f;
    private float prevDy = 0f;

    public ZoomLayout(Context context) {
        super(context);
        init(context);
    }

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

    public ZoomLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this);
        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i(TAG, "DOWN");
                        if (scale > MIN_ZOOM) {
                            mode = Mode.DRAG;
                            startX = motionEvent.getX() - prevDx;
                            startY = motionEvent.getY() - prevDy;
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == Mode.DRAG) {
                            dx = motionEvent.getX() - startX;
                            dy = motionEvent.getY() - startY;
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_DOWN:
                        mode = Mode.ZOOM;
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = Mode.DRAG;
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "UP");
                        mode = Mode.NONE;
                        prevDx = dx;
                        prevDy = dy;
                        break;
                }
                scaleDetector.onTouchEvent(motionEvent);

                if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale;
                    float maxDy = (child().getHeight() - (child().getHeight() / scale))/ 2 * scale;
                    dx = Math.min(Math.max(dx, -maxDx), maxDx);
                    dy = Math.min(Math.max(dy, -maxDy), maxDy);
                    Log.i(TAG, "Width: " + child().getWidth() + ", scale " + scale + ", dx " + dx
                            + ", max " + maxDx);
                    applyScaleAndTranslation();
                }

                return true;
            }
        });
    }

    // ScaleGestureDetector

    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleBegin");
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleDetector) {
        float scaleFactor = scaleDetector.getScaleFactor();
        Log.i(TAG, "onScale" + scaleFactor);
        if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) {
            scale *= scaleFactor;
            scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM));
            lastScaleFactor = scaleFactor;
        } else {
            lastScaleFactor = 0;
        }
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleEnd");
    }

    private void applyScaleAndTranslation() {
        child().setScaleX(scale);
        child().setScaleY(scale);
        child().setTranslationX(dx);
        child().setTranslationY(dy);
    }

    private View child() {
        return getChildAt(0);
    }
}
</code>```

Error  coming for:-

```<code>  recyclerView.addView(myZoomView);

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nm.esign, PID: 6028
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nm.esign/com.nm.esign.activity.ViewTemplate}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.support.v7.widget.RecyclerView.generateDefaultLayoutParams(RecyclerView.java:3869)
    at android.view.ViewGroup.addView(ViewGroup.java:4431)
    at android.view.ViewGroup.addView(ViewGroup.java:4409)
    at com.nm.esign.activity.ViewTemplate.onCreate(ViewTemplate.java:112)
    at android.app.Activity.performCreate(Activity.java:6904)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
You must have this line in your code</p>

```<code>LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
</code>```

Body:
I've created a zoom function which is working zooming for LinearLayout and FrameLayout but not working for RecyclerView.

XML file :

<com.nm.esign.entities.ZoomLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/zoom_main1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fl_zoom"
    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view_template_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="30dp"

            android:scrollbars="vertical" />

    </LinearLayout>

     </com.nm.esign.entities.ZoomLayout>

Main activity:

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_view_template);

        //  prevBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentPrev_temp);
        // nextBtn=(android.support.v7.widget.AppCompatButton)findViewById(R.id.btnDocumentNxt_temp);
    RecyclerView    recyclerView = (RecyclerView) findViewById(R.id.recycler_view_template_img);

    LinearLayout    fl_zoom=(LinearLayout)findViewById(R.id.fl_zoom)

        ZoomLayout myZoomView = new ZoomLayout(ViewTemplate.this);

      fl_zoom.addView(myZoomView); // working fine
// recyclerView.addView(myZoomView); // not working

....................................

}

ZoomLayout class:

/**
 * Created by Lenovo5 on 3/16/2017.
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Layout that provides pinch-zooming of content. This view should have exactly one child
 * view containing the content.
 */
public class ZoomLayout extends FrameLayout implements ScaleGestureDetector.OnScaleGestureListener {

    private enum Mode {
        NONE,
        DRAG,
        ZOOM
    }

    private static final String TAG = "ZoomLayout";
    private static final float MIN_ZOOM = 1.0f;
    private static final float MAX_ZOOM = 4.0f;

    private Mode mode = Mode.NONE;
    private float scale = 1.0f;
    private float lastScaleFactor = 0f;

    // Where the finger first  touches the screen
    private float startX = 0f;
    private float startY = 0f;

    // How much to translate the canvas
    private float dx = 0f;
    private float dy = 0f;
    private float prevDx = 0f;
    private float prevDy = 0f;

    public ZoomLayout(Context context) {
        super(context);
        init(context);
    }

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

    public ZoomLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(context, this);
        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i(TAG, "DOWN");
                        if (scale > MIN_ZOOM) {
                            mode = Mode.DRAG;
                            startX = motionEvent.getX() - prevDx;
                            startY = motionEvent.getY() - prevDy;
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mode == Mode.DRAG) {
                            dx = motionEvent.getX() - startX;
                            dy = motionEvent.getY() - startY;
                        }
                        break;
                    case MotionEvent.ACTION_POINTER_DOWN:
                        mode = Mode.ZOOM;
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        mode = Mode.DRAG;
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "UP");
                        mode = Mode.NONE;
                        prevDx = dx;
                        prevDy = dy;
                        break;
                }
                scaleDetector.onTouchEvent(motionEvent);

                if ((mode == Mode.DRAG && scale >= MIN_ZOOM) || mode == Mode.ZOOM) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    float maxDx = (child().getWidth() - (child().getWidth() / scale)) / 2 * scale;
                    float maxDy = (child().getHeight() - (child().getHeight() / scale))/ 2 * scale;
                    dx = Math.min(Math.max(dx, -maxDx), maxDx);
                    dy = Math.min(Math.max(dy, -maxDy), maxDy);
                    Log.i(TAG, "Width: " + child().getWidth() + ", scale " + scale + ", dx " + dx
                            + ", max " + maxDx);
                    applyScaleAndTranslation();
                }

                return true;
            }
        });
    }

    // ScaleGestureDetector

    @Override
    public boolean onScaleBegin(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleBegin");
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector scaleDetector) {
        float scaleFactor = scaleDetector.getScaleFactor();
        Log.i(TAG, "onScale" + scaleFactor);
        if (lastScaleFactor == 0 || (Math.signum(scaleFactor) == Math.signum(lastScaleFactor))) {
            scale *= scaleFactor;
            scale = Math.max(MIN_ZOOM, Math.min(scale, MAX_ZOOM));
            lastScaleFactor = scaleFactor;
        } else {
            lastScaleFactor = 0;
        }
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector scaleDetector) {
        Log.i(TAG, "onScaleEnd");
    }

    private void applyScaleAndTranslation() {
        child().setScaleX(scale);
        child().setScaleY(scale);
        child().setTranslationX(dx);
        child().setTranslationY(dy);
    }

    private View child() {
        return getChildAt(0);
    }
}

Error  coming for:-

  recyclerView.addView(myZoomView);

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nm.esign, PID: 6028
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nm.esign/com.nm.esign.activity.ViewTemplate}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
    at android.support.v7.widget.RecyclerView.generateDefaultLayoutParams(RecyclerView.java:3869)
    at android.view.ViewGroup.addView(ViewGroup.java:4431)
    at android.view.ViewGroup.addView(ViewGroup.java:4409)
    at com.nm.esign.activity.ViewTemplate.onCreate(ViewTemplate.java:112)
    at android.app.Activity.performCreate(Activity.java:6904)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7331)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
You must have this line in your code

LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);


问:
C# Inserting a DataSet Into SQL Database
I'm trying to insert a dataset into an SQL database but I am having difficulties passing my dataset as an argument to my DB class. I am not sure if it is allowed to pass as an argument. If not, what are my alternatives?

The way I create my dataset:

```<code>public static void getLogs() {
    string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\someDir";
    SQLiteConnection cn = new SQLiteConnection("Data Source=" + path + ";Version=3;New=False;Compress=True;");
    cn.Open();
    SQLiteDataAdapter sd = new SQLiteDataAdapter("SELECT * FROM table", cn);

    DataSet ds = new DataSet();
    sd.Fill(ds);

    cn.Close();

    db.InsertLogs(Form1.adminID, Form1.deviceID, ds);
}
</code>```

My database class and insert method looks like the following:

```<code>public void InsertLogs(string user_id, string device_id, DataSet history)
{
    string query = "INSERT INTO table (column1, column2, column3, column4, column5, column6, column7) VALUES (@value1, @value2, @value3, @value4, @value5, @value6, @value7);";

    if (OpenConnection() == true)
    {
        foreach (DataTable table in history.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.Parameters.AddWithValue("@value1", int.Parse(user_id));
                cmd.Parameters.AddWithValue("@value2", int.Parse(device_id));
                cmd.Parameters.AddWithValue("@value3", row[0]);
                cmd.Parameters.AddWithValue("@value4", row[1]);
                cmd.Parameters.AddWithValue("@value5", row[2]);
                cmd.Parameters.AddWithValue("@value6", row[3]);
                cmd.Parameters.AddWithValue("@value7", row[4]);
                cmd.ExecuteNonQuery();
            }
        }
        CloseConnection();
    }
}
</code>```

Thank you

答:
you can loop through datatables in a dataset and can pass a datatable as a stored procedure paramater,
found an example here</p>

Body:
I'm trying to insert a dataset into an SQL database but I am having difficulties passing my dataset as an argument to my DB class. I am not sure if it is allowed to pass as an argument. If not, what are my alternatives?

The way I create my dataset:

public static void getLogs() {
    string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\someDir";
    SQLiteConnection cn = new SQLiteConnection("Data Source=" + path + ";Version=3;New=False;Compress=True;");
    cn.Open();
    SQLiteDataAdapter sd = new SQLiteDataAdapter("SELECT * FROM table", cn);

    DataSet ds = new DataSet();
    sd.Fill(ds);

    cn.Close();

    db.InsertLogs(Form1.adminID, Form1.deviceID, ds);
}

My database class and insert method looks like the following:

public void InsertLogs(string user_id, string device_id, DataSet history)
{
    string query = "INSERT INTO table (column1, column2, column3, column4, column5, column6, column7) VALUES (@value1, @value2, @value3, @value4, @value5, @value6, @value7);";

    if (OpenConnection() == true)
    {
        foreach (DataTable table in history.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.Parameters.AddWithValue("@value1", int.Parse(user_id));
                cmd.Parameters.AddWithValue("@value2", int.Parse(device_id));
                cmd.Parameters.AddWithValue("@value3", row[0]);
                cmd.Parameters.AddWithValue("@value4", row[1]);
                cmd.Parameters.AddWithValue("@value5", row[2]);
                cmd.Parameters.AddWithValue("@value6", row[3]);
                cmd.Parameters.AddWithValue("@value7", row[4]);
                cmd.ExecuteNonQuery();
            }
        }
        CloseConnection();
    }
}

Thank you


问:
Why -1 >> 1 is -1 ? And 1 >> 1 is 0!
I have next code:

```<code>std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;
</code>```

The result is:

```<code>-5
-5
-4
-4
-3
-3
-2
-2
-1
-1
</code>```

But why?

-1 is 1111 1111 (for 1 byte), -1 >> 1 must be : 1011 1111 and it is not -1 or 0! (sign-bit is not shifted, I know)

Can someone explain to me how this works?

答:
Right-shifting a negative number is implementation-defined.

Implementations which shift in a sign-extended bit to the leftmost bit, work as you reported.

As for why it is done this way, it's because right-shifting can be used to divide by a power of 2 with round-towards-negative-infinity (e.g. like floor()) rounding behavior:

```<code>(-8 >> 2) == -2
(-9 >> 2) == -3
(-10 >> 2) == -3
(-11 >> 2) == -3
(-12 >> 2) == -3
</code>```

See this SO question.

Title: Why -1 >> 1 is -1 ? And 1 >> 1 is 0!

Body:
I have next code:

std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;

The result is:

-5
-5
-4
-4
-3
-3
-2
-2
-1
-1

But why?

-1 is 1111 1111 (for 1 byte), -1 >> 1 must be : 1011 1111 and it is not -1 or 0! (sign-bit is not shifted, I know)

Can someone explain to me how this works?

Body:
Right-shifting a negative number is implementation-defined.

Implementations which shift in a sign-extended bit to the leftmost bit, work as you reported.

As for why it is done this way, it's because right-shifting can be used to divide by a power of 2 with round-towards-negative-infinity (e.g. like floor()) rounding behavior:

(-8 >> 2) == -2
(-9 >> 2) == -3
(-10 >> 2) == -3
(-11 >> 2) == -3
(-12 >> 2) == -3

See this SO question.


问:
VB code to connect to SQL server on windows server 2012R2 - not locally
I know how to connect to SQL server Management studio locally, the one to your desktop, Windows Authentication. Code is as below.

```<code>myconnection As New SqlConnection("data source =serverNAME01; initial catalog=ZPCD; integrated security=true")
</code>```

But how do I connect to SQL server Management Studio on Windows Server 2012R2, SQL Server Authentication from my desktop ?

The computer and username for remote desktop connection to Windows Server 2012R2 are:

computerNAME01,

userNAME01

The server name, login, password and IP address to management studio (database engine) are:

Server name: serverName01

Login: sa

Password: Password01

IP: 192.167.1.21

and database name is
ZPCD

This is an example of my code, but it doesn't work.

```<code>connetionString="Data Source=192.167.1.21,1433;
    Network Library=DBMSSOCN;   Initial Catalog=ZPCD;
    User ID=sa;Password=Password01"
</code>```

Error Message:

A network - related or instance-specific error occurred while establishing a connection to SQL server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provide: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 5)

答:
This is the format of the connection string I use.  The format (apparently) changed in VB.NET from VS 2008 to VS 2010.  When I upgraded my software from VS 2008 to VS 2010, it failed to connect to Sql Server.  Took me hours to figure it out:

```<code>connectionString="server=192.168.1.1;database=MyDb;uid=sa; pwd=MyPassword" providerName="System.Data.SqlClient"
</code>```

R/
Prescott ....

Body:
I know how to connect to SQL server Management studio locally, the one to your desktop, Windows Authentication. Code is as below.

myconnection As New SqlConnection("data source =serverNAME01; initial catalog=ZPCD; integrated security=true")

But how do I connect to SQL server Management Studio on Windows Server 2012R2, SQL Server Authentication from my desktop ?

The computer and username for remote desktop connection to Windows Server 2012R2 are:

computerNAME01,

userNAME01

The server name, login, password and IP address to management studio (database engine) are:

Server name: serverName01

Login: sa

Password: Password01

IP: 192.167.1.21

and database name is
ZPCD

This is an example of my code, but it doesn't work.

connetionString="Data Source=192.167.1.21,1433;
    Network Library=DBMSSOCN;   Initial Catalog=ZPCD;
    User ID=sa;Password=Password01"

Error Message:

A network - related or instance-specific error occurred while establishing a connection to SQL server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provide: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 5)

Body:
This is the format of the connection string I use.  The format (apparently) changed in VB.NET from VS 2008 to VS 2010.  When I upgraded my software from VS 2008 to VS 2010, it failed to connect to Sql Server.  Took me hours to figure it out:

connectionString="server=192.168.1.1;database=MyDb;uid=sa; pwd=MyPassword" providerName="System.Data.SqlClient"

R/
Prescott ....


问:
Prevent response body download in python async http requests
I want to "ping" a server, check the header response to see if the link is broken, and if it's not broken, actually download the response body.

Traditionally, using a sync method with the requests module, you could send a get request with the stream = True parameter, and capture the headers before the response body download, deciding, in case of error (not found, for example), to abort the connection.

My problem is, doing this with the async libraries grequests or requests-futures has become impossible for my reduced knowdlege base.

I've tried setting the stream parameter to true in request-futures but to no use, it still downloads the response body without letting me intervene as soon as it gets the response headers. And even if it did, I wouldn't be sure of how to proceed.

This is what I've tried:

test.py

```<code>from requests_futures.sessions import FuturesSession

session = FuturesSession()
session.stream = True

future = session.get('http://www.google.com')
response = future.result()
print(response.status_code) # Here I would assume the response body hasn't been loaded
</code>```

Upon debugging I find it downloads the response body either way.

I would appreciate any solution to the initial problem, whether it follows my logic or not.

答:
Just check the status from the head request and proceed accordingly:</p>

```<code>header = session.head('https://google.com')

if header.ok is True:
    session.get('https://google.com')
</code>```

Body:
I want to "ping" a server, check the header response to see if the link is broken, and if it's not broken, actually download the response body.

Traditionally, using a sync method with the requests module, you could send a get request with the stream = True parameter, and capture the headers before the response body download, deciding, in case of error (not found, for example), to abort the connection.

My problem is, doing this with the async libraries grequests or requests-futures has become impossible for my reduced knowdlege base.

I've tried setting the stream parameter to true in request-futures but to no use, it still downloads the response body without letting me intervene as soon as it gets the response headers. And even if it did, I wouldn't be sure of how to proceed.

This is what I've tried:

test.py

from requests_futures.sessions import FuturesSession

session = FuturesSession()
session.stream = True

future = session.get('http://www.google.com')
response = future.result()
print(response.status_code) # Here I would assume the response body hasn't been loaded

Upon debugging I find it downloads the response body either way.

I would appreciate any solution to the initial problem, whether it follows my logic or not.

Body:
Just check the status from the head request and proceed accordingly:

header = session.head('https://google.com')

if header.ok is True:
    session.get('https://google.com')


问:
Does retain cycle for a block applies for methods the block call?
Ok, we know that we may have a retain cycle if we do this

```<code>[someObject messageWithBlock:^{ [self doSomething]; }];
</code>```

and that the solution is something like this

```<code>__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];
</code>```

But what about if we do this last code but doSomething has a lot of references to self? Like:

```<code>- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}
</code>```

Will this create a retain cycle?

and what about this:

```<code>__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];
</code>```

Where MY_TABLE is a #define?

答:
retain cycle is created when we have more than 2 references of object. ARC decrease the retain count by on when goes out of scope. But if we have more than 1 strong references of a object, then retain cycle occurs.

(i) To remove the retain cycle , Always take weak references of object specifically in case of blocks. because block create a separate copy of objects i like this what you did:

```<code> __weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
[weakSelf doSomething];
 }];
</code>```

(ii) For function not Any issue

```<code>- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}
</code>```

Body:
Ok, we know that we may have a retain cycle if we do this

[someObject messageWithBlock:^{ [self doSomething]; }];

and that the solution is something like this

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{ [weakSelf doSomething]; }];

But what about if we do this last code but doSomething has a lot of references to self? Like:

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}

Will this create a retain cycle?

and what about this:

__weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
   self.onError(NSLocalizedStringFromTable(@"Error", MY_TABLE, nil))
}];

Where MY_TABLE is a #define?

Body:
retain cycle is created when we have more than 2 references of object. ARC decrease the retain count by on when goes out of scope. But if we have more than 1 strong references of a object, then retain cycle occurs.

(i) To remove the retain cycle , Always take weak references of object specifically in case of blocks. because block create a separate copy of objects i like this what you did:

 __weak typeof(self) weakSelf = self;
[someObject messageWithBlock:^{
[weakSelf doSomething];
 }];

(ii) For function not Any issue

- (void) doSomething {
    self.myProperty = @"abc";
    [self doOtherThing];
}


问:
How to remove repeated foreach values in jquery
I am working now wordpress this is my code

```<code>jQuery(document).ready(function () {

 <?php
 $var= $product->get_available_variations();
 foreach ($var as $key => $test)
 {

$check=$test['display_price'];
 ?>
 var check='<?php echo $check;?>';

 jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

 <?php
 }
 ?>
</code>```

Actually my task is split foreach values and append another div.But my answer is again and again repeated.My out put is there,

```<code>53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
</code>```

But i want out put

```<code> 53.95
39.95
29.95
27.95
</code>```

this only.please help me.

答:
You can use array_unique

```<code> $var= array_unique($product->get_available_variations());
</code>```

Why don't you get unique records from database itself use distinct on the column

Body:
I am working now wordpress this is my code

jQuery(document).ready(function () {

 <?php
 $var= $product->get_available_variations();
 foreach ($var as $key => $test)
 {

$check=$test['display_price'];
 ?>
 var check='<?php echo $check;?>';

 jQuery('
'+check+'
').appendTo('.variation_buttons_wrapper');

 <?php
 }
 ?>

Actually my task is split foreach values and append another div.But my answer is again and again repeated.My out put is there,

53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95

But i want out put

 53.95
39.95
29.95
27.95

this only.please help me.

Body:
You can use array_unique

 $var= array_unique($product->get_available_variations());

Why don't you get unique records from database itself use distinct on the column


问:
Apache HTTPClient 4.x vs multiple JDK URL connections
I am trying out Apache HTTPClient 4.3.6 connection pool manager to increase the throughput of my HTTP calls. My assumption is, HTTPClient implementation in general is using persistence connection. The result of my test code (included at the end), however, showed that multiple concurrent HTTP connections using JDK URLConnection perform better.

How do I make HTTPClient fast?

Does HTTPClient uses the same HTTP connection for http://localhost:9000/user/123 and http://localhost:9000/user/456?

Thanks

```<code>import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FooTest {

public static void main(String[] args) throws Exception {
    runWithConnectionPool();
}

 private static String extract(BufferedReader reader) throws Exception {
     StringBuilder buffer = new StringBuilder();
     String line = null;
     while ((line = reader.readLine()) != null) {
         buffer.append(line);
     }
     return buffer.toString();
 }

 private static void runWithConnectionPool() throws Exception {
     PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
     cm.setMaxTotal(1);

     CloseableHttpClient httpClient = HttpClients.custom()
         .setConnectionManager(cm)
         .setMaxConnTotal(100)
         .setMaxConnPerRoute(100)
         .build();

     long start = System.currentTimeMillis();

     HttpGet getReq = new HttpGet("http://www.google.com");

     /*
       Option A: Using HTTP connection pool
       Option B: Individual JDK 8 URL connection
     */
 //    Thread[] workers = generateAndStart(10, httpClient, getReq, 0);                 // (A)
     Thread[] workers = generateAndStart(10, getReq.getURI().toURL(), 0);  // (B)

     for (int i = 0; i < workers.length; i++) {
         workers[i].join();
     }

     System.out.println("Elasped: " + (System.currentTimeMillis() - start));
 }

 private static Thread[] generateAndStart(int num, URL url, long delay) {
     Thread[] workers = new Thread[num];
     for (int i = 0; i < num; i++) {
         System.out.println("Starting worker: " + i);
         int j = i;
         workers[i] = new Thread(() -> connect(url, delay, j));
         workers[i].start();
     }
     return workers;
 }

 private static void connect(URL url, long delay, int ndx)  {
     try {
         System.out.println(url.toURI().toString() + " started.");
     } catch (Exception e) {
         e.printStackTrace();
     }

     try {

         URLConnection connection = url.openConnection();
         connection.addRequestProperty("Accept", "application/json");
         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

         String line;
         while ((line = reader.readLine()) != null) {
             ObjectMapper mapper = new ObjectMapper();
             System.out.println(line);
         }
         if (delay > 0) {
             System.out.println("Delayed.");
             sleep(delay);
         }
         reader.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 private static Thread[] generateAndStart(int num, CloseableHttpClient httpClient, HttpGet getReq, long delay) {
     Thread[] workers = new Thread[num];
     for (int i = 0; i < num; i++) {
         System.out.println("Starting worker: " + i);
         final int j = i;
         workers[i] = new Thread(() -> connect(httpClient, getReq, delay, j));
         workers[i].start();
     }
     return workers;
 }

 private static void connect(CloseableHttpClient httpClient, HttpGet request, long delay, int ndx) {
     System.out.println(request.getURI().toString() + " started.");

     try(
         CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
         BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {

         String line;
         while ((line = reader.readLine()) != null) {
             ObjectMapper mapper = new ObjectMapper();
             System.out.println(line);
         }
         if (delay > 0) {
             System.out.println("Delayed.");
             sleep(delay);
         }
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 private static void sleep(long delay) {
     try {
         Thread.sleep(delay);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }
 }
</code>```

Update 1 (28 March 2017)

I have made several observations and conclusions,

JDK java.net.URLConnection does not make a connection until URLConnection.getInputStream() is called.

java.net.URLConnection closes the current socket if bad connection happens e.g. HTTP error, and creates a new socket.

Using the java.net.URLConnection instances created from the same java.net.URL instance in a multi threaded environment will create multiple sockets to the server. Instead, for simplicity, invoke URL.openConnection() in a synchronized block. <s>On the same note, it does not mean every call to the URL.openConnection() will create a new socket. I believe URL regulates this.</s> I was wrong. The number of sockets created is according to the number of threads that invoke URL.openConnection().

It is mentioned in many places and I mention again, closing / disconnecting the URLConnection does not close the socket.

Connecting to a different path of the same server does not create another connection socket. In other words, persistent connection is usable with different paths.

Apache HTTPClient in general is easier to use and more intuitive. It supports persistent connection (uses the same socket for connection) in a multi threaded environment without user's intervention.

I could not get URL to comply to http.maxConnections and http.keepAlive. For example, I include -Dhttp.keepAlive=false during runtime does not prevent Connection: keep-alive included in the HTTP headers.

My observations come from the examples I pasted here. They are better examples than the code pasted above.

答:
I found my answers after experimenting with JDK URLConnection and Apache HTTPClient.

URLConnection is fast because it opens new sockets for each connection made by each thread to the server whilst Apache HTTPClient controls the number of sockets open according its setting in a multi threaded environment. When the sockets are limited to few, the total connection time taken is about the same for both HTTP libraries.

Apache HTTPClient uses persistent connection to the same server for different URLs.

mitmproxy is a good and easy to use tool for  HTTP connections verifications.

Body:
I am trying out Apache HTTPClient 4.3.6 connection pool manager to increase the throughput of my HTTP calls. My assumption is, HTTPClient implementation in general is using persistence connection. The result of my test code (included at the end), however, showed that multiple concurrent HTTP connections using JDK URLConnection perform better.

How do I make HTTPClient fast?

Does HTTPClient uses the same HTTP connection for http://localhost:9000/user/123 and http://localhost:9000/user/456?

Thanks

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FooTest {

public static void main(String[] args) throws Exception {
    runWithConnectionPool();
}

 private static String extract(BufferedReader reader) throws Exception {
     StringBuilder buffer = new StringBuilder();
     String line = null;
     while ((line = reader.readLine()) != null) {
         buffer.append(line);
     }
     return buffer.toString();
 }

 private static void runWithConnectionPool() throws Exception {
     PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
     cm.setMaxTotal(1);

     CloseableHttpClient httpClient = HttpClients.custom()
         .setConnectionManager(cm)
         .setMaxConnTotal(100)
         .setMaxConnPerRoute(100)
         .build();

     long start = System.currentTimeMillis();

     HttpGet getReq = new HttpGet("http://www.google.com");

     /*
       Option A: Using HTTP connection pool
       Option B: Individual JDK 8 URL connection
     */
 //    Thread[] workers = generateAndStart(10, httpClient, getReq, 0);                 // (A)
     Thread[] workers = generateAndStart(10, getReq.getURI().toURL(), 0);  // (B)

     for (int i = 0; i < workers.length; i++) {
         workers[i].join();
     }

     System.out.println("Elasped: " + (System.currentTimeMillis() - start));
 }

 private static Thread[] generateAndStart(int num, URL url, long delay) {
     Thread[] workers = new Thread[num];
     for (int i = 0; i < num; i++) {
         System.out.println("Starting worker: " + i);
         int j = i;
         workers[i] = new Thread(() -> connect(url, delay, j));
         workers[i].start();
     }
     return workers;
 }

 private static void connect(URL url, long delay, int ndx)  {
     try {
         System.out.println(url.toURI().toString() + " started.");
     } catch (Exception e) {
         e.printStackTrace();
     }

     try {

         URLConnection connection = url.openConnection();
         connection.addRequestProperty("Accept", "application/json");
         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

         String line;
         while ((line = reader.readLine()) != null) {
             ObjectMapper mapper = new ObjectMapper();
             System.out.println(line);
         }
         if (delay > 0) {
             System.out.println("Delayed.");
             sleep(delay);
         }
         reader.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 private static Thread[] generateAndStart(int num, CloseableHttpClient httpClient, HttpGet getReq, long delay) {
     Thread[] workers = new Thread[num];
     for (int i = 0; i < num; i++) {
         System.out.println("Starting worker: " + i);
         final int j = i;
         workers[i] = new Thread(() -> connect(httpClient, getReq, delay, j));
         workers[i].start();
     }
     return workers;
 }

 private static void connect(CloseableHttpClient httpClient, HttpGet request, long delay, int ndx) {
     System.out.println(request.getURI().toString() + " started.");

     try(
         CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
         BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {

         String line;
         while ((line = reader.readLine()) != null) {
             ObjectMapper mapper = new ObjectMapper();
             System.out.println(line);
         }
         if (delay > 0) {
             System.out.println("Delayed.");
             sleep(delay);
         }
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 private static void sleep(long delay) {
     try {
         Thread.sleep(delay);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }
 }

Update 1 (28 March 2017)

I have made several observations and conclusions,

JDK java.net.URLConnection does not make a connection until URLConnection.getInputStream() is called.

java.net.URLConnection closes the current socket if bad connection happens e.g. HTTP error, and creates a new socket.

Using the java.net.URLConnection instances created from the same java.net.URL instance in a multi threaded environment will create multiple sockets to the server. Instead, for simplicity, invoke URL.openConnection() in a synchronized block. <s>On the same note, it does not mean every call to the URL.openConnection() will create a new socket. I believe URL regulates this.</s> I was wrong. The number of sockets created is according to the number of threads that invoke URL.openConnection().

It is mentioned in many places and I mention again, closing / disconnecting the URLConnection does not close the socket.

Connecting to a different path of the same server does not create another connection socket. In other words, persistent connection is usable with different paths.

Apache HTTPClient in general is easier to use and more intuitive. It supports persistent connection (uses the same socket for connection) in a multi threaded environment without user's intervention.

I could not get URL to comply to http.maxConnections and http.keepAlive. For example, I include -Dhttp.keepAlive=false during runtime does not prevent Connection: keep-alive included in the HTTP headers.

My observations come from the examples I pasted here. They are better examples than the code pasted above.


问:
Connection timeout for SQL server
Can I increase the timeout by modifying the connection string in the web.config?

答:
Hmmm...

As Darin said, you can specify a higher connection timeout value, but I doubt that's really the issue.

When you get connection timeouts, it's typically a problem with one of the following:

Network configuration - slow connection between your web server/dev box and the SQL server. Increasing the timeout may correct this, but it'd be wise to investigate the underlying problem.

Connection string. I've seen issues where an incorrect username/password will, for some reason, give a timeout error instead of a real error indicating "access denied." This shouldn't happen, but such is life.

Connection String 2: If you're specifying the name of the server incorrectly, or incompletely (for instance, mysqlserver instead of mysqlserver.webdomain.com), you'll get a timeout. Can you ping the server using the server name exactly as specified in the connection string from the command line?

Connection string 3 : If the server name is in your DNS (or hosts file), but the pointing to an incorrect or inaccessible IP, you'll get a timeout rather than a machine-not-found-ish error.

The query you're calling is timing out. It can look like the connection to the server is the problem, but, depending on how your app is structured, you could be making it all the way to the stage where your query is executing before the timeout occurs.

Connection leaks. How many processes are running? How many open connections? I'm not sure if raw ADO.NET performs connection pooling, automatically closes connections when necessary ala Enterprise Library, or where all that is configured. This is probably a red herring. When working with WCF and web services, though, I've had issues with unclosed connections causing timeouts and other unpredictable behavior.

Things to try:

Do you get a timeout when connecting to the server with SQL Management Studio? If so, network config is likely the problem. If you do not see a problem when connecting with Management Studio, the problem will be in your app, not with the server.

Run SQL Profiler, and see what's actually going across the wire. You should be able to tell if you're really connecting, or if a query is the problem.

Run your query in Management Studio, and see how long it takes.

Good luck!

Title: Connection timeout for SQL server


问:
How to load external properties file with Java without rebuilding the Jar?
I use gradle which structures projects in maven style so I have the following

src/main/java/Hello.java and src/main/resources/test.properties

My Hello.java look like this

```<code>public class Hello {
    public static void main(String[] args) {
        Properties configProperties = new Properties();
        ClassLoader classLoader =  Hello.class.getClassLoader();
        try {
            configProperties.load(classLoader.getResourceAsStream("test.properties"));
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?

答: Archaius may be complete overkill for such a simple problem, but it is a great way to manage external properties. It is a library for handling configuration: hierarchies of configuration, configuration from property files, configuration from databases, configuration from user defined sources. It may seem complicated, but you will never have to worry about hand-rolling a half-broken solution to configuration again. The Getting Started page has a section on using a local file as the configuration source.</p>

Body:
I use gradle which structures projects in maven style so I have the following

src/main/java/Hello.java and src/main/resources/test.properties

My Hello.java look like this

public class Hello {
    public static void main(String[] args) {
        Properties configProperties = new Properties();
        ClassLoader classLoader =  Hello.class.getClassLoader();
        try {
            configProperties.load(classLoader.getResourceAsStream("test.properties"));
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?


问:
RadioButton.IsChecked Not Going False
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.

```<code>    private void usingmltBtn_Click(object sender, RoutedEventArgs e)
    {

        if (RadioButton.IsChecked == true)
        {
            RadioButton.IsChecked = false;
            i2cerrRec.Visibility = Visibility.Collapsed;
            i2cerrTxt.Visibility = Visibility.Collapsed;
            mltI2Cnck = 0;

        }
        else if (RadioButton.IsChecked == false)
        {
            RadioButton.IsChecked = true;
            mlttempLbl.Text = "N/C";
        }

    }
</code>```

Thanks for your help.

答:
Go through the url below

```<code>https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/radio-button
</code>```

You might wrong in XAML code!

Title: RadioButton.IsChecked Not Going False

Body:
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.

    private void usingmltBtn_Click(object sender, RoutedEventArgs e)
    {

        if (RadioButton.IsChecked == true)
        {
            RadioButton.IsChecked = false;
            i2cerrRec.Visibility = Visibility.Collapsed;
            i2cerrTxt.Visibility = Visibility.Collapsed;
            mltI2Cnck = 0;

        }
        else if (RadioButton.IsChecked == false)
        {
            RadioButton.IsChecked = true;
            mlttempLbl.Text = "N/C";
        }

    }

Thanks for your help.

Body:
Go through the url below

https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/radio-button

You might wrong in XAML code!