问:
Slow query with CROSS APPLY
I have the following SQL code which takes several seconds to execute:

```<code>SELECT instance.startdate
      ,instance.enddate
FROM (select mr.id
      FROM meeting_recurrence AS mr
      inner JOIN meeting_details md ON md.id = mr.meeting_template_id
      WHERE host_user_id=17) AS p
CROSS APPLY GetRecurrenceMeetingInstances(p.id,'2018-11-09 11:00:00','2018-11-09 15:00:00') AS instance
WHERE 21015 IS NOT NULL
AND instance.meetingid <> 21015
</code>```

The internal select (select mr.id FROM meeting_recurrence...) returns in the above example instantly, with two ids.

Running GetRecurrenceMeetingInstances() with those two ids separately, returns empty results instantly.

Why does running the entire statement take so long compared to running them separately?

Execution plan image: https://imgur.com/a/3Ydym

答:
It seems CROSS APPLY was calling GetRecurrenceMeetingInstances() a lot more than i thought. I solved the problem by saving the inner select in a local variable first:</p>

```<code>DECLARE @innerresult table(meetingid int)
INSERT INTO @innerresult(meetingid) (select mr.id FROM meeting_recurrence AS mr inner JOIN meeting_details md ON md.id = mr.meeting_template_id
    WHERE host_user_id=17)

INSERT INTO @timeslots (startdate,enddate)
    SELECT instance.startdate,instance.enddate
    FROM (select meetingid FROM @innerresult) AS p
    CROSS APPLY GetRecurrenceMeetingInstances(p.meetingid,'2018-11-09 11:00:00','2018-11-09 15:00:00') AS instance
</code>```

Title: Slow query with CROSS APPLY

Body:
I have the following SQL code which takes several seconds to execute:

SELECT instance.startdate
      ,instance.enddate
FROM (select mr.id
      FROM meeting_recurrence AS mr
      inner JOIN meeting_details md ON md.id = mr.meeting_template_id
      WHERE host_user_id=17) AS p
CROSS APPLY GetRecurrenceMeetingInstances(p.id,'2018-11-09 11:00:00','2018-11-09 15:00:00') AS instance
WHERE 21015 IS NOT NULL
AND instance.meetingid <> 21015

The internal select (select mr.id FROM meeting_recurrence...) returns in the above example instantly, with two ids.

Running GetRecurrenceMeetingInstances() with those two ids separately, returns empty results instantly.

Why does running the entire statement take so long compared to running them separately?

Execution plan image: https://imgur.com/a/3Ydym

Body:
It seems CROSS APPLY was calling GetRecurrenceMeetingInstances() a lot more than i thought. I solved the problem by saving the inner select in a local variable first:

DECLARE @innerresult table(meetingid int)
INSERT INTO @innerresult(meetingid) (select mr.id FROM meeting_recurrence AS mr inner JOIN meeting_details md ON md.id = mr.meeting_template_id
    WHERE host_user_id=17)

INSERT INTO @timeslots (startdate,enddate)
    SELECT instance.startdate,instance.enddate
    FROM (select meetingid FROM @innerresult) AS p
    CROSS APPLY GetRecurrenceMeetingInstances(p.meetingid,'2018-11-09 11:00:00','2018-11-09 15:00:00') AS instance


来源: stackexchange

问:
How to read macOS desktop file in cocoa app
I want to make cocoa app execute .sh file or other Operation,
this my code:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);
}

- (NSString *)cmd:(NSString *)cmd
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/bash"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}
</code>```

but log error：

```<code>ls: .: Operation not permitted
</code>```

how to do that?I search about macOS permit,Do I need use SMJobBless ?

答:
change

```<code> NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);
</code>```

with

```<code>NSLog(@"%@",[self cmd:@"cd ~/Desktop; ls;"]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make cocoa app execute .sh file or other Operation,
this my code:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);
}

- (NSString *)cmd:(NSString *)cmd
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/bash"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}

but log error：

ls: .: Operation not permitted

how to do that?I search about macOS permit,Do I need use SMJobBless ?

Body:
change

 NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);

with

NSLog(@"%@",[self cmd:@"cd ~/Desktop; ls;"]);


问:
I want to save a image from remote URL to local system in PHP
this is my PHP code

```<code><?php
$return = array();
$img_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$imageUrl = $img_url;
$dd = pathinfo($imageUrl);
$pic_name=  $dd['basename'];

@$rawImage = file_get_contents($imageUrl);

if($rawImage)
{
    file_put_contents("C:/xampp/htdocs/get_img/".$pic_name,$rawImage);

    echo 'Image Saved';
}
else
{

echo 'Error Occured';
}

?>
</code>```

but for this URL from google images, this code is giving me this.

"Warning: file_put_contents(C:/xampp/htdocs/get_img/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS): failed to open stream: Resource temporarily unavailable in C:\xampp\htdocs\get_img\get1.php on line 12"

how can i save this image?

答:
Try this, It will help you  </p>

```<code>$imageLink = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$random = mt_rand();
$size = getimagesize($imageLink);
$extension = image_type_to_extension($size[2]);
$filename = $random . $extension;
$path = "/images/";
file_put_contents(getcwd() . $path . $filename, file_get_contents($imageLink));
</code>```

Body:
this is my PHP code

<?php
$return = array();
$img_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$imageUrl = $img_url;
$dd = pathinfo($imageUrl);
$pic_name=  $dd['basename'];

@$rawImage = file_get_contents($imageUrl);

if($rawImage)
{
    file_put_contents("C:/xampp/htdocs/get_img/".$pic_name,$rawImage);

    echo 'Image Saved';
}
else
{

echo 'Error Occured';
}

?>

but for this URL from google images, this code is giving me this.

"Warning: file_put_contents(C:/xampp/htdocs/get_img/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS): failed to open stream: Resource temporarily unavailable in C:\xampp\htdocs\get_img\get1.php on line 12"

how can i save this image?

Body:
Try this, It will help you

$imageLink = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$random = mt_rand();
$size = getimagesize($imageLink);
$extension = image_type_to_extension($size[2]);
$filename = $random . $extension;
$path = "/images/";
file_put_contents(getcwd() . $path . $filename, file_get_contents($imageLink));


问:
now getting 401 unauthorized in jenkins when deploying artifact to archiva maven repo
This used to work before I upgraded Jenkins to 1.494. Now I get this error in Jenkins when using the build promotion plugin to copy the war artifact to the snapshot repo:

```<code>    ERROR: Failed to deploy artifacts: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
org.apache.maven.artifact.deployer.ArtifactDeploymentException: Failed to deploy artifacts: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:141)
    at hudson.maven.reporters.MavenArtifactRecord.deploy(MavenArtifactRecord.java:190)
    at hudson.maven.RedeployPublisher.perform(RedeployPublisher.java:173)
    at hudson.plugins.promoted_builds.Promotion$RunnerImpl.build(Promotion.java:187)
    at hudson.plugins.promoted_builds.Promotion$RunnerImpl.doRun(Promotion.java:141)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:586)
    at hudson.model.Run.execute(Run.java:1543)
    at hudson.model.Run.run(Run.java:1489)
    at hudson.plugins.promoted_builds.Promotion.run(Promotion.java:106)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:236)
Caused by: org.sonatype.aether.deployment.DeploymentException: Failed to deploy artifacts: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.sonatype.aether.impl.internal.DefaultDeployer.deploy(DefaultDeployer.java:280)
    at org.sonatype.aether.impl.internal.DefaultDeployer.deploy(DefaultDeployer.java:211)
    at org.sonatype.aether.impl.internal.DefaultRepositorySystem.deploy(DefaultRepositorySystem.java:443)
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:137)
    ... 10 more
Caused by: org.sonatype.aether.transfer.ArtifactTransferException: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(WagonRepositoryConnector.java:951)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(WagonRepositoryConnector.java:941)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:837)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector.put(WagonRepositoryConnector.java:467)
    at org.sonatype.aether.impl.internal.DefaultDeployer.deploy(DefaultDeployer.java:274)
    ... 13 more
Caused by: org.apache.maven.wagon.TransferFailedException: Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:613)
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:509)
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:490)
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:470)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:811)
    ... 15 more
</code>```

I have the creds in the settings.xml file:

```<code><server>
      <id>snapshots</id>
      <username>deployment</username>
      <password>deployment</password>
    </server>
</code>```

Not sure why this all of a sudden stopped working with 1.494. I downgraded incrementally to 1.491 and it still happened.  Very frustrating.

答:
I missed giving the deployment user the Role RepositoryManager after re-creating my Archiva repository. After adding the role, it solved the 401 when uploading artifacts.

See Archiva User Guide.

Body:
This used to work before I upgraded Jenkins to 1.494. Now I get this error in Jenkins when using the build promotion plugin to copy the war artifact to the snapshot repo:

    ERROR: Failed to deploy artifacts: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
org.apache.maven.artifact.deployer.ArtifactDeploymentException: Failed to deploy artifacts: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:141)
    at hudson.maven.reporters.MavenArtifactRecord.deploy(MavenArtifactRecord.java:190)
    at hudson.maven.RedeployPublisher.perform(RedeployPublisher.java:173)
    at hudson.plugins.promoted_builds.Promotion$RunnerImpl.build(Promotion.java:187)
    at hudson.plugins.promoted_builds.Promotion$RunnerImpl.doRun(Promotion.java:141)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:586)
    at hudson.model.Run.execute(Run.java:1543)
    at hudson.model.Run.run(Run.java:1489)
    at hudson.plugins.promoted_builds.Promotion.run(Promotion.java:106)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:236)
Caused by: org.sonatype.aether.deployment.DeploymentException: Failed to deploy artifacts: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.sonatype.aether.impl.internal.DefaultDeployer.deploy(DefaultDeployer.java:280)
    at org.sonatype.aether.impl.internal.DefaultDeployer.deploy(DefaultDeployer.java:211)
    at org.sonatype.aether.impl.internal.DefaultRepositorySystem.deploy(DefaultRepositorySystem.java:443)
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:137)
    ... 10 more
Caused by: org.sonatype.aether.transfer.ArtifactTransferException: Could not transfer artifact com.blah.data:RestWebServices:war:1.0-20121224.163825-2 from/to archiva.apache.snapshots (http://10.31.31.64:8080/archiva/repository/snapshots): Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(WagonRepositoryConnector.java:951)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(WagonRepositoryConnector.java:941)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:837)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector.put(WagonRepositoryConnector.java:467)
    at org.sonatype.aether.impl.internal.DefaultDeployer.deploy(DefaultDeployer.java:274)
    ... 13 more
Caused by: org.apache.maven.wagon.TransferFailedException: Failed to transfer file: http://10.31.31.64:8080/archiva/repository/snapshots/com/blah/data/RestWebServices/1.0-SNAPSHOT/RestWebServices-1.0-20121224.163825-2.war. Return code is: 401, ReasonPhrase:Unauthorized.
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:613)
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:509)
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:490)
    at org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:470)
    at org.sonatype.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:811)
    ... 15 more

I have the creds in the settings.xml file:

<server>
      <id>snapshots</id>
      <username>deployment</username>
      <password>deployment</password>
    </server>

Not sure why this all of a sudden stopped working with 1.494. I downgraded incrementally to 1.491 and it still happened.  Very frustrating.


问:
azure iothub sdk mqtt sample - error tls certificate
I'm trying to run the azure iothub sdk c sample of the mqtt protocol.
I've compiled hte project but when I run the program it returns some error about SSL routines

This i the complete error:

```<code>error:1416F086: SSL routines:tls_process_server_certificate:certificate verify failed
Info: Closing tlsio from a state other than TLSIO_STATE_EXT_OPEN or TLSIO_STATE_EXT_ERROR
</code>```

I got only this error repeated five times, one for each accepted message ready to be transmitted to the IoTHub.

I've read that I need to set trust to the openssl certs in the sample directory but I've not figured out how to do this task or how to avoid this problem.

Is there someone who has already faced this issue?

答: This document describes in detail how to prepare your development environment as well as how to run the samples on Linux, Windows or other platforms. Please refer to the section to rebuild you code and then run to test.</p>

Body:
I'm trying to run the azure iothub sdk c sample of the mqtt protocol.
I've compiled hte project but when I run the program it returns some error about SSL routines

This i the complete error:

error:1416F086: SSL routines:tls_process_server_certificate:certificate verify failed
Info: Closing tlsio from a state other than TLSIO_STATE_EXT_OPEN or TLSIO_STATE_EXT_ERROR

I got only this error repeated five times, one for each accepted message ready to be transmitted to the IoTHub.

I've read that I need to set trust to the openssl certs in the sample directory but I've not figured out how to do this task or how to avoid this problem.

Is there someone who has already faced this issue?


问:
get the continuous value of week number for the next following year
Can someone help me,
How to get the continuous value of week number for the next following year.
For example 50,51,52,53,54,55,56 ...

Here's my code below:

```<code>now <- as.Date(Sys.time())
dates <- seq(now, now + 900, by = "1 day")
dat <- data.frame(Dates = dates, Week = format(dates, format = "%W"))
dat
</code>```

I want the value continuing to 54,55,56,... instead of starting over from 0,1,2,.. on year change

Thanks

答:
Try</p>

```<code>round(difftime(dates, now, units = "weeks"))

# Time differences in weeks
#  [1]   0   0   0   0   1   1   1   1   1   1   1   2   2   2  ...
</code>```

Body:
Can someone help me,
How to get the continuous value of week number for the next following year.
For example 50,51,52,53,54,55,56 ...

Here's my code below:

now <- as.Date(Sys.time())
dates <- seq(now, now + 900, by = "1 day")
dat <- data.frame(Dates = dates, Week = format(dates, format = "%W"))
dat

I want the value continuing to 54,55,56,... instead of starting over from 0,1,2,.. on year change

Thanks

Body:
Try

round(difftime(dates, now, units = "weeks"))

# Time differences in weeks
#  [1]   0   0   0   0   1   1   1   1   1   1   1   2   2   2  ...


问:
How to analyise battery usage of android application and optimize it?
I would like to analyze battery usage of my application, I mean the parts of the app, such as
broadcastreceivers, listeners, services, etc.., how much battery uses. I need a detailed list, and from the list, I would like to optimize battery usage.

Method would be similar than using Memory Analyzer (http://android-developers.blogspot.hu/2011/03/memory-analysis-for-android.html)
Is there any tool for it? I used some battery tracking app from PlayStore, but global battery usage of application is not enough.

答:
This question is quite old, but, i guess is still relevant.

Battery consumption is a really big issue, thats left unresolved so far, so that only 'hard' work and learning might help you. There's no public API which gives you a helpful look of the battery, and no 'paying' sdk which gives you analytics on the battery, BUT, you can learn a lot from running a battery stats command from the ADB.

Run this command from your terminal : adb shell dumpsys batterystats > results.txt

Few things to observe in the results.txt file :

The results are taken from the beginning of the time you unplugged your phone from the charger(if it reached 100%)

If you're fully (or almost) charged, the battery stats will be erased, so if you have an issue, and you can't process the stats, don't fully charge your device until you can run this command from a computer.

We found that using wakelock is a huge battery consumption. You can check on the results how much time an application has a wakelock.
So, for example, if i see this line :
Wake lock *sync*/com.android.contacts/com.whatsapp/WhatsApp: 128ms partial (4 times) realtime i can understand from it that WhatsApp is running a wakelock for 128 milliseconds, which is ok, however, if the running time was hours, this will be bad, and will kill my battery.

Wifi Lock - you can also check if the wifi keeps your device running, and if you see these lines, with high timing, it should appear suspicious.

Wifi Running: 3h 23m (87.0%)
Full Wifi Lock: 2h 3m (91.0%)
Wifi Scan: 1h 54m (79.0%) 44x

Check your CPU time : for example :

Proc com.android.phone:
  CPU: 3h 34m 12s 910ms usr + 7s 250ms krn ; 0ms fg

This means, that the phone app worked for more than 3 hours, which is a lot(unless the user was talking all this time)

Check out your bluetooth

1002:
Wake lock bluedroid_timer: 3m 29s 892ms partial (158 times) realtime
Foreground for: 8h 1m 2s 834ms
Active for: 8h 1m 3s 546ms
Total cpu time: u=48m 38s 350ms s=29s 752ms p=204mAh
Proc com.android.bluetooth:
  CPU: 23m 25s 230ms usr + 22s 520ms krn ; 0ms fg
  211 starts
Proc *wakelock*:
  CPU: 0ms usr + 2ms krn ; 0ms fg
Apk com.android.bluetooth:
  Service com.android.bluetooth.gatt.GattService:
    Created for: 1h 13m 52s 667ms upt

8 hours is A LOT for bluetooth.

How much time did your services run for ?

Service com.google.location.nearby.direct.service.NearbyDirectService:
    Created for: 17m 50s 232ms uptime
    Starts: 212, launches: 212

In the end of this file, you have a summary of all the applications running on your device. Its pretty nice, and gives you an idea of how much time/cpu/wifi/network/service each apk consumed.
For example,

u0a1091:
Mobile network: 14.96KB received, 17.10KB sent (packets 120 received, 183 sent)
Mobile radio active: 4m 30s 136ms (10.5%) 18x @ 892 mspp
Active for: 8h 1m 3s 546ms
Total cpu time: u=520ms s=210ms p=0.0653mAh
Proc org.telegram.messenger:
  CPU: 670ms usr + 260ms krn ; 0ms fg

There are a lot more options to go through in this file, and it takes a while to figure out more, this is what i've learned from my researches.


问:
Python - Update Dictionary With User Input
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

```<code>while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break
</code>```

When running this code i get the following error:

```<code>Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range
</code>```

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

答:
The updates is a list. If you want to store the updated records, you should write as:

```<code>Employee[dict_key] = updates
</code>```

This will create a structure:

```<code>{'1234': ['John', 'IT', 'Manager']}
</code>```

Also as pointed by the comments, if the input is separated by , then use split(',')

Body:
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break

When running this code i get the following error:

Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

Body:
The updates is a list. If you want to store the updated records, you should write as:

Employee[dict_key] = updates

This will create a structure:

{'1234': ['John', 'IT', 'Manager']}

Also as pointed by the comments, if the input is separated by , then use split(',')


问:
Nested Case Statement for multiple condition
I have a data set like bellow image.
I need in the data set

Grade Red is present then in OpenSegment=yes if not but
Grade Amber is present then in OpenSegment=yes if not but
Grade Blue is present then in OpenSegment=yes

for that I write

```<code> COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE '' END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE '' END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE '' END
                )
</code>```

but not working.

Result after putting  ELSE NULL

答:
Good answer by Tim Biegeleisen but looking at the question shouldn't you do the case when on the Grade column instead of ID?

So code would be;

```<code>SELECT
    CASE WHEN airag.Grade IN ('Red', 'Amber', 'Blue') THEN 'yes' END AS OpenSegment
    -- other columns
FROM yourTable
</code>```

Body:
I have a data set like bellow image.
I need in the data set

Grade Red is present then in OpenSegment=yes if not but
Grade Amber is present then in OpenSegment=yes if not but
Grade Blue is present then in OpenSegment=yes

for that I write

 COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE '' END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE '' END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE '' END
                )

but not working.

Result after putting  ELSE NULL

Body:
Good answer by Tim Biegeleisen but looking at the question shouldn't you do the case when on the Grade column instead of ID?

So code would be;

SELECT
    CASE WHEN airag.Grade IN ('Red', 'Amber', 'Blue') THEN 'yes' END AS OpenSegment
    -- other columns
FROM yourTable


问:
How to make switch tab content fixed?
I have switch tab but my problem is how can make a content fixed?
Example if I switch tabs my content is still fixed even short or long content

On this code when I have long content my layout will go long and my content is short my content also will be long.

How can set layout be fixed?

.tabs{
     margin-bottom:25px;
    }
    .nav-tabs{
    }
    .nav-tabs li{
     position:relative;
     display:block;
     float:left;
     margin-right:1px;
    }
    .nav-tabs li a{
     display:block;
     padding:10px 20px;
     background:#efefef;
     text-decoration:none;
    }
    .nav-tabs li > i{
     color:#efefef;
    }
    .nav-tabs li > i{
     position: absolute;
     bottom: -10px;
     font-size: 16px;
     width: 20px;
     left: 50%;
     margin-left: -10px;
    }
    .nav-tabs li a:hover{
     color:#fff;
     background:#666;
     text-decoration:none;
    }
    .nav-tabs li a:active, .nav-tabs li.active a{
     color:#fff;
     background:#666;
    }
    .tab-content{
     padding:20px 0;
     background:#ffffff;
    }
    .tab-content > .tab-pane{
     display:none;
    }
    .tab-content > .active{
     display:block;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="tabs">
                    <ul class="nav nav-tabs">
                      <li class="active">  Sample Tab #1  </li>
                      <li>  Sample Tab #2  </li>
                      <li>  Sample Tab #3  </li>
                    </ul>
                    <div class="tab-content">
                      <div id="sampletab1" class="tab-pane active">
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor.</p>
                      </div>
                      <div id="sampletab2" class="tab-pane">
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque.</p>
                      </div>
                      <div id="sampletab3" class="tab-pane">
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor. In iaculis viverra neque, ac eleifend ante lobortis id. In viverra ipsum ac eros tristique dignissim. Donec aliquam velit vitae mi dictum. </p>
                      </div>
                    </div>
                  </div></code>```

Thankyou

答:
You can use this code to determine the max height .tab-pane then you assign this height to the .tab-content so it will be fixed and take the height of the max one</p>

```<code>var maxHeight=0;
$(".tab-content .tab-pane").each(function(){
$(this).addClass("active");
var height = $(this).height();
maxHeight = height>maxHeight?height:maxHeight;
$(this).removeClass("active");
});
$(".tab-content .tab-pane:first").addClass("active");
$(".tab-content").height(maxHeight);
</code>```

Title: How to make switch tab content fixed?

Body:
I have switch tab but my problem is how can make a content fixed?
Example if I switch tabs my content is still fixed even short or long content

On this code when I have long content my layout will go long and my content is short my content also will be long.

How can set layout be fixed?

.tabs{
     margin-bottom:25px;
    }
    .nav-tabs{
    }
    .nav-tabs li{
     position:relative;
     display:block;
     float:left;
     margin-right:1px;
    }
    .nav-tabs li a{
     display:block;
     padding:10px 20px;
     background:#efefef;
     text-decoration:none;
    }
    .nav-tabs li > i{
     color:#efefef;
    }
    .nav-tabs li > i{
     position: absolute;
     bottom: -10px;
     font-size: 16px;
     width: 20px;
     left: 50%;
     margin-left: -10px;
    }
    .nav-tabs li a:hover{
     color:#fff;
     background:#666;
     text-decoration:none;
    }
    .nav-tabs li a:active, .nav-tabs li.active a{
     color:#fff;
     background:#666;
    }
    .tab-content{
     padding:20px 0;
     background:#ffffff;
    }
    .tab-content > .tab-pane{
     display:none;
    }
    .tab-content > .active{
     display:block;
    }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  Sample Tab #1

  Sample Tab #2

  Sample Tab #3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce velit tortor, dictum in gravida nec, aliquet non lorem. Donec vestibulum justo a diam ultricies pellentesque. Quisque mattis diam vel lacus tincidunt elementum. Sed vitae adipiscing turpis. Aenean ligula nibh, molestie id viverra a, dapibus at dolor. In iaculis viverra neque, ac eleifend ante lobortis id. In viverra ipsum ac eros tristique dignissim. Donec aliquam velit vitae mi dictum.

Thankyou

Body:
You can use this code to determine the max height .tab-pane then you assign this height to the .tab-content so it will be fixed and take the height of the max one

var maxHeight=0;
$(".tab-content .tab-pane").each(function(){
$(this).addClass("active");
var height = $(this).height();
maxHeight = height>maxHeight?height:maxHeight;
$(this).removeClass("active");
});
$(".tab-content .tab-pane:first").addClass("active");
$(".tab-content").height(maxHeight);


问:
How do I correct the following error code: ValueError: Cannot feed value of shape (64, 15) for Tensor 'InputData/X:0', which has shape '(?, 16, 1)'
I'm trying to use an LSTM Neural Network to perform a prediction. The data set has 16 X values to every Y value. As far as I can tell there is a problem with the shapes of the train X & Y arrays or the test X & Y arrays or both. I've tried reshaping, it appears my adjustments are not correct. Below is the code along the with output from Jupyter Notebook. Thank you in advance for your insights.

```<code>from __future__ import division, print_function, absolute_import

#import pandas as pd
import tflearn
import numpy as np
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf

def myRNN():
    tf.reset_default_graph()
    # Network building
    net = tflearn.input_data(shape=[None, 16, 1])
    net = tflearn.lstm(net, 32, dropout=0.8,bias=True)
    net = tflearn.fully_connected(net, 1, activation='relu')
    net = tflearn.regression(net, optimizer='adam', loss='mean_square', learning_rate=0.003)

    #Gather the Training Data
    csvData = np.genfromtxt('LabelCall5Data.csv', delimiter=',')
    trainX = csvData[0:3360,0:15]
    trainY = csvData[0:3360,16]

    #Transpose the input Data
    trainX = np.reshape(trainX, (-1, 16, 1))
    trainY = np.reshape(trainY, (-1, 1))
    print('trainX Shape: ', trainX.shape)
    print('trainY Shape: ', trainY.shape)

    #Gather the Testing Data
    testX = csvData[3361:,0:15]
    testY = csvData[3361:,16]
    print('testY Shape: ', testX.shape)
    print('testY Shape: ', testY.shape)

    # Training
    model = tflearn.DNN(net)
    model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True)

    # Predict the future values
    predictY = model.predict(testX)

    print("---------TEST ERROR-----------")
    expected = np.array(testY).flatten()
    predicted = np.array(predictY).flatten()
    error = sum(((expected - predicted) **2)/len(expected))
    print(error)`enter code here`
</code>```

The output is below.

```<code>Training Step: 49  | total loss: 24915.56836 | time: 0.557s
| Adam | epoch: 001 | loss: 24915.56836 - binary_acc: 0.0000 -- iter: 3136/3150

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-130-e193b95cc714> in <module>()
----> 1 myRNN()

<ipython-input-129-b039a187b4c6> in myRNN()
     37     # Training
     38     model = tflearn.DNN(net)
---> 39     model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True)
     40
     41     # Predict the future values

~/anaconda3/lib/python3.6/site-packages/tflearn/models/dnn.py in fit(self, X_inputs, Y_targets, n_epoch, validation_set, show_metric, batch_size, shuffle, snapshot_epoch, snapshot_step, excl_trainops, validation_batch_size, run_id, callbacks)
    214                          excl_trainops=excl_trainops,
    215                          run_id=run_id,
--> 216                          callbacks=callbacks)
    217
    218     def fit_batch(self, X_inputs, Y_targets):

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in fit(self, feed_dicts, n_epoch, val_feed_dicts, show_metric, snapshot_step, snapshot_epoch, shuffle_all, dprep_dict, daug_dict, excl_trainops, run_id, callbacks)
    337                                                        (bool(self.best_checkpoint_path) | snapshot_epoch),
    338                                                        snapshot_step,
--> 339                                                        show_metric)
    340
    341                             # Update training state

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in _train(self, training_step, snapshot_epoch, snapshot_step, show_metric)
    845             if show_metric and self.metric is not None:
    846                 eval_ops.append(self.metric)
--> 847             e = evaluate_flow(self.session, eval_ops, self.test_dflow)
    848             self.val_loss = e[0]
    849             if show_metric and self.metric is not None:

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in evaluate_flow(session, ops_to_evaluate, dataflow)
    996
    997         while feed_batch:
--> 998             r = session.run(ops_to_evaluate, feed_batch)
    999             current_batch_size = get_current_batch_size(feed_batch, dataflow)
   1000             for i in range(len(r)):

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    887     try:
    888       result = self._run(None, fetches, feed_dict, options_ptr,
--> 889                          run_metadata_ptr)
    890       if run_metadata:
    891         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1094                 'Cannot feed value of shape %r for Tensor %r, '
   1095                 'which has shape %r'
-> 1096                 % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
   1097           if not self.graph.is_feedable(subfeed_t):
   1098             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (64, 15) for Tensor 'InputData/X:0', which has shape '(?, 16, 1)'
</code>```

答:
The problem is that when you are creating trainX, you only take 15 values and not 16.

Writing trainX = csvData[0:3360,0:15] only gives you the first 15 channels in the second dimension. Replace it with trainX = csvData[0:3360,0:16].

And your testing data has the same issue, with the bonus of not being reshaped before feeding it to the network. This results in not having the right number of dimensions either.

Body:
I'm trying to use an LSTM Neural Network to perform a prediction. The data set has 16 X values to every Y value. As far as I can tell there is a problem with the shapes of the train X & Y arrays or the test X & Y arrays or both. I've tried reshaping, it appears my adjustments are not correct. Below is the code along the with output from Jupyter Notebook. Thank you in advance for your insights.

from __future__ import division, print_function, absolute_import

#import pandas as pd
import tflearn
import numpy as np
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf

def myRNN():
    tf.reset_default_graph()
    # Network building
    net = tflearn.input_data(shape=[None, 16, 1])
    net = tflearn.lstm(net, 32, dropout=0.8,bias=True)
    net = tflearn.fully_connected(net, 1, activation='relu')
    net = tflearn.regression(net, optimizer='adam', loss='mean_square', learning_rate=0.003)

    #Gather the Training Data
    csvData = np.genfromtxt('LabelCall5Data.csv', delimiter=',')
    trainX = csvData[0:3360,0:15]
    trainY = csvData[0:3360,16]

    #Transpose the input Data
    trainX = np.reshape(trainX, (-1, 16, 1))
    trainY = np.reshape(trainY, (-1, 1))
    print('trainX Shape: ', trainX.shape)
    print('trainY Shape: ', trainY.shape)

    #Gather the Testing Data
    testX = csvData[3361:,0:15]
    testY = csvData[3361:,16]
    print('testY Shape: ', testX.shape)
    print('testY Shape: ', testY.shape)

    # Training
    model = tflearn.DNN(net)
    model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True)

    # Predict the future values
    predictY = model.predict(testX)

    print("---------TEST ERROR-----------")
    expected = np.array(testY).flatten()
    predicted = np.array(predictY).flatten()
    error = sum(((expected - predicted) **2)/len(expected))
    print(error)`enter code here`

The output is below.

Training Step: 49  | total loss: 24915.56836 | time: 0.557s
| Adam | epoch: 001 | loss: 24915.56836 - binary_acc: 0.0000 -- iter: 3136/3150

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-130-e193b95cc714> in <module>()
----> 1 myRNN()

<ipython-input-129-b039a187b4c6> in myRNN()
     37     # Training
     38     model = tflearn.DNN(net)
---> 39     model.fit(trainX, trainY, n_epoch=100, validation_set=(testX, testY), show_metric=True)
     40
     41     # Predict the future values

~/anaconda3/lib/python3.6/site-packages/tflearn/models/dnn.py in fit(self, X_inputs, Y_targets, n_epoch, validation_set, show_metric, batch_size, shuffle, snapshot_epoch, snapshot_step, excl_trainops, validation_batch_size, run_id, callbacks)
    214                          excl_trainops=excl_trainops,
    215                          run_id=run_id,
--> 216                          callbacks=callbacks)
    217
    218     def fit_batch(self, X_inputs, Y_targets):

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in fit(self, feed_dicts, n_epoch, val_feed_dicts, show_metric, snapshot_step, snapshot_epoch, shuffle_all, dprep_dict, daug_dict, excl_trainops, run_id, callbacks)
    337                                                        (bool(self.best_checkpoint_path) | snapshot_epoch),
    338                                                        snapshot_step,
--> 339                                                        show_metric)
    340
    341                             # Update training state

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in _train(self, training_step, snapshot_epoch, snapshot_step, show_metric)
    845             if show_metric and self.metric is not None:
    846                 eval_ops.append(self.metric)
--> 847             e = evaluate_flow(self.session, eval_ops, self.test_dflow)
    848             self.val_loss = e[0]
    849             if show_metric and self.metric is not None:

~/anaconda3/lib/python3.6/site-packages/tflearn/helpers/trainer.py in evaluate_flow(session, ops_to_evaluate, dataflow)
    996
    997         while feed_batch:
--> 998             r = session.run(ops_to_evaluate, feed_batch)
    999             current_batch_size = get_current_batch_size(feed_batch, dataflow)
   1000             for i in range(len(r)):

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    887     try:
    888       result = self._run(None, fetches, feed_dict, options_ptr,
--> 889                          run_metadata_ptr)
    890       if run_metadata:
    891         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1094                 'Cannot feed value of shape %r for Tensor %r, '
   1095                 'which has shape %r'
-> 1096                 % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
   1097           if not self.graph.is_feedable(subfeed_t):
   1098             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (64, 15) for Tensor 'InputData/X:0', which has shape '(?, 16, 1)'


问:
AngularDart Components Dropdown Selects selectionChange event
I'm using material-dropdown-select component, but I didn't find the way to trigger the event when the user changes the  selection.

(on selection change ??)

```<code><material-dropdown-select class="psDropDown" dir="rtl"
                    [buttonText]="dropDownSelectLabel"
                    [selection]="singleSelectModel"
                    [options]="lookUpOptions"
                    ></material-dropdown-select>
</code>```

How can I react to a selection change event

答: You can subscribe to selectionChanges of the selection model

Body:
I'm using material-dropdown-select component, but I didn't find the way to trigger the event when the user changes the  selection.

(on selection change ??)

<material-dropdown-select class="psDropDown" dir="rtl"
                    [buttonText]="dropDownSelectLabel"
                    [selection]="singleSelectModel"
                    [options]="lookUpOptions"
                    ></material-dropdown-select>

How can I react to a selection change event


问:
Odd visual issue with ListView item layout with two pressable pieces
I wanted to make a ListView where the items have two pressable pieces, like the layouts that show up in a couple of places in the stock Android phone/contacts application:

I have the layout working fine, including handling events from each piece separately, except for a visual issue when the smaller piece is pressed.  In my application the smaller piece only gets a small ellipse for the background when it is pressed, like this:

Note that is actually not my application - that is NubDial, but my application has the same problem.  Since NubDial uses the exact same XML layout as the phone app, I'm not sure how relevant the list item layouts are, but here they are anyway:

Contacts list: contacts_list_item.xml

NubDial: contacts_list_item.xml

Does anybody know what might be happening there?

答:
The layout was using this background drawable for the button on the right:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_window_focused="false"
        android:drawable="@android:color/transparent" />
    <item android:state_focused="false" android:state_pressed="true"
        android:drawable="@*android:drawable/list_selector_background_transition" />
    <item android:state_focused="false" android:state_pressed="false"
        android:drawable="@android:drawable/screen_background_dark"/>

</selector>
</code>```

Copying the list_selector_background_transition drawable and its images into my project fixed the issue.  I thought this was pretty odd, and I would have liked to use the system drawable if possible.  Anyone know what was going on?

ContentLicense: CC BY-SA 4.0

Body:
The layout was using this background drawable for the button on the right:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_window_focused="false"
        android:drawable="@android:color/transparent" />
    <item android:state_focused="false" android:state_pressed="true"
        android:drawable="@*android:drawable/list_selector_background_transition" />
    <item android:state_focused="false" android:state_pressed="false"
        android:drawable="@android:drawable/screen_background_dark"/>

</selector>

Copying the list_selector_background_transition drawable and its images into my project fixed the issue.  I thought this was pretty odd, and I would have liked to use the system drawable if possible.  Anyone know what was going on?

ContentLicense: CC BY-SA 2.5


问:
UI Automator / Ui Automator2 : Scroll and find child UI Element in Recycler View
I want to acheive something like this.

    Open Gmail app, look for a particular mail (scroll also) and click on it.

  In the method below, I am able to search for a particular mail and click on it.

```<code>public void openMailWithParticularTitle(){
        UiObject2 obj =  Utils.getDeviceInstance().findObject(By.res("com.google.android.gm:id/recycler_list_view"));
        List<UiObject2> mails = obj.findObjects(By.clazz("android.view.View"));
        for(int i =0; i<mails.size();i++){
            if(mails.get(i).getContentDescription()!=null && mails.get(i).getContentDescription().contains("My Mail Link")){
                mails.get(i).click();
                break;
            }
        }
    }
</code>```

But it only looks for visible items, doesn't scroll to look for child elements.

So I looked around and tried this, but this also doesn't seem to work due to some reasons.

```<code> public void scrollMailWithParticularTitle2() throws UiObjectNotFoundException {
        openApp(Const.package_gmail_app,true);
        UiScrollable settingsItem = new UiScrollable(new UiSelector()
                .className("android.support.v7.widget.RecyclerView"));
        UiObject about = settingsItem.getChildByText(new UiSelector()
                .className("android.view.View"), "My Mail Link");
        about.click();
    }
</code>```

    Any help/ suggestion would be appreciated.
(I've limited knowledge of UI testing)

答:
Try with scrollIntoView function:

Perform a scroll forward action to move through the scrollable layout element until a visible item that matches the selector is found

I used it once to find my app in apps menu:

```<code>UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));
allAppsButton.clickAndWaitForNewWindow();

UiScrollable appView = new UiScrollable(new UiSelector().scrollable(true));
appView.scrollIntoView(new UiSelector().text(APP_TITLE));
mDevice.findObject(new UiSelector().text(APP_TITLE)).clickAndWaitForNewWindow();
</code>```

Body:
I want to acheive something like this.

    Open Gmail app, look for a particular mail (scroll also) and click on it.

  In the method below, I am able to search for a particular mail and click on it.

public void openMailWithParticularTitle(){
        UiObject2 obj =  Utils.getDeviceInstance().findObject(By.res("com.google.android.gm:id/recycler_list_view"));
        List<UiObject2> mails = obj.findObjects(By.clazz("android.view.View"));
        for(int i =0; i<mails.size();i++){
            if(mails.get(i).getContentDescription()!=null && mails.get(i).getContentDescription().contains("My Mail Link")){
                mails.get(i).click();
                break;
            }
        }
    }

But it only looks for visible items, doesn't scroll to look for child elements.

So I looked around and tried this, but this also doesn't seem to work due to some reasons.

 public void scrollMailWithParticularTitle2() throws UiObjectNotFoundException {
        openApp(Const.package_gmail_app,true);
        UiScrollable settingsItem = new UiScrollable(new UiSelector()
                .className("android.support.v7.widget.RecyclerView"));
        UiObject about = settingsItem.getChildByText(new UiSelector()
                .className("android.view.View"), "My Mail Link");
        about.click();
    }

    Any help/ suggestion would be appreciated.
(I've limited knowledge of UI testing)

Body:
Try with scrollIntoView function:

Perform a scroll forward action to move through the scrollable layout element until a visible item that matches the selector is found

I used it once to find my app in apps menu:

UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));
allAppsButton.clickAndWaitForNewWindow();

UiScrollable appView = new UiScrollable(new UiSelector().scrollable(true));
appView.scrollIntoView(new UiSelector().text(APP_TITLE));
mDevice.findObject(new UiSelector().text(APP_TITLE)).clickAndWaitForNewWindow();


问:
How to find column names for all tables in all databases in SQL Server
I want to find all column names in all tables in all databases. Is there a query that can do that for me?

答:
try the below query

```<code>DECLARE @Query VARCHAR(max)
SELECT @Query = 'USE ? SELECT ''?'' AS DataBaseName,
                                sys.columns.name AS ColumnName  ,
                                sys.tables.name  AS TableName   ,
                                schema_name (sys.tables.schema_Id) AS schemaName
                         FROM sys.columns
                         JOIN sys.tables
              ON sys.columns.object_id = sys.tables.object_id
              WHERE sys.columns.name = ''id'' '
EXEC SP_MSFOREACHDB @Query
</code>```

gives list of tables containing ID column from all databases.

Body:
try the below query

DECLARE @Query VARCHAR(max)
SELECT @Query = 'USE ? SELECT ''?'' AS DataBaseName,
                                sys.columns.name AS ColumnName  ,
                                sys.tables.name  AS TableName   ,
                                schema_name (sys.tables.schema_Id) AS schemaName
                         FROM sys.columns
                         JOIN sys.tables
              ON sys.columns.object_id = sys.tables.object_id
              WHERE sys.columns.name = ''id'' '
EXEC SP_MSFOREACHDB @Query

gives list of tables containing ID column from all databases.


问:
Jmeter script recorder and recording for multiple users/threads
I created in Jmeter a Test Plan that looks like that:

the idea is to keep track of all the APIs the browser access between two pages. So, I open the localhost:63948/Home/LoginEmailSenha and I go until the other page I want. Under the Recording Controller label I get the list of the APIs.

But what can I do so that it feels like there isn't only one person accessing but actually 200? I tried to change the Number of Threads(users) at the Thread Group but nothing seems to change as I want to get the API errors that occured because there are too many people.

答:
HTTP(S) Test Script Recorder is used to create a test scenario "skeleton", it basically stands between browser and application under test, captures requests and generates relevant HTTP Request samplers.

If you need to mimic 200 users you need to replay the recorded scenario with increased number of threads.

References:

JMeter Proxy Step by Step

Building a Web Test Plan

Building an Advanced Web Test Plan

If your target is to simulate the load during recording time you can take a look at JMeter Chrome Extension, it has FollowMe Mode when any your online activity is replicated with a given number of virtual users.


问:
Sharepoint Workbench : This site can provide a secure connection
I've created a webpart.
I'm using a Node.js, with npm, Yeoman and Gulp.
I installed a certificate with gulp trust-dev-cert, and I have this error on my page "This site can provide a secure connection", and the app isn't accessible.

This is my package.json

My node version is 8.9.1.
I tried to change the NODE_NO_HTTP2=1 environment variable , like this tutorial  , but it doesn't work.

Do you have any idea to resolve my certificate problem ?

Thank you very much

答:
Not sure why it isn't working after NODE_NO_HTTP2=1 changes.

I would suggest that you uninstall the current Node.js installation and reinstall the Node.js with the previous LTS version.

The previous Node.js version is v 6.12.

You can download it and install it on your machine and then run the gulp commands.

Link - Node.js v6.12.0

As mentioned here, currently only Node v6 is supported in SPFx


问:
python how to pad numpy array with zeros
I want to know how I can pad a 2D numpy array with zeros using python 2.6.6 with numpy version 1.5.0. But these are my limitations. Therefore I cannot use np.pad. For example, I want to pad a with zeros such that its shape matches b. The reason why I want to do this is so I can do:

```<code>b-a
</code>```

such that

```<code>>>> a
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]])
>>> b
array([[ 3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.]])
>>> c
array([[1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0]])
</code>```

The only way I can think of doing this is appending, however this seems pretty ugly. is there a cleaner solution possibly using b.shape?

Edit,
Thank you to  MSeiferts  answer. I had to clean it up a bit, and this is what I got:

```<code>def pad(array, reference_shape, offsets):
    """
    array: Array to be padded
    reference_shape: tuple of size of ndarray to create
    offsets: list of offsets (number of elements must be equal to the dimension of the array)
    will throw a ValueError if offsets is too big and the reference_shape cannot handle the offsets
    """

    # Create an array of zeros with the reference shape
    result = np.zeros(reference_shape)
    # Create a list of slices from offset to offset + shape in each dimension
    insertHere = [slice(offsets[dim], offsets[dim] + array.shape[dim]) for dim in range(array.ndim)]
    # Insert the array in the result at the specified offsets
    result[insertHere] = array
    return result
</code>```

Body:
I want to know how I can pad a 2D numpy array with zeros using python 2.6.6 with numpy version 1.5.0. But these are my limitations. Therefore I cannot use np.pad. For example, I want to pad a with zeros such that its shape matches b. The reason why I want to do this is so I can do:

b-a

such that

>>> a
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]])
>>> b
array([[ 3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.]])
>>> c
array([[1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 0]])

The only way I can think of doing this is appending, however this seems pretty ugly. is there a cleaner solution possibly using b.shape?

Edit,
Thank you to  MSeiferts  answer. I had to clean it up a bit, and this is what I got:

def pad(array, reference_shape, offsets):
    """
    array: Array to be padded
    reference_shape: tuple of size of ndarray to create
    offsets: list of offsets (number of elements must be equal to the dimension of the array)
    will throw a ValueError if offsets is too big and the reference_shape cannot handle the offsets
    """

    # Create an array of zeros with the reference shape
    result = np.zeros(reference_shape)
    # Create a list of slices from offset to offset + shape in each dimension
    insertHere = [slice(offsets[dim], offsets[dim] + array.shape[dim]) for dim in range(array.ndim)]
    # Insert the array in the result at the specified offsets
    result[insertHere] = array
    return result

Body:
In case you need to add a fence of 1s to an array:

>>> mat = np.zeros((4,4), np.int32)
>>> mat
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
>>> mat[0,:] = mat[:,0] = mat[:,-1] =  mat[-1,:] = 1
>>> mat
array([[1, 1, 1, 1],
       [1, 0, 0, 1],
       [1, 0, 0, 1],
       [1, 1, 1, 1]])


问:
How to paint a gradient color in Android on a Canvas with the color changing?
I need to paint the background of my Canvas one color with shading/gradient applied, but each onDraw call I would like to potentially change the color.

I am having trouble doing this without creating a new object each onDraw call. Anyone have any ideas?  If I use drawPaint() and set a new shader() to my paint, then I have created a new shader object and if I create a new GradientDrawable() I have as well.  I want to avoid GC.

I thought I could reuse one GradientDrawable() object and call the .setColor() method, but this just resets any gradient data associated it and paints the drawable as that solid color.

Anyone?

答: Unfortunately you have to create a new LinearGradient everytime. Note that you don't have to use a GradientDrawable, you can draw the shape yourself with a Paint on which you set the shader.</p>


问:
Configure Smtp Virtual Server in windows Server using Powershell-(Relay,Connection)
Using powershell I have to enable SMTP and

Add relay Ip

Add connection IPs

Set Access Control Authentication

I found following code for the above operation

```<code>$GetSMTP = Get-CimInstance -Namespace "root\MicrosoftIISv2" -Class "IISSMTPServerSetting" -Filter "Name ='SmtpSvc/1'"
$RelayIps =  @(10,92,32,83,127,0,0,1)
$GetSMTP.RelayIpList = $RelayIps
Set-CimInstance -InputObject $GetSMTP

$GetSMTP
$GetSMTP = Get-CimInstance -Namespace "root\MicrosoftIISv2" -Class "IIsIPSecuritySetting" -Filter "Name ='SmtpSvc/1'"

$NewConnectionIps = @(
                     "10.92.32.80, 10.92.32.81";
                     "10.92.32.83,127.0.0.1";
                      )
$GetSMTP.ipgrant += $NewConnectionIps
Set-CimInstance -InputObject $GetSMTP

$GetSMTP
</code>```

The above powershell code executed successfully and it list as it is added.

But when i connect to smtp server, the following error is throwing

I have a found a solution to solve the above issue, To delete the folders inside "C:\inetpub\mailroot" and where i am able to start the default Smtp Virtual Server, but again facing an issue while click smtp vitrual server properties

答:
In addition to PonVimal's answer (accepted):

This solution uses Get-NetworkAddress function from Indented.NetworkTools

If you would like to specify relay for a group of computers instead of single address you can use System.DirectoryServices in a following manner (thanks to this answer as well):

```<code>$IpRelayList = @("192.168.1.0, 255.255.0.0",
                "127.3.4.0, 255.255.255.192")

#adding relays
$iisObject = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/smtpsvc/1")
$relays = $iisObject.Properties["RelayIpList"].Value
$bindingFlags = [Reflection.BindingFlags] "Public, Instance, GetProperty"
$ipList = $relays.GetType().InvokeMember("IPGrant", $bindingFlags, $null, $relays, $null);

#if relay list is empty we are retrieving host subnets and adding to relay
$Networkip =@()
if($IpRelayList.Count -eq 0)
{
    $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName localhost | ? {$_.IPEnabled}
    foreach($Network in $Networks)
    {
        $line = Get-NetworkAddress $Network.IpAddress[0] $Network.IpSubnet[0]
        $line = $line + ", " + $Network.IpSubnet[0]
        $Networkip += $line
    }
}

$ipList = $Networkip + $IpRelayList

# This is important, we need to pass an object array of one element containing our ipList array
[Object[]] $ipArray = @()
$ipArray += , $ipList

# Now update
$bindingFlags = [Reflection.BindingFlags] "Public, Instance, SetProperty"
$ipList = $relays.GetType().InvokeMember("IPGrant", $bindingFlags, $null, $relays, $ipArray);

$iisObject.Properties["RelayIpList"].Value = $relays
$iisObject.CommitChanges()
</code>```

Body:
Using powershell I have to enable SMTP and

Add relay Ip

Add connection IPs

Set Access Control Authentication

I found following code for the above operation

$GetSMTP = Get-CimInstance -Namespace "root\MicrosoftIISv2" -Class "IISSMTPServerSetting" -Filter "Name ='SmtpSvc/1'"
$RelayIps =  @(10,92,32,83,127,0,0,1)
$GetSMTP.RelayIpList = $RelayIps
Set-CimInstance -InputObject $GetSMTP

$GetSMTP
$GetSMTP = Get-CimInstance -Namespace "root\MicrosoftIISv2" -Class "IIsIPSecuritySetting" -Filter "Name ='SmtpSvc/1'"

$NewConnectionIps = @(
                     "10.92.32.80, 10.92.32.81";
                     "10.92.32.83,127.0.0.1";
                      )
$GetSMTP.ipgrant += $NewConnectionIps
Set-CimInstance -InputObject $GetSMTP

$GetSMTP

The above powershell code executed successfully and it list as it is added.

But when i connect to smtp server, the following error is throwing

I have a found a solution to solve the above issue, To delete the folders inside "C:\inetpub\mailroot" and where i am able to start the default Smtp Virtual Server, but again facing an issue while click smtp vitrual server properties

Body:
In addition to PonVimal's answer (accepted):

This solution uses Get-NetworkAddress function from Indented.NetworkTools

If you would like to specify relay for a group of computers instead of single address you can use System.DirectoryServices in a following manner (thanks to this answer as well):

$IpRelayList = @("192.168.1.0, 255.255.0.0",
                "127.3.4.0, 255.255.255.192")

#adding relays
$iisObject = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/smtpsvc/1")
$relays = $iisObject.Properties["RelayIpList"].Value
$bindingFlags = [Reflection.BindingFlags] "Public, Instance, GetProperty"
$ipList = $relays.GetType().InvokeMember("IPGrant", $bindingFlags, $null, $relays, $null);

#if relay list is empty we are retrieving host subnets and adding to relay
$Networkip =@()
if($IpRelayList.Count -eq 0)
{
    $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName localhost | ? {$_.IPEnabled}
    foreach($Network in $Networks)
    {
        $line = Get-NetworkAddress $Network.IpAddress[0] $Network.IpSubnet[0]
        $line = $line + ", " + $Network.IpSubnet[0]
        $Networkip += $line
    }
}

$ipList = $Networkip + $IpRelayList

# This is important, we need to pass an object array of one element containing our ipList array
[Object[]] $ipArray = @()
$ipArray += , $ipList

# Now update
$bindingFlags = [Reflection.BindingFlags] "Public, Instance, SetProperty"
$ipList = $relays.GetType().InvokeMember("IPGrant", $bindingFlags, $null, $relays, $ipArray);

$iisObject.Properties["RelayIpList"].Value = $relays
$iisObject.CommitChanges()


问:
Append mode requires a document without errors, even if recovery is possible
The PDF which I signed with append mode is exported from Office Word 2016.

Here is my file : word.pdf

And I got this error message:

com.itextpdf.kernel.PdfException: Append mode requires a document without errors, even if recovery is possible.

I am using iText7 7.0.4 .

答:
This actually is a bug in iText 7 creating an incremental update to a hybrid-reference file.

The error situation

Unfortunately the description in the question did not clearly describe a way to reproduce the error. Thus, the error can be reproduced like this:

Stamping the OP's sample document in append mode (it does not need to be a signing use case).

This step does not yet create the error in question.

Stamping the output of step 1 again in append mode (again it does not need to be for signing).

In this step the exception

```<code> com.itextpdf.kernel.PdfException: Append mode requires a document without errors, even if recovery is possible.
</code>```

occurs.

The PDF in question

The OP's PDF is special as it a hybrid-reference file. According to the PDF specification (ISO 32000-1) such a file

is readable by readers designed only to support versions of PDF before PDF 1.5. Such a file contains objects referenced by standard cross-reference tables in addition to objects in object streams that are referenced by cross-reference streams.

In case of these files the startxref offset points to the start of the pre-1.5 cross reference table and the trailer XRefStm entry points to the 1.5 cross reference stream.

The PDF specification furthermore dictates that

the XRefStm entry shall not be used in the trailer dictionary of the main cross-reference section but only in an update cross-reference section.

Therefore the funny looking construction in the file:

```<code>18 0 obj
<</Type/ObjStm/N 10/First 67/Filter/FlateDecode/Length 357>>
stream
[...object stream data...]
endstream
endobj
[...]
25 0 obj
<</Type/XRef/Size 25/W[ 1 4 2] /Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Filter/FlateDecode/Length 97>>
stream
[...cross reference stream data...]
endstream
endobj
xref
0 26
[...cross reference table with 25 entries, objects in object stream are marked free...]
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] >>
startxref
[points to the preceding cross reference table]
48341
%%EOF
xref
0 0
[...empty incremental update cross reference table...]
trailer
[XRefStm points to the cross reference stream in object 25]
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Prev 48341/XRefStm 48045>>
startxref
[points to the empty incremental update cross reference table]
49017
%%EOF
</code>```

Thus, while funny looking, this construction is correct.

What goes wrong

When reading the original document iText 7 recognizes that the document contains both a cross reference table and cross reference stream and chooses the cross reference stream. (Actually PdfReader.readXrefSection first reads the empty cross reference table, then finds the XRefStm entry in the trailer, and then reads the cross reference stream.)

When creating the incremental update, iText 7 remembers that the source PDF has been parsed via a cross reference stream and, therefore, uses full compression, i.e. in particular it uses an object stream and a cross reference stream.

When creating that cross reference stream, though, it sets its Prev entry to what the final startxref of the original PDF pointed to, i.e. the empty cross reference table, and not the cross reference stream it actually used.

Such mixed constructs (a cross reference stream pointing to a cross reference table as Prev) are not allowed, though.

Thus, iText in step one created an invalid cross references structure in its result document and, therefore, in step two found a broken PDF to process and complained.

Body:
This actually is a bug in iText 7 creating an incremental update to a hybrid-reference file.

The error situation

Unfortunately the description in the question did not clearly describe a way to reproduce the error. Thus, the error can be reproduced like this:

Stamping the OP's sample document in append mode (it does not need to be a signing use case).

This step does not yet create the error in question.

Stamping the output of step 1 again in append mode (again it does not need to be for signing).

In this step the exception

 com.itextpdf.kernel.PdfException: Append mode requires a document without errors, even if recovery is possible.

occurs.

The PDF in question

The OP's PDF is special as it a hybrid-reference file. According to the PDF specification (ISO 32000-1) such a file

is readable by readers designed only to support versions of PDF before PDF 1.5. Such a file contains objects referenced by standard cross-reference tables in addition to objects in object streams that are referenced by cross-reference streams.

In case of these files the startxref offset points to the start of the pre-1.5 cross reference table and the trailer XRefStm entry points to the 1.5 cross reference stream.

The PDF specification furthermore dictates that

the XRefStm entry shall not be used in the trailer dictionary of the main cross-reference section but only in an update cross-reference section.

Therefore the funny looking construction in the file:

18 0 obj
<</Type/ObjStm/N 10/First 67/Filter/FlateDecode/Length 357>>
stream
[...object stream data...]
endstream
endobj
[...]
25 0 obj
<</Type/XRef/Size 25/W[ 1 4 2] /Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Filter/FlateDecode/Length 97>>
stream
[...cross reference stream data...]
endstream
endobj
xref
0 26
[...cross reference table with 25 entries, objects in object stream are marked free...]
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] >>
startxref
[points to the preceding cross reference table]
48341
%%EOF
xref
0 0
[...empty incremental update cross reference table...]
trailer
[XRefStm points to the cross reference stream in object 25]
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Prev 48341/XRefStm 48045>>
startxref
[points to the empty incremental update cross reference table]
49017
%%EOF

Thus, while funny looking, this construction is correct.

What goes wrong

When reading the original document iText 7 recognizes that the document contains both a cross reference table and cross reference stream and chooses the cross reference stream. (Actually PdfReader.readXrefSection first reads the empty cross reference table, then finds the XRefStm entry in the trailer, and then reads the cross reference stream.)

When creating the incremental update, iText 7 remembers that the source PDF has been parsed via a cross reference stream and, therefore, uses full compression, i.e. in particular it uses an object stream and a cross reference stream.

When creating that cross reference stream, though, it sets its Prev entry to what the final startxref of the original PDF pointed to, i.e. the empty cross reference table, and not the cross reference stream it actually used.

Such mixed constructs (a cross reference stream pointing to a cross reference table as Prev) are not allowed, though.

Thus, iText in step one created an invalid cross references structure in its result document and, therefore, in step two found a broken PDF to process and complained.


问:
How to pass an object to dynamic code in C#
im using System.CodeDom.Compiler to generate a dynamic code , i need to pass some objects to the functions in code , but when i pass objects they refer to my current name space ...

```<code>string code = @"
            using System;
            using " + type + @";
            namespace First
            {
                public class Program
                {
                    static " + type + ".Class1 " + type.ToLower() + " = (" + type + ".Class1)"+o + @";
                    public static bool check () {
                        if( " + exp
                        +
                        @")
                            return true;
                        else
                            return false;
                    }
                    public static void Main()
                    {
                    " +
                       "    Console.WriteLine(\"Hello, world!\");"
                      + @"
                    }
                }
            }
        ";
</code>```

and i get this error : The name 'MineRuleEngine'(my current name space) does not exist in the current context

答:
my problem is that object "o" is refer to MineRuleEngine.person for example . and my dynamic code doesn't know "MineRuleEngine" namespace

The reason your code doesn't know about this object is because you have to explictly take care of using "external" resources (i.e. classes)

You have to specify using MyNamespace; in code and you have to add a reference to an assembly containing the namespace.

For example:

```<code> CSharpCodeProvider provider = new CSharpCodeProvider();
 CompilerParameters param = new CompilerParameters(new string[] { "System.dll", "Scripting.dll" });
</code>```

Also take a look at this question Referencing current assembly with CompilerParameters

Body:
im using System.CodeDom.Compiler to generate a dynamic code , i need to pass some objects to the functions in code , but when i pass objects they refer to my current name space ...

string code = @"
            using System;
            using " + type + @";
            namespace First
            {
                public class Program
                {
                    static " + type + ".Class1 " + type.ToLower() + " = (" + type + ".Class1)"+o + @";
                    public static bool check () {
                        if( " + exp
                        +
                        @")
                            return true;
                        else
                            return false;
                    }
                    public static void Main()
                    {
                    " +
                       "    Console.WriteLine(\"Hello, world!\");"
                      + @"
                    }
                }
            }
        ";

and i get this error : The name 'MineRuleEngine'(my current name space) does not exist in the current context

Body:
my problem is that object "o" is refer to MineRuleEngine.person for example . and my dynamic code doesn't know "MineRuleEngine" namespace

The reason your code doesn't know about this object is because you have to explictly take care of using "external" resources (i.e. classes)

You have to specify using MyNamespace; in code and you have to add a reference to an assembly containing the namespace.

For example:

 CSharpCodeProvider provider = new CSharpCodeProvider();
 CompilerParameters param = new CompilerParameters(new string[] { "System.dll", "Scripting.dll" });

Also take a look at this question Referencing current assembly with CompilerParameters


问:
Android NDK: Application targets deprecated ABI(s): armeabi error after update NDK
Yesterday, after updating NDK I'm having these errors:

```<code>Error:(81) Android NDK: Application targets deprecated ABI(s): armeabi
Error:(82) Android NDK: Support for these ABIs will be removed in a
future NDK release.
</code>```

This links directed me to setup-app.mk file on lines

```<code>_deprecated_abis := $(filter $(NDK_DEPRECATED_ABIS),$(NDK_APP_ABI))
ifneq ($(_deprecated_abis),)
  $(call __ndk_warning,Application targets deprecated ABI(s):
  $(_deprecated_abis))
  $(call __ndk_warning,Support for these ABIs will be removed in a
  future NDK release.)
endif
</code>```

I have no idea, how to solve this problem.
Any advice?

答:
Remove armeabi from your APP_ABI list.

As you can see from the source though, it should be a warning, not an error. How are you invoking ndk-build?

Body:
Yesterday, after updating NDK I'm having these errors:

Error:(81) Android NDK: Application targets deprecated ABI(s): armeabi
Error:(82) Android NDK: Support for these ABIs will be removed in a
future NDK release.

This links directed me to setup-app.mk file on lines

_deprecated_abis := $(filter $(NDK_DEPRECATED_ABIS),$(NDK_APP_ABI))
ifneq ($(_deprecated_abis),)
  $(call __ndk_warning,Application targets deprecated ABI(s):
  $(_deprecated_abis))
  $(call __ndk_warning,Support for these ABIs will be removed in a
  future NDK release.)
endif

I have no idea, how to solve this problem.
Any advice?


问:
How to implement hyperparameter search in Tensorflow?
I would like to implement a hyperparameter search in Tensorflow, like the one presented in this video. Unfortunately I was not able to find any tutorials about it.

I've found some code which uses it, but I was not able to understand it properly. Implementing the bayesian optimization would be the best, but I would like to try the grid or random search first.

Should I create the different graphs before? How is it possible to do the training on multiple graphs, and how to compare them?

答:
In the video some code is provided here which allows you to recreate their results.

The code runs the models and the plots are generated by tensorboard with the command tensorboard --logdir <log location>. In this case: tensorboard --logdir /tmp/mnist_tutorial.

The excerpt from the video is as follows:

# Try a few learning rates
for learning_rate in [1E-3, 1E-4, 1E-5]:

    for use_two_fc in [True, False]
        for use_two_conv in [True, False]:

            # Construct a hyperparameter string for each one (example: "lr_1E,fc=2,conv=2)
            hparam_str = make_hparam_string(learning_rate, use_two_fc, use_two_conv)

            writer = tf.summaru/FileWriter("/tmp/mnist_tutorial/" + hparam_str)

            # Actually run with the new settings
            mnist(learning_rate, use_two_fully_connected_layers, _use_two_conv_layers, writer)
```

Check out the github repo for more a detailed explanation of how to set up tensorboard.

Body:
In the video some code is provided here which allows you to recreate their results.

The code runs the models and the plots are generated by tensorboard with the command tensorboard --logdir <log location>. In this case: tensorboard --logdir /tmp/mnist_tutorial.

The excerpt from the video is as follows:

# Try a few learning rates
for learning_rate in [1E-3, 1E-4, 1E-5]:

    for use_two_fc in [True, False]
        for use_two_conv in [True, False]:

            # Construct a hyperparameter string for each one (example: "lr_1E,fc=2,conv=2)
            hparam_str = make_hparam_string(learning_rate, use_two_fc, use_two_conv)

            writer = tf.summaru/FileWriter("/tmp/mnist_tutorial/" + hparam_str)

            # Actually run with the new settings
            mnist(learning_rate, use_two_fully_connected_layers, _use_two_conv_layers, writer)

Check out the github repo for more a detailed explanation of how to set up tensorboard.


问:
LibGDX: move and then stop box2d immediately
I'm working on a project in LibGDX.
It's a 2d platform game. you can say it's like Super Mario.

So this is how i move my player to the right:

```<code>if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
    player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
}
</code>```

When i leave the key, the player is still moving a bit. (it's still have "Linear Impulse" force on his physical body i think).

How can i make it stop?

My question could be simple as:
What is the best way to move a physical body on LibGDX in one direction while holding a key. and when i leave the key, the player stops immediately.

bdw -  I have tryied with "setTransform" and it's making issues when the body is touching other objects - plus the sahpe come "before" the rest of the game in the screen (you can see it on debug)

Thanks.

答:
Your method is OK. I would also recommend to set the max speed of your body:

```<code>if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x < maxSpeed)
    player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
}
</code>```

Stop your body immediately by using the setLinearVelocity method.:

```<code>player.b2body.setLinearVelocity(0f, 0f);
</code>```

Body:
I'm working on a project in LibGDX.
It's a 2d platform game. you can say it's like Super Mario.

So this is how i move my player to the right:

if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
    player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
}

When i leave the key, the player is still moving a bit. (it's still have "Linear Impulse" force on his physical body i think).

How can i make it stop?

My question could be simple as:
What is the best way to move a physical body on LibGDX in one direction while holding a key. and when i leave the key, the player stops immediately.

bdw -  I have tryied with "setTransform" and it's making issues when the body is touching other objects - plus the sahpe come "before" the rest of the game in the screen (you can see it on debug)

Thanks.

Body:
Your method is OK. I would also recommend to set the max speed of your body:

if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x < maxSpeed)
    player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
}

Stop your body immediately by using the setLinearVelocity method.:

player.b2body.setLinearVelocity(0f, 0f);


问:
Multiple index properties on a type?
Is it possible to have something like this in C#? I am not very sure:

```<code>class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}
</code>```

So it could be used as such:

```<code>myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...
</code>```

So my complete member methods that I need to implement in my framework (by calling them) are:

```<code>GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)
</code>```

I want to implement them cleaner in my own type.

答:
In C#, indexers have to be called this (see http://msdn.microsoft.com/en-us/library/aa664459(v=VS.71).aspx).  You can overload indexers, but remember that C# doesn't allow overloading based on return type only.  So, whereas you can have:

```<code>public int this[int i]
public string this[string s]
</code>```

You couldn't have:

```<code>public int this[int i]
public string this[int i]
</code>```

The .NET class library design guidelines recommend having only one indexer per class.

So in your case, there's no way to do what you're asking using indexers only.

Title: Multiple index properties on a type?

Body:
Is it possible to have something like this in C#? I am not very sure:

class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}

So it could be used as such:

myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...

So my complete member methods that I need to implement in my framework (by calling them) are:

GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)

I want to implement them cleaner in my own type.

Body:
In C#, indexers have to be called this (see http://msdn.microsoft.com/en-us/library/aa664459(v=VS.71).aspx).  You can overload indexers, but remember that C# doesn't allow overloading based on return type only.  So, whereas you can have:

public int this[int i]
public string this[string s]

You couldn't have:

public int this[int i]
public string this[int i]

The .NET class library design guidelines recommend having only one indexer per class.

So in your case, there's no way to do what you're asking using indexers only.


问:
Microsoft SQL Server, increasing price by percentage, rounded up
let's say I have a table called products_tbl, and a price column called price. I need a script to update the prices by 3% rounded up, so if the result of a cell is 41.3, it has to become 42.
Is it possible?</p>

答:
This is what I understood, I'm surprised the question got interpreted this many ways:</p>

```<code>BEGIN TRAN

UPDATE products_tbl
SET price = CEILING(price * 1.03)

SELECT *
FROM products_tbl

ROLLBACK TRAN -- Because we only answer w/ commits for a fee.
</code>```

Body:
This is what I understood, I'm surprised the question got interpreted this many ways:

BEGIN TRAN

UPDATE products_tbl
SET price = CEILING(price * 1.03)

SELECT *
FROM products_tbl

ROLLBACK TRAN -- Because we only answer w/ commits for a fee.


问:
Ecto.Query joins generates far too many INNER JOIN
Not sure why Ecto is returning the incorrect result.
I might be messing things up with joins

This is my Ecto.Query

```<code>from u in User,
        join: c in assoc(u, :companies),
        join: r in assoc(c, :roles),
        join: a in assoc(r, :assets),
        where: u.id == ^2 and a.id == ^1,
        group_by: [c.id, u.id, r.id],
        select: {u.email, u.id, r.name, c.name}
</code>```

It generates:

```<code>    SELECT u0."email", u0."id", r2."name", c1."name"
FROM "users" AS u0
INNER JOIN "access_lists" AS a4 ON a4."user_id" = u0."id"
INNER JOIN "companies" AS c1 ON a4."company_id" = c1."id"
INNER JOIN "access_lists" AS a5 ON a5."company_id" = c1."id"
INNER JOIN "roles" AS r2 ON a5."role_id" = r2."id"
INNER JOIN "access_lists" AS a6 ON a6."role_id" = r2."id"
INNER JOIN "assets" AS a3 ON a6."asset_id" = a3."id"
 WHERE ((u0."id" = $1) AND (a3."id" = $2))
GROUP BY c1."id", u0."id", r2."id" [2, 1]
</code>```

The result of this query is incorrect

this is the correct query:

```<code>SELECT u0.email, u0.id, r2.name, c1.name, a6.asset_name , a6.id as asset_id
FROM users AS u0
INNER JOIN access_lists AS a4 ON a4.user_id = u0.id
INNER JOIN assets AS a6 ON a4.asset_id = a6.id
INNER JOIN companies AS c1 ON a4.company_id = c1.id
INNER JOIN roles AS r2 ON a4.role_id = r2.id
WHERE ((u0.id = 2) AND (a6.id = 1))
Group By u0.id, r2.id, c1.id, a6.id
</code>```

Here is the schemas:

AccessList:

```<code>  schema "access_lists" do
        belongs_to :user, Db.User
        belongs_to :role, Db.Role
        belongs_to :asset, Db.Asset
        belongs_to :project, Db.Project
        belongs_to :company, Db.Company

        timestamps()
    end
</code>```

User:

```<code>many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :assets, Db.Asset, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList
</code>```

Asset:

```<code>many_to_many :users, Db.User, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList
many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList
</code>```

Company:

```<code>    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :roles, Db.Role, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList
</code>```

Role:

```<code>    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList
    many_to_many :companies, Db.Company, join_through: Db.AccessList
</code>```

Here is a diagram:

答:
I have used

```<code>from u in User,
        join: acl in AccessList, on: acl.user_id == u.id,
        join: c in Company, on: acl.company_id == c.id,
        join: r in Role, on: acl.role_id == r.id,
        join: a in Asset, on: acl.asset_id == a.id,
        where: u.id == ^2 and a.id == ^1,
        group_by: [c.id, u.id, r.id],
        select: {u.email, u.id, r.name, c.name}
</code>```

This works and I get the correct result however I am not sure why.

And why do I have to define every join and

why can't I use join assoc instead

Body:
Not sure why Ecto is returning the incorrect result.
I might be messing things up with joins

This is my Ecto.Query

from u in User,
        join: c in assoc(u, :companies),
        join: r in assoc(c, :roles),
        join: a in assoc(r, :assets),
        where: u.id == ^2 and a.id == ^1,
        group_by: [c.id, u.id, r.id],
        select: {u.email, u.id, r.name, c.name}

It generates:

    SELECT u0."email", u0."id", r2."name", c1."name"
FROM "users" AS u0
INNER JOIN "access_lists" AS a4 ON a4."user_id" = u0."id"
INNER JOIN "companies" AS c1 ON a4."company_id" = c1."id"
INNER JOIN "access_lists" AS a5 ON a5."company_id" = c1."id"
INNER JOIN "roles" AS r2 ON a5."role_id" = r2."id"
INNER JOIN "access_lists" AS a6 ON a6."role_id" = r2."id"
INNER JOIN "assets" AS a3 ON a6."asset_id" = a3."id"
 WHERE ((u0."id" = $1) AND (a3."id" = $2))
GROUP BY c1."id", u0."id", r2."id" [2, 1]

The result of this query is incorrect

this is the correct query:

SELECT u0.email, u0.id, r2.name, c1.name, a6.asset_name , a6.id as asset_id
FROM users AS u0
INNER JOIN access_lists AS a4 ON a4.user_id = u0.id
INNER JOIN assets AS a6 ON a4.asset_id = a6.id
INNER JOIN companies AS c1 ON a4.company_id = c1.id
INNER JOIN roles AS r2 ON a4.role_id = r2.id
WHERE ((u0.id = 2) AND (a6.id = 1))
Group By u0.id, r2.id, c1.id, a6.id

Here is the schemas:

AccessList:

  schema "access_lists" do
        belongs_to :user, Db.User
        belongs_to :role, Db.Role
        belongs_to :asset, Db.Asset
        belongs_to :project, Db.Project
        belongs_to :company, Db.Company

        timestamps()
    end

User:

many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :assets, Db.Asset, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList

Asset:

many_to_many :users, Db.User, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList
many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList

Company:

    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :roles, Db.Role, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList

Role:

    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList
    many_to_many :companies, Db.Company, join_through: Db.AccessList

Here is a diagram:

Body:
I have used

from u in User,
        join: acl in AccessList, on: acl.user_id == u.id,
        join: c in Company, on: acl.company_id == c.id,
        join: r in Role, on: acl.role_id == r.id,
        join: a in Asset, on: acl.asset_id == a.id,
        where: u.id == ^2 and a.id == ^1,
        group_by: [c.id, u.id, r.id],
        select: {u.email, u.id, r.name, c.name}

This works and I get the correct result however I am not sure why.

And why do I have to define every join and

why can't I use join assoc instead