问:
Spring MVC Rest - How can I know if a user loses their connection while waiting on response?
I have a Spring 4 MVC application that is serving a rest API. I am trying to debug an issue where it appears that users are losing their connection, but I'm not sure how to capture this information at the application level. </p>

<p>Is there a logging level or something I can turn on? In the logs, it looks like the request just stops processing, but I don't see any error. </p>

答:
What you can not check is the download-speed because its hardware-buffer is block-based. You may be able to set the block-size to 1byte, so the time-effort is multipicated in small bandwidths. This might give a exception if the socket is closed.

To provoce some exceptions you could decrease the socket timeout (the time waiting for a byte to be read). This is a configuration issue, you should check the web-container's documentation (connectionTimeout in tomcat).

Not every OS is supporting this SO_TIMEOUT, but the common OS's should be able to configure it.

Anyway, it is a task for the web-container (like tomcat) and therefore its detached from the application (for a good reason from my point of view).

You may check the chrome-browser devtools let you emulate slow bandwidths.

Body:
I have a Spring 4 MVC application that is serving a rest API. I am trying to debug an issue where it appears that users are losing their connection, but I'm not sure how to capture this information at the application level.

Is there a logging level or something I can turn on? In the logs, it looks like the request just stops processing, but I don't see any error.


来源: stackexchange

问:
Update-AzureRmVmss : Long running operation failed with status 'Failed'. ErrorCode: VMExtensionProvisioningError
I am trying to change the password of VMSS (Service Fabric Cluster nodes) via Powershell.
The Process of the chnage password of VMSS come with the following error.
After error come the password changed but VMSS state showing failed,

```<code>Update-AzureRmVmss : Long running operation failed with status 'Failed'.
ErrorCode: VMExtensionProvisioningError
ErrorMessage: VM has reported a failure when processing extension 'ServiceProfilerAgent'. Error message: "Failed to launch diagnostic agent. The agent output: $Unpacking resources...
Executing Service Profiler Agent version 1.0.41004.1 with arguments: --mode AzureVMExtension --vmextsettings 1.settings
Welcome to Service Profiler - to exit the program press 'Ctrl+C'.
Initializing agent...
Loading settings from cloud storage. Settings name: default
The settings file 'default-settings.json' was not found in storage.
Account name: appperformance
Container name: sp-agent-settings
Blob name: default-settings.json
There was a problem loading the settings. Failed to load settings from cloud storage.
".
StartTime: 6/4/2017 10:58:11 AM
EndTime: 6/4/2017 10:58:16 AM
OperationID: a0bfeb48-2da0-4dea-8e73-9137d11b0351
Status: Failed
At line:1 char:1
+ Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -Virtua ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Update-AzureRmVmss], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Common.ComputeCloudException,Microsoft.Azure.Commands.Compute.Automation.UpdateAzureRmVmss
</code>```

I have successfully changed the password of VMSS scale set but this error comes.
My VMSS state showing fails but still my service fabric Cluster running.

Here are the commands i have used to changed the password of VMSS.

```<code>Login-AzureRmAccount
$vmssName = "node"
$vmssResourceGroup = "RG"
publicConfig = @{"UserName" = "username"}
$privateConfig = @{"Password" = "Password"}
$extName = "VMAccessAgent"
$publisher = "Microsoft.Compute"
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
$vmss = Add-AzureRmVmssExtension -VirtualMachineScaleSet $vmss -Name $extName -Publisher $publisher -Setting $publicConfig -ProtectedSetting $privateConfig -Type $extName -TypeHandlerVersion "2.0" -AutoUpgradeMinorVersion $true
Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -VirtualMachineScaleSet $vmss
</code>```

答:
It seems the profiler agent cannot connect to the storage account to download the settings file.

Can you check if the storage account still exists or the storage connection has changed?

If anything has changed, you can update the storage account in https://www.azureserviceprofiler.com/  and re-run the deployment script with the updated storage account.

If you decide to stop the profiling, you can also remove the Microsoft.VisualStudio.ServiceProfiler/ ServiceProfilerAgent extension.

Hope this helps! :)

ContentLicense: CC BY-SA 3.0

Body:
I am trying to change the password of VMSS (Service Fabric Cluster nodes) via Powershell.
The Process of the chnage password of VMSS come with the following error.
After error come the password changed but VMSS state showing failed,

Update-AzureRmVmss : Long running operation failed with status 'Failed'.
ErrorCode: VMExtensionProvisioningError
ErrorMessage: VM has reported a failure when processing extension 'ServiceProfilerAgent'. Error message: "Failed to launch diagnostic agent. The agent output: $Unpacking resources...
Executing Service Profiler Agent version 1.0.41004.1 with arguments: --mode AzureVMExtension --vmextsettings 1.settings
Welcome to Service Profiler - to exit the program press 'Ctrl+C'.
Initializing agent...
Loading settings from cloud storage. Settings name: default
The settings file 'default-settings.json' was not found in storage.
Account name: appperformance
Container name: sp-agent-settings
Blob name: default-settings.json
There was a problem loading the settings. Failed to load settings from cloud storage.
".
StartTime: 6/4/2017 10:58:11 AM
EndTime: 6/4/2017 10:58:16 AM
OperationID: a0bfeb48-2da0-4dea-8e73-9137d11b0351
Status: Failed
At line:1 char:1
+ Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -Virtua ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Update-AzureRmVmss], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Common.ComputeCloudException,Microsoft.Azure.Commands.Compute.Automation.UpdateAzureRmVmss

I have successfully changed the password of VMSS scale set but this error comes.
My VMSS state showing fails but still my service fabric Cluster running.

Here are the commands i have used to changed the password of VMSS.

Login-AzureRmAccount
$vmssName = "node"
$vmssResourceGroup = "RG"
publicConfig = @{"UserName" = "username"}
$privateConfig = @{"Password" = "Password"}
$extName = "VMAccessAgent"
$publisher = "Microsoft.Compute"
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
$vmss = Add-AzureRmVmssExtension -VirtualMachineScaleSet $vmss -Name $extName -Publisher $publisher -Setting $publicConfig -ProtectedSetting $privateConfig -Type $extName -TypeHandlerVersion "2.0" -AutoUpgradeMinorVersion $true
Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -VirtualMachineScaleSet $vmss


问:
Azure SQL Database "DTU percentage" metric
With the new Azure SQL Database tier structure, it seems important to monitor your database "DTU" usage to know whether to upgrade or downgrade to another tier.

When reading Azure SQL Database Service Tiers and Performance Levels, it only talks about monitoring with CPU, Data and Log percentage usage.

But, when I add new metrics, I also have an DTU percentage option:

I can't find any about this online.  Is this essentially a summary of the other DTU-related metrics?

答:
From this document, this DTU percent is determined by this query:

```<code>SELECT end_time,
  (SELECT Max(v)
   FROM (VALUES (avg_cpu_percent), (avg_data_io_percent),
(avg_log_write_percent)) AS
   value(v)) AS [avg_DTU_percent]
FROM sys.dm_db_resource_stats;
</code>```

looks like the max of avg_cpu_percent, avg_data_io_percent and avg_log_write_percent

Reference:

https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-resource-stats-azure-sql-database

ContentLicense: CC BY-SA 4.0

Body:
From this document, this DTU percent is determined by this query:

SELECT end_time,
  (SELECT Max(v)
   FROM (VALUES (avg_cpu_percent), (avg_data_io_percent),
(avg_log_write_percent)) AS
   value(v)) AS [avg_DTU_percent]
FROM sys.dm_db_resource_stats;

looks like the max of avg_cpu_percent, avg_data_io_percent and avg_log_write_percent

Reference:

https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-resource-stats-azure-sql-database


问:
Intellij Re-import Gradle Project
I just added a new test source directory to my Gradle project and want IntelliJ to recognize it. I can close the project and reopen the build.gradle file and chose "Delete Existing Project and Import"; is there a way to update the module sources without deleting the existing project?

```<code>idea {
    module {
        // just added these two lines
        testSourceDirs += file('src/integration-test/java')
        testSourceDirs += file('src/integration-test/resources')
    }
}
</code>```

I don't want to just manually add the sources, instead I want IntelliJ to re-import the Gradle project structure from the 'build.gradle' file.

Details: Gradle v1.7, IntelliJ v12

答:
I'm using intellij 2017 and was unable to locate the "refresh" option as described in previous versions of intellij.  For me,

./gradlew idea corrected the issue.  gradle idea should also work.

UPDATE

As noted in the comments, when using intellij 2017 open the build.gradle file as a project and enable the "auto import" command to avoid this issue all together!

Title: Intellij Re-import Gradle Project

Body:
I just added a new test source directory to my Gradle project and want IntelliJ to recognize it. I can close the project and reopen the build.gradle file and chose "Delete Existing Project and Import"; is there a way to update the module sources without deleting the existing project?

idea {
    module {
        // just added these two lines
        testSourceDirs += file('src/integration-test/java')
        testSourceDirs += file('src/integration-test/resources')
    }
}

I don't want to just manually add the sources, instead I want IntelliJ to re-import the Gradle project structure from the 'build.gradle' file.

Details: Gradle v1.7, IntelliJ v12


问:
Best practices for using Django ORM in threaded application
I'm working on a multi-threaded application that uses the Django ORM with MySQL. The idea is to use a single startup script to launch multiple modules ("module" here in the functional sense, not the literal Python sense), each of which has a "service loop" that runs in its own thread. I've organized it using a single class for each module.

I originally did this using a sqlite DB and it worked great. Now I'm transitioning to MySQL and am running into DB connection problems related to threading. For example, it looks like I need to call db.connections.close_all() within each thread to avoid contention with the DB connection? I'm thinking that I need to move all setup related to the Django ORM to the service thread but then I wouldn't be able to import models in the class's init() method.

Anyway, I'm sure that other people have dealt with this before, and I'm sure there are some good patterns out there. Anyone have any suggestions or best practices they could share?

This is my simple startup script:

```<code>from controller.modules.manager import Manager
from controller.modules.scanner import Scanner

print("Starting...")

# The directory scanner
scanner = Scanner()

# The job manager
manager = Manager()
</code>```

And here's an example of one of the modules (the Scanner class):

```<code>import os
from multiprocessing import Process
from time import sleep
import threading
import django

# Need to do this before importing models
from common.utilities.os import OS
os.environ["DJANGO_SETTINGS_MODULE"] = "common.settings"
django.setup()

# Import models here

class Scanner:
    def __init__(self):
        # Define some member variables here, some of which include
        # DB models

        # Launch service loop
        Process(target=self.service_loop, name='service loop').start()

    def service_loop(self):
        while True:
            # Scan some directories and update some DB entries

            # Throttle the loop
            sleep(config.THROTTLE_SLEEP_TIME_SEC)
</code>```

答: SOLVED. After countless hours of experimenting and googling I finally found exactly what I was looking for here. I inherited the module classes from python's threading.Thread class and it solved all issues.</p>

Body:
I'm working on a multi-threaded application that uses the Django ORM with MySQL. The idea is to use a single startup script to launch multiple modules ("module" here in the functional sense, not the literal Python sense), each of which has a "service loop" that runs in its own thread. I've organized it using a single class for each module.

I originally did this using a sqlite DB and it worked great. Now I'm transitioning to MySQL and am running into DB connection problems related to threading. For example, it looks like I need to call db.connections.close_all() within each thread to avoid contention with the DB connection? I'm thinking that I need to move all setup related to the Django ORM to the service thread but then I wouldn't be able to import models in the class's init() method.

Anyway, I'm sure that other people have dealt with this before, and I'm sure there are some good patterns out there. Anyone have any suggestions or best practices they could share?

This is my simple startup script:

from controller.modules.manager import Manager
from controller.modules.scanner import Scanner

print("Starting...")

# The directory scanner
scanner = Scanner()

# The job manager
manager = Manager()

And here's an example of one of the modules (the Scanner class):

import os
from multiprocessing import Process
from time import sleep
import threading
import django

# Need to do this before importing models
from common.utilities.os import OS
os.environ["DJANGO_SETTINGS_MODULE"] = "common.settings"
django.setup()

# Import models here

class Scanner:
    def __init__(self):
        # Define some member variables here, some of which include
        # DB models

        # Launch service loop
        Process(target=self.service_loop, name='service loop').start()

    def service_loop(self):
        while True:
            # Scan some directories and update some DB entries

            # Throttle the loop
            sleep(config.THROTTLE_SLEEP_TIME_SEC)


问:
Monitor Outbound Webservice calls
I'm currently debugging a 3rd party component and I need to monitor to see if it is making an outbound webservice call. Does anyone know of a way of quickly setting up something to monitor this as I step over the code. </p>

答: Try fiddler, easier to use than wireshark if this is new to you.</p>

ContentLicense: CC BY-SA 2.5

Title: Monitor Outbound Webservice calls


问:
Is it good practice having separate database for different pages in a website?
I have a website xyz.com that is going to be launched in an online server. I have three pages x, y and z (suppose x is for image gallery, y is for video gallery, and z is for another gallery). I need to have a comment section for each of the pages, and user input is going to be stored in database. There need not be any relation between the comments in different pages, or in another words, comment from one page doesn't have to relate with the comments in another pages. I want to deal them separately.

Now my question is:

Should I use one database and create just three different tables for each pages or should I create three completely different database each of them having one table? Which one is good practice?

答: Use one database with as many tables as you need, there's no reason to create several databases for your project</p>


问:
Downloading saved model from Google Cloud Datalab notebook
I'm new to Google Cloud Platform. I have written my code in Cloud Datalab , and saved a model in the datalabs notebook after training it with data. I want to download the saved model in my local machine and use it for further prediction. I saved the model in local machine and tried to run predictions with it. But I got an error saying " NotFittedError: Couldn't find trained model at  ". Can anyone tell me how to get around the problem? </p>

答:
Can you let me know how do you do prediction? Through gcloud? Also, how do you save the model? Do you call TensorFlow's tf.python.saved_model library to save it?

With gcloud, you specify model by its directory. The directory should include a "saved_model.pb" file and a few other directories. You can inspect the model dir to see if "saved_model.pb" is there.


问:
Drawing latitude, longitude of array elements on canvas
I'm trying to draw rects on a canvas for each element in my array. For the positioning I use the longitude and latitude values of the elements.

My array looks something like this and contains 50.000 elements that are objects:

```<code>var modified_array =
[{"city":"NYC","longitude":-73.935242,"latitude":40.730610},
 {"city":"NYC","longitude":-74.044502,"latitude":40.689247}]
</code>```

EDIT: The solution from @le_m helped me out a lot and I implemented a filter like he suggested:

```<code>const test2 = test.filter(({latitude, longitude}) => latitude != null
              && longitude != null);

function getBoundingRect(test2) {
    let left = Infinity, right  = -Infinity;
    let top  = Infinity, bottom = -Infinity;

    for (let {latitude, longitude} of test2) {
        if (left   > latitude ) left   = latitude;
        if (top    > longitude) top    = longitude;
        if (right  < latitude) right  = latitude;
        if (bottom < longitude) bottom = longitude;
    }
    return {x: left, y: top, width: right - left, height: bottom -
    top};
}

function draw(ctx, test2) {
    let boundingRect = getBoundingRect(test2);
    let scale = Math.min(canvas.width, canvas.height);

    for (let {latitude, longitude} of test2) {
        let x = (latitude  - boundingRect.x) / boundingRect.width  *
        scale;
        let y = (longitude - boundingRect.y) / boundingRect.height *
        scale;
        ctx.fillStyle = "rgba(65,105,225,0.2)";
        ctx.fillRect(x - 5, y - 5, 4, 4);
    }
}

draw(ctx, test2);
</code>```

The filter doesn't seem to work What am I doing wrong?

答:
I suggest computing the bounding box or bounding rectangle of all data points and stretch that bounding rectangle to fill your whole canvas:

function getBoundingRect(data) {
  let left = Infinity, right  = -Infinity;
  let top  = Infinity, bottom = -Infinity;

  for (let {latitude, longitude} of data) {
    if (left   > latitude ) left   = latitude;
    if (top    > longitude) top    = longitude;
    if (right  < latitude ) right  = latitude;
    if (bottom < longitude) bottom = longitude;
  }
  return {x: left, y: top, width: right - left, height: bottom - top};
}

function draw(ctx, data) {
  let boundingRect = getBoundingRect(data);
  let scale = Math.min(canvas.width, canvas.height);

  for (let {latitude, longitude} of data) {
    let x = (latitude  - boundingRect.x) / boundingRect.width  * scale;
    let y = (longitude - boundingRect.y) / boundingRect.height * scale;
    ctx.fillRect(x - 5, y - 5, 10, 10);
  }
}

let data = [
  {"city": "NYC", "longitude": -73.935242, "latitude": 40.730610},
  {"city": "NYC", "longitude": -74.044502, "latitude": 40.689247},
  {"city": "NYC", "longitude": -74.020219, "latitude": 40.578912},
  {"city": "NYC", "longitude": -73.992833, "latitude": 40.634345},
  {"city": "NYC", "longitude": -74.120332, "latitude": 40.484633}
];

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

draw(ctx, data);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="200px" height="200px"></canvas></code>```

The getBoundingRect(data) function computes the bounding rectangle - i.e. the smallest rectangle which still contains all given data points.

The bounding rectangle (left, top, right, bottom) is found by iterating over all data points and widening the rectangle whenever a point is discovered to lie outside the current bounding rectangle.

The draw function finally draws all data points on the given canvas context ctx. An offset (the bounding rectangle's left and top position) is subtracted from all data point coordinates. This guarantees that all data point coordinates are positive and greater than 0. Subsequently, the data point coordinates are scaled to stretch the whole canvas while maintaining the aspect ratio.

Body:
I'm trying to draw rects on a canvas for each element in my array. For the positioning I use the longitude and latitude values of the elements.

My array looks something like this and contains 50.000 elements that are objects:

var modified_array =
[{"city":"NYC","longitude":-73.935242,"latitude":40.730610},
 {"city":"NYC","longitude":-74.044502,"latitude":40.689247}]

EDIT: The solution from @le_m helped me out a lot and I implemented a filter like he suggested:

const test2 = test.filter(({latitude, longitude}) => latitude != null
              && longitude != null);

function getBoundingRect(test2) {
    let left = Infinity, right  = -Infinity;
    let top  = Infinity, bottom = -Infinity;

    for (let {latitude, longitude} of test2) {
        if (left   > latitude ) left   = latitude;
        if (top    > longitude) top    = longitude;
        if (right  < latitude) right  = latitude;
        if (bottom < longitude) bottom = longitude;
    }
    return {x: left, y: top, width: right - left, height: bottom -
    top};
}

function draw(ctx, test2) {
    let boundingRect = getBoundingRect(test2);
    let scale = Math.min(canvas.width, canvas.height);

    for (let {latitude, longitude} of test2) {
        let x = (latitude  - boundingRect.x) / boundingRect.width  *
        scale;
        let y = (longitude - boundingRect.y) / boundingRect.height *
        scale;
        ctx.fillStyle = "rgba(65,105,225,0.2)";
        ctx.fillRect(x - 5, y - 5, 4, 4);
    }
}

draw(ctx, test2);

The filter doesn't seem to work What am I doing wrong?

Body:
I suggest computing the bounding box or bounding rectangle of all data points and stretch that bounding rectangle to fill your whole canvas:

function getBoundingRect(data) {
  let left = Infinity, right  = -Infinity;
  let top  = Infinity, bottom = -Infinity;

  for (let {latitude, longitude} of data) {
    if (left   > latitude ) left   = latitude;
    if (top    > longitude) top    = longitude;
    if (right  < latitude ) right  = latitude;
    if (bottom < longitude) bottom = longitude;
  }
  return {x: left, y: top, width: right - left, height: bottom - top};
}

function draw(ctx, data) {
  let boundingRect = getBoundingRect(data);
  let scale = Math.min(canvas.width, canvas.height);

  for (let {latitude, longitude} of data) {
    let x = (latitude  - boundingRect.x) / boundingRect.width  * scale;
    let y = (longitude - boundingRect.y) / boundingRect.height * scale;
    ctx.fillRect(x - 5, y - 5, 10, 10);
  }
}

let data = [
  {"city": "NYC", "longitude": -73.935242, "latitude": 40.730610},
  {"city": "NYC", "longitude": -74.044502, "latitude": 40.689247},
  {"city": "NYC", "longitude": -74.020219, "latitude": 40.578912},
  {"city": "NYC", "longitude": -73.992833, "latitude": 40.634345},
  {"city": "NYC", "longitude": -74.120332, "latitude": 40.484633}
];

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

draw(ctx, data);

<canvas id="canvas" width="200px" height="200px"></canvas>

The getBoundingRect(data) function computes the bounding rectangle - i.e. the smallest rectangle which still contains all given data points.

The bounding rectangle (left, top, right, bottom) is found by iterating over all data points and widening the rectangle whenever a point is discovered to lie outside the current bounding rectangle.

The draw function finally draws all data points on the given canvas context ctx. An offset (the bounding rectangle's left and top position) is subtracted from all data point coordinates. This guarantees that all data point coordinates are positive and greater than 0. Subsequently, the data point coordinates are scaled to stretch the whole canvas while maintaining the aspect ratio.


问:
Can an Android view have an aspect ratio, fill the parent horizontally and be centered in the parent?
I am trying to embed an image between the rows of a RecyclerView (As another ViewType/ViewHolder). Said image must have a 9:5 aspect ratio, with a max height of 600px so it doesn't grow huge on bigger phones or tablets, and therefore must be centered horizontally if it's size doesn't match the parent width due to aspect ratio resizing.

Is this achievable without custom code? I tried ConstraintLayout and PercentFrameLayout and both seem to ignore the android:maxHeight criteria.

答:
You can do this with ConstraintLayout using guidelines. Set your guidelines 600px apart and constrain the ImageView to the guidelines: top and bottom. These constraints will keep the image from growing beyond 600px. Here is a video of what happens when I move the bottom guideline up and down. Below is the XML for the layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.MainActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guidelineTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="0px" />

    <android.support.constraint.Guideline
        android:id="@+id/guidelineBottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="600px" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="0dp"
        app:layout_constraintBottom_toTopOf="@+id/guidelineBottom"
        app:layout_constraintDimensionRatio="9:5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guidelineTop"
        app:srcCompat="@mipmap/ic_launcher"/>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
You can do this with ConstraintLayout using guidelines. Set your guidelines 600px apart and constrain the ImageView to the guidelines: top and bottom. These constraints will keep the image from growing beyond 600px. Here is a video of what happens when I move the bottom guideline up and down. Below is the XML for the layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.MainActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guidelineTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="0px" />

    <android.support.constraint.Guideline
        android:id="@+id/guidelineBottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="600px" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="0dp"
        app:layout_constraintBottom_toTopOf="@+id/guidelineBottom"
        app:layout_constraintDimensionRatio="9:5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guidelineTop"
        app:srcCompat="@mipmap/ic_launcher"/>

</android.support.constraint.ConstraintLayout>


问:
T.test for each row in R
I am working with two data frames both with 20502 rows, and I want to preform a t.test with the 1st row of one data frame and the 1st of the other data frame and so one until the 20502 row of the two data frames.

ps: I have missing values (NA) in my data frames

答:
If I'm understanding what you're doing correctly, this isn't the typical way to use data.frames - typically, columns should stand on their own as variables, not rows, and the host of data.frame tools available makes use of this assumption.  That being said, for data.frames A and B below...

```<code>A <- as.data.frame(matrix(1:12,nrow=3,ncol=4))
A
##   V1 V2 V3 V4
## 1  1  4  7 10
## 2  2  5  8 11
## 3  3  6  9 12

B <- as.data.frame(matrix(2:13,nrow=3,ncol=4))
B
##   V1 V2 V3 V4
## 1  2  5  8 11
## 2  3  6  9 12
## 3  4  7 10 13
</code>```

...what you'd like to do is a 2-sample t-test of c(1,4,7,10) vs. c(2,5,8,11), etc for each row, all the way down.  You could get there with

```<code>pvals <- rep(NA, nrow(A))
for(i in 1:nrow(A)) pvals[i] <- t.test(A[i,],B[i,])$p.value
</code>```

Title: T.test for each row in R

Body:
If I'm understanding what you're doing correctly, this isn't the typical way to use data.frames - typically, columns should stand on their own as variables, not rows, and the host of data.frame tools available makes use of this assumption.  That being said, for data.frames A and B below...

A <- as.data.frame(matrix(1:12,nrow=3,ncol=4))
A
##   V1 V2 V3 V4
## 1  1  4  7 10
## 2  2  5  8 11
## 3  3  6  9 12

B <- as.data.frame(matrix(2:13,nrow=3,ncol=4))
B
##   V1 V2 V3 V4
## 1  2  5  8 11
## 2  3  6  9 12
## 3  4  7 10 13

...what you'd like to do is a 2-sample t-test of c(1,4,7,10) vs. c(2,5,8,11), etc for each row, all the way down.  You could get there with

pvals <- rep(NA, nrow(A))
for(i in 1:nrow(A)) pvals[i] <- t.test(A[i,],B[i,])$p.value


问:
Statsmodels - Negative Binomial doesn't converge while GLM does converge
I'm trying to do a Negative Binomial regression using Python's statsmodels package. The model estimates fine when using the GLM routine i.e.

```<code>model = smf.glm(formula="Sales_Focus_2016 ~ Sales_Focus_2015  + A_Calls + A_Ed", data=df, family=sm.families.NegativeBinomial()).fit()
model.summary()
</code>```

However, the GLM routine doesn't estimate alpha, the dispersion term. I tried to use the Negative Binomial routine directly (which does estimate alpha) i.e.

```<code>nb = smf.negativebinomial(formula="Sales_Focus_2016 ~ Sales_Focus_2015 + A_Calls + A_Ed", data=df).fit()
nb.summary()
</code>```

But this doesn't converge. Instead I get the message:

```<code>Warning: Desired error not necessarily achieved due to precision loss.
     Current function value: nan
     Iterations: 0
     Function evaluations: 1
     Gradient evaluations: 1
</code>```

My question is:

Do the two routines use different methods of estimation? Is there a way to make the smf.NegativeBinomial routine use the same estimation methods as the GLM routine?

答:
discrete.NegativeBinomial uses either a newton method (default) in statsmodels or the scipy optimizers. The main problem is that the exponential mean function can easily result in overflow problems or problems from large gradients and hessian when we are still far away from the optimum. There are some attempts in the fit method to get good starting values but this does not always work.

a few possibilities that I usually try

check that no regressor has large values, e.g. rescale to have max below 10

use method='nm' Nelder-Mead as initial optimizer and switch to newton or bfgs after some iterations or after convergence.

try to come up with better starting values (see for example about GLM below)

GLM uses by default iteratively reweighted least squares, IRLS, which is only standard for one parameter families, i.e. it takes the dispersion parameter as given. So the same method cannot be directly used for the full MLE in discrete NegativeBinomial.

GLM negative binomial still specifies the full loglike. So it is possible to do a grid search over the dispersion parameter using GLM.fit() for estimating the mean parameters for each value of the dispersion parameter. This should be equivalent to the corresponding discrete NegativeBinomial version (nb2 ? I don't remember). It could also be used as start_params for the discrete version.

In the statsmodels master version, there is now a connection to allow arbitrary scipy optimizers instead of the ones that were hardcoded. scipy recently obtained trust region newton methods, and will get more in future, which should work for more cases than the simple newton method in statsmodels.
(However, most likely that does not work currently for discrete NegativeBinomial, I just found out about a possible problem https://github.com/statsmodels/statsmodels/issues/3747 )

Body:
I'm trying to do a Negative Binomial regression using Python's statsmodels package. The model estimates fine when using the GLM routine i.e.

model = smf.glm(formula="Sales_Focus_2016 ~ Sales_Focus_2015  + A_Calls + A_Ed", data=df, family=sm.families.NegativeBinomial()).fit()
model.summary()

However, the GLM routine doesn't estimate alpha, the dispersion term. I tried to use the Negative Binomial routine directly (which does estimate alpha) i.e.

nb = smf.negativebinomial(formula="Sales_Focus_2016 ~ Sales_Focus_2015 + A_Calls + A_Ed", data=df).fit()
nb.summary()

But this doesn't converge. Instead I get the message:

Warning: Desired error not necessarily achieved due to precision loss.
     Current function value: nan
     Iterations: 0
     Function evaluations: 1
     Gradient evaluations: 1

My question is:

Do the two routines use different methods of estimation? Is there a way to make the smf.NegativeBinomial routine use the same estimation methods as the GLM routine?


问:
replace NA with groups mean in a non specified number of columns
I want to replace the NA with mean of each single group collembola and mite in multiple columns. Here it is an example with 3 columns however I want to apply this a data frame with 5000 columns

```<code>dat <- read.table(text =
                  "id    ID        length  width    extra
                  101   collembola  2.1     0.9     1
                  102   mite        NA      0.7     NA
                  103   mite        1.1     0.8     2
                  104   collembola  1       NA      3
                  105   collembola  1.5     0.5     4
                  106   mite        NA      NA      NA
                  106   mite        1.9     NA      4",
                  header=TRUE)
</code>```

It works if I enter each column

```<code>library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
data2 <- ddply(dat, ~ ID, transform, length = impute.mean(length))
</code>```

I want to apply the function that calculates the mean of each single group ID collembola and mite across multiple columns, below is what I tried (it does not work):

```<code>dat2 <- ddply(dat, ~ ID, transform,  impute.mean(dat[,3:ncol(dat)]))
</code>```

答:
If you don't mind using dplyr:

library(dplyr)

dat %>%
  group_by(ID) %>%
  mutate_if(is.numeric, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
#> # A tibble: 7 x 5
#> # Groups:   ID [2]
#>      id         ID length width extra
#>   <int>     <fctr>  <dbl> <dbl> <dbl>
#> 1   101 collembola    2.1  0.90     1
#> 2   102       mite    1.5  0.70     3
#> 3   103       mite    1.1  0.80     2
#> 4   104 collembola    1.0  0.70     3
#> 5   105 collembola    1.5  0.50     4
#> 6   106       mite    1.5  0.75     3
#> 7   106       mite    1.9  0.75     4
```

Body:
I want to replace the NA with mean of each single group collembola and mite in multiple columns. Here it is an example with 3 columns however I want to apply this a data frame with 5000 columns

dat <- read.table(text =
                  "id    ID        length  width    extra
                  101   collembola  2.1     0.9     1
                  102   mite        NA      0.7     NA
                  103   mite        1.1     0.8     2
                  104   collembola  1       NA      3
                  105   collembola  1.5     0.5     4
                  106   mite        NA      NA      NA
                  106   mite        1.9     NA      4",
                  header=TRUE)

It works if I enter each column

library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
data2 <- ddply(dat, ~ ID, transform, length = impute.mean(length))

I want to apply the function that calculates the mean of each single group ID collembola and mite across multiple columns, below is what I tried (it does not work):

dat2 <- ddply(dat, ~ ID, transform,  impute.mean(dat[,3:ncol(dat)]))


问:
Convert Image to CVPixelBuffer for Machine Learning Swift
I am trying to get Apple's sample Core ML Models that were demoed at the 2017 WWDC to function correctly. I am using the GoogLeNet to try and classify images (see the Apple Machine Learning Page). The model takes a CVPixelBuffer as an input. I have an image called imageSample.jpg that I'm using for this demo. My code is below:

```<code>        var sample = UIImage(named: "imageSample")?.cgImage
        let bufferThree = getCVPixelBuffer(sample!)

        let model = GoogLeNetPlaces()
        guard let output = try? model.prediction(input: GoogLeNetPlacesInput.init(sceneImage: bufferThree!)) else {
            fatalError("Unexpected runtime error.")
        }

        print(output.sceneLabel)
</code>```

I am always getting the unexpected runtime error in the output rather than an image classification. My code to convert the image is below:

```<code>func getCVPixelBuffer(_ image: CGImage) -> CVPixelBuffer? {
        let imageWidth = Int(image.width)
        let imageHeight = Int(image.height)

        let attributes : [NSObject:AnyObject] = [
            kCVPixelBufferCGImageCompatibilityKey : true as AnyObject,
            kCVPixelBufferCGBitmapContextCompatibilityKey : true as AnyObject
        ]

        var pxbuffer: CVPixelBuffer? = nil
        CVPixelBufferCreate(kCFAllocatorDefault,
                            imageWidth,
                            imageHeight,
                            kCVPixelFormatType_32ARGB,
                            attributes as CFDictionary?,
                            &pxbuffer)

        if let _pxbuffer = pxbuffer {
            let flags = CVPixelBufferLockFlags(rawValue: 0)
            CVPixelBufferLockBaseAddress(_pxbuffer, flags)
            let pxdata = CVPixelBufferGetBaseAddress(_pxbuffer)

            let rgbColorSpace = CGColorSpaceCreateDeviceRGB();
            let context = CGContext(data: pxdata,
                                    width: imageWidth,
                                    height: imageHeight,
                                    bitsPerComponent: 8,
                                    bytesPerRow: CVPixelBufferGetBytesPerRow(_pxbuffer),
                                    space: rgbColorSpace,
                                    bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

            if let _context = context {
                _context.draw(image, in: CGRect.init(x: 0, y: 0, width: imageWidth, height: imageHeight))
            }
            else {
                CVPixelBufferUnlockBaseAddress(_pxbuffer, flags);
                return nil
            }

            CVPixelBufferUnlockBaseAddress(_pxbuffer, flags);
            return _pxbuffer;
        }

        return nil
    }
</code>```

I got this code from a previous StackOverflow post (last answer here). I recognize that the code may not be correct, but I have no idea of how to do this myself. I believe that this is the section that contains the error. The model calls for the following type of input: Image<RGB,224,224>

答:
You don't need to do a bunch of image mangling yourself to use a Core ML model with an image — the new Vision framework can do that for you.

```<code>import Vision
import CoreML

let model = try VNCoreMLModel(for: MyCoreMLGeneratedModelClass().model)
let request = VNCoreMLRequest(model: model, completionHandler: myResultsMethod)
let handler = VNImageRequestHandler(url: myImageURL)
handler.perform([request])

func myResultsMethod(request: VNRequest, error: Error?) {
    guard let results = request.results as? [VNClassificationObservation]
        else { fatalError("huh") }
    for classification in results {
        print(classification.identifier, // the scene label
              classification.confidence)
    }

}
</code>```

The WWDC17 session on Vision should have a bit more info — it's tomorrow afternoon.

Body:
I am trying to get Apple's sample Core ML Models that were demoed at the 2017 WWDC to function correctly. I am using the GoogLeNet to try and classify images (see the Apple Machine Learning Page). The model takes a CVPixelBuffer as an input. I have an image called imageSample.jpg that I'm using for this demo. My code is below:

        var sample = UIImage(named: "imageSample")?.cgImage
        let bufferThree = getCVPixelBuffer(sample!)

        let model = GoogLeNetPlaces()
        guard let output = try? model.prediction(input: GoogLeNetPlacesInput.init(sceneImage: bufferThree!)) else {
            fatalError("Unexpected runtime error.")
        }

        print(output.sceneLabel)

I am always getting the unexpected runtime error in the output rather than an image classification. My code to convert the image is below:

func getCVPixelBuffer(_ image: CGImage) -> CVPixelBuffer? {
        let imageWidth = Int(image.width)
        let imageHeight = Int(image.height)

        let attributes : [NSObject:AnyObject] = [
            kCVPixelBufferCGImageCompatibilityKey : true as AnyObject,
            kCVPixelBufferCGBitmapContextCompatibilityKey : true as AnyObject
        ]

        var pxbuffer: CVPixelBuffer? = nil
        CVPixelBufferCreate(kCFAllocatorDefault,
                            imageWidth,
                            imageHeight,
                            kCVPixelFormatType_32ARGB,
                            attributes as CFDictionary?,
                            &pxbuffer)

        if let _pxbuffer = pxbuffer {
            let flags = CVPixelBufferLockFlags(rawValue: 0)
            CVPixelBufferLockBaseAddress(_pxbuffer, flags)
            let pxdata = CVPixelBufferGetBaseAddress(_pxbuffer)

            let rgbColorSpace = CGColorSpaceCreateDeviceRGB();
            let context = CGContext(data: pxdata,
                                    width: imageWidth,
                                    height: imageHeight,
                                    bitsPerComponent: 8,
                                    bytesPerRow: CVPixelBufferGetBytesPerRow(_pxbuffer),
                                    space: rgbColorSpace,
                                    bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

            if let _context = context {
                _context.draw(image, in: CGRect.init(x: 0, y: 0, width: imageWidth, height: imageHeight))
            }
            else {
                CVPixelBufferUnlockBaseAddress(_pxbuffer, flags);
                return nil
            }

            CVPixelBufferUnlockBaseAddress(_pxbuffer, flags);
            return _pxbuffer;
        }

        return nil
    }

I got this code from a previous StackOverflow post (last answer here). I recognize that the code may not be correct, but I have no idea of how to do this myself. I believe that this is the section that contains the error. The model calls for the following type of input: Image<RGB,224,224>

Body:
You don't need to do a bunch of image mangling yourself to use a Core ML model with an image — the new Vision framework can do that for you.

import Vision
import CoreML

let model = try VNCoreMLModel(for: MyCoreMLGeneratedModelClass().model)
let request = VNCoreMLRequest(model: model, completionHandler: myResultsMethod)
let handler = VNImageRequestHandler(url: myImageURL)
handler.perform([request])

func myResultsMethod(request: VNRequest, error: Error?) {
    guard let results = request.results as? [VNClassificationObservation]
        else { fatalError("huh") }
    for classification in results {
        print(classification.identifier, // the scene label
              classification.confidence)
    }

}

The WWDC17 session on Vision should have a bit more info — it's tomorrow afternoon.


问:
Can VSCode / Typescript do Type inference on plugin-modifed objects?
I'm enjoying the developer ergonomics of VSCode and Typescript. A slight snag has occurred when I've applied a plugin to the pouchdb package:

```<code>import * as pouch from 'pouchdb-browser'
pouch.plugin(require('pouchdb-authentication'));

const remoteDB: PouchDB.Database<PouchDB.Core.Encodable> = new pouch(
    'https://user.cloudant.com/databaseName',
    { skip_setup: true } // a param wanted by the plugin
);

// invoking a method added by the plugin:
remoteDB.signup('username','password', (err, resp) => {console.log(err)} );
</code>```

The above code works in the browser, but my development experience is hindered because VSCode isn't recognizing the plugin-added methods:

Is this sort of type inference outside of VSCode's scope?

OF NOTE: There is no @types package for this package on NPM: https://www.npmjs.com/package/@types/pouchdb-authentication is a 404. Is that the missing piece?

答:
As far as I can tell from the documentation (https://pouchdb.com/api.html#plugins), the plugin method extends your PouchDB.Database object with whatever you pass to it.

As such in reality, if you use pouch.plugin(require('pouchdb-authentication'));, then your database is no longer of type PouchDB.Database<T>; it is actually an extension of that interface. So the fact that VSCode is complaining is correct, as the type you have declared remoteDB to have does not have a signup method.

What you can do then is create your own interface for remoteDB that extends PouchDB.Database<T> with whatever methods and properties pouchdb-authentication adds; e.g.

```<code>interface PouchDBSignupPlugin<T> extends PouchDB.Database<T> {
    signup: (username: string, password: string, handler: (err: any, resp: any) => void) => any;
}
</code>```

and use it as such:

```<code>const remoteDB = new pouch<PouchDB.Core.Encodable>(
    'https://user.cloudant.com/databaseName',
    { skip_setup: true } // a param wanted by the plugin
) as PouchDBSignupPlugin<PouchDB.Core.Encodable>;
</code>```

Then you should find that VSCode and TypeScript will recognise a signup method on remoteDB.

Body:
I'm enjoying the developer ergonomics of VSCode and Typescript. A slight snag has occurred when I've applied a plugin to the pouchdb package:

import * as pouch from 'pouchdb-browser'
pouch.plugin(require('pouchdb-authentication'));

const remoteDB: PouchDB.Database<PouchDB.Core.Encodable> = new pouch(
    'https://user.cloudant.com/databaseName',
    { skip_setup: true } // a param wanted by the plugin
);

// invoking a method added by the plugin:
remoteDB.signup('username','password', (err, resp) => {console.log(err)} );

The above code works in the browser, but my development experience is hindered because VSCode isn't recognizing the plugin-added methods:

Is this sort of type inference outside of VSCode's scope?

OF NOTE: There is no @types package for this package on NPM: https://www.npmjs.com/package/@types/pouchdb-authentication is a 404. Is that the missing piece?

Body:
As far as I can tell from the documentation (https://pouchdb.com/api.html#plugins), the plugin method extends your PouchDB.Database object with whatever you pass to it.

As such in reality, if you use pouch.plugin(require('pouchdb-authentication'));, then your database is no longer of type PouchDB.Database<T>; it is actually an extension of that interface. So the fact that VSCode is complaining is correct, as the type you have declared remoteDB to have does not have a signup method.

What you can do then is create your own interface for remoteDB that extends PouchDB.Database<T> with whatever methods and properties pouchdb-authentication adds; e.g.

interface PouchDBSignupPlugin<T> extends PouchDB.Database<T> {
    signup: (username: string, password: string, handler: (err: any, resp: any) => void) => any;
}

and use it as such:

const remoteDB = new pouch<PouchDB.Core.Encodable>(
    'https://user.cloudant.com/databaseName',
    { skip_setup: true } // a param wanted by the plugin
) as PouchDBSignupPlugin<PouchDB.Core.Encodable>;

Then you should find that VSCode and TypeScript will recognise a signup method on remoteDB.


问:
Make only part of a resources string a link in xaml
My goal is to have a string with a link that opens a new window. The catch is that the string has to be localizable.

In order for our localization tool to be able to recognize the strings, it has to be defined like this:

```<code><sys:String x:Uid="testString" x:Key="testString">click here for a good time</sys:String>
</code>```

The string would then be referenced like this:

```<code><TextBlock Text="{StaticResource testString}"/>
</code>```

I need the word "here" to be a link that opens another window. The other words should do nothing when clicked on.

Is this even possible?

答:
Is there some reason these strings can't be split up?  You are already assuming in your question that 'here' translates to the place they should click.</p>

```<code><sys:String x:Uid="prefix" x:Key="testString">click</sys:String>
<sys:String x:Uid="caption" x:Key="testString">here</sys:String>
<sys:String x:Uid="suffix" x:Key="testString">for a good time</sys:String>

<StackPanel>
   <TextBlock Text="{StaticResource prefix}" />
   <Button Command={StaticResource someCommand}>
      <TextBlock Text="{StaticResource caption}" />
   </Button>
   <TextBlock Text="{StaticResource suffix}" />
</StackPanel>
</code>```

Body:
My goal is to have a string with a link that opens a new window. The catch is that the string has to be localizable.

In order for our localization tool to be able to recognize the strings, it has to be defined like this:

<sys:String x:Uid="testString" x:Key="testString">click here for a good time</sys:String>

The string would then be referenced like this:

<TextBlock Text="{StaticResource testString}"/>

I need the word "here" to be a link that opens another window. The other words should do nothing when clicked on.

Is this even possible?

Body:
Is there some reason these strings can't be split up?  You are already assuming in your question that 'here' translates to the place they should click.

<sys:String x:Uid="prefix" x:Key="testString">click</sys:String>
<sys:String x:Uid="caption" x:Key="testString">here</sys:String>
<sys:String x:Uid="suffix" x:Key="testString">for a good time</sys:String>

<StackPanel>
   <TextBlock Text="{StaticResource prefix}" />
   <Button Command={StaticResource someCommand}>
      <TextBlock Text="{StaticResource caption}" />
   </Button>
   <TextBlock Text="{StaticResource suffix}" />
</StackPanel>


问:
Enterprise Service Bus and BPM
I am a Java professional. I have a requirement to implement Enterprise Service Bus(ESB). There are quite a few ESB providers are available in the market.I am confusing a bit among those.
Please suggest which one is the best to implement ESB and BPM. I am expecting to have an open source solution with rich documentation and easy to understand with number of examples and scenarios so that we can start from scratch and implement it without any hassle.</p>

答:
WSO2 has a good option with their Enterprise Integratir. This combines ESB, BPM and related functionality.

Check here for more: http://wso2.com/integration

However this is one of those questions that is purely opinion based.

Title: Enterprise Service Bus and BPM


问:
SQLCMD include all scripts in folder
In my Post Deployment Script, I would like to include all script files in a folder using a wildcard like this:
       :r .\$(ReleaseName)\*.sql

Is there a way to do this? I can't find any..

答:
I took a different approach that was easier for me to understand.

I simply added code to the Pre-build event in the database project properties page that copies the script files into a single file. I call a bat file and pass in the project path as a parameter because it's much nicer to edit the file than trying to edit in that little textbox in the properties page.

```<code>$(ProjectDir)PreBuildEvent.bat "$(ProjectDir)"
</code>```

I set the contents of the bat to this:

```<code>copy %ProjectDir%DbUpdateScripts\*-Pre.sql %ProjectDir%DbUpdateScripts\AllPreScripts.sql
copy %ProjectDir%DbUpdateScripts\*-Post.sql %ProjectDir%DbUpdateScripts\AllPostScripts.sql
</code>```

Then just include those files in your actual pre and post deploy scripts.

```<code>:r .\DbUpdateScripts\AllPreScripts.sql
:r .\DbUpdateScripts\AllPostScripts.sql
</code>```

And finally, add AllPreScripts.sql and AllPostScripts.sql to your .gitignore file if you have one to prevent them from getting added to source control.

Title: SQLCMD include all scripts in folder

Body:
I took a different approach that was easier for me to understand.

I simply added code to the Pre-build event in the database project properties page that copies the script files into a single file. I call a bat file and pass in the project path as a parameter because it's much nicer to edit the file than trying to edit in that little textbox in the properties page.

$(ProjectDir)PreBuildEvent.bat "$(ProjectDir)"

I set the contents of the bat to this:

copy %ProjectDir%DbUpdateScripts\*-Pre.sql %ProjectDir%DbUpdateScripts\AllPreScripts.sql
copy %ProjectDir%DbUpdateScripts\*-Post.sql %ProjectDir%DbUpdateScripts\AllPostScripts.sql

Then just include those files in your actual pre and post deploy scripts.

:r .\DbUpdateScripts\AllPreScripts.sql
:r .\DbUpdateScripts\AllPostScripts.sql

And finally, add AllPreScripts.sql and AllPostScripts.sql to your .gitignore file if you have one to prevent them from getting added to source control.


问:
Unix Shell Script - AWK delimiter issue
I have following lines in a file. Please note I have intentionally kept the extra hash between 2 and 0 in the 2nd line.
File name : test.txt

```<code>Name#|#Age#|#Dept
AC#|#2#0#|#Science
BC#|#22#|#Commerce
</code>```

I am using awk to get the data in Dept column

```<code>awk -F "#|#" -v c="Dept" 'NR==1{for (i=1; i<=NF; i++) if ($i==c){p=i; break}; next} {print $p}' "test.txt" >> result.txt
</code>```

The result.txt shows me the following

```<code>|
Commerce
</code>```

The first line is coming as pipe because if the extra # in the first line.
Can anyone help on this

答:
Currently the meaning of the delimiter set is: match # or #. The pipe | character in this case acts as an OR statement; instead try using:

```<code>awk -F '#[|]#' ...
</code>```

Putting | into a character class [ ... ] awk will match it literally.

Title: Unix Shell Script - AWK delimiter issue

Body:
I have following lines in a file. Please note I have intentionally kept the extra hash between 2 and 0 in the 2nd line.
File name : test.txt

Name#|#Age#|#Dept
AC#|#2#0#|#Science
BC#|#22#|#Commerce

I am using awk to get the data in Dept column

awk -F "#|#" -v c="Dept" 'NR==1{for (i=1; i<=NF; i++) if ($i==c){p=i; break}; next} {print $p}' "test.txt" >> result.txt

The result.txt shows me the following

|
Commerce

The first line is coming as pipe because if the extra # in the first line.
Can anyone help on this

Body:
Currently the meaning of the delimiter set is: match # or #. The pipe | character in this case acts as an OR statement; instead try using:

awk -F '#[|]#' ...

Putting | into a character class [ ... ] awk will match it literally.


问:
How to git reset an old commit for the purposes of branching off another commit
So, midway through a PR I realized this would be a lot easier if I had branched off another commit (let's call this commit A) on a separate branch. In short, my current PR (call this commit B) is dependent on that commit (commit A).

Unfortunately, while working on commit B, I made one commit. Let's call this commit B0. How do I checkout to prior to me commiting commit B0 so that I have non-committed files that I can stash? IN short, I want to stash my changes from commit B0, branch off commit A, and stash pop my changes onto commit A1. How do I do this?

Can I also cherry pick?

答:
So, from how I understand it, your history looks like this:

```<code>       your pull request
             ↓
A --- B0 --- B
</code>```

And you actually want it to look like this:

```<code>A --- B0
 \
  \-- B
      ↑
updated pull request
</code>```

In that case, you have multiple ways of doing so. A very quick way would be to just make a new branch off A and cherry-pick your commit:

```<code>git checkout -b new_pr A
git cherry-pick old_pr
</code>```

Then you can push your new branch to your old branch to update the pull request. Or you check out your old branch and hard-reset it to the new branch.

You can also use interactive rebase to remove B0 simply from the history (if that’s a good idea depends on whether you still want to use that for anything). For that, just run git rebase -i A and then in the editor remove the line for B0.

Body:
So, from how I understand it, your history looks like this:

       your pull request
             ↓
A --- B0 --- B

And you actually want it to look like this:

A --- B0
 \
  \-- B
      ↑
updated pull request

In that case, you have multiple ways of doing so. A very quick way would be to just make a new branch off A and cherry-pick your commit:

git checkout -b new_pr A
git cherry-pick old_pr

Then you can push your new branch to your old branch to update the pull request. Or you check out your old branch and hard-reset it to the new branch.

You can also use interactive rebase to remove B0 simply from the history (if that’s a good idea depends on whether you still want to use that for anything). For that, just run git rebase -i A and then in the editor remove the line for B0.


问:
How to change the name of the Special Fields in Crystal Report?
In Crystal Report, I want to change the text of the Special Field "Page N of M" as "Sheet N of M".
How to do this?
I am using Crystal Reports 2008.</p>

答:
Agree with PowerUser!
Make a text box with "Sheet" then
insert SPECIAL FIELD [PAGE NUMBER] then type in text box "of" then insert SPECIAL FIELD [TOTAL PAGE COUNT]

result: SHEET 1 of 1 (depending on the number of docs your working with)


问:
Android Gradle - Gitlab CI - Docker - CMake - NullPointerException
I'm trying to get simple Android Unit Tests to run on Gitlab CI, but I'm having troubles getting things to build correctly in the CI Docker image.  I have the master project which pulls from a Library project.  The Library has C code in it, so I need to use CMake to get it to build.  All of this is working locally on my windows machine when using Android Studio.  However, once I move to the CI server, things break with the following error:

```
Using incremental javac compilation for :Library debug.
Incremental java compilation is an incubating feature.
Checking the license for package CMake 3.6.3155560 in /android-sdk-linux/licenses
License for package CMake 3.6.3155560 accepted.
Preparing "Install CMake 3.6.3155560 (revision: 3.6.3155560)".
"Install CMake 3.6.3155560 (revision: 3.6.3155560)" ready.
Finishing "Install CMake 3.6.3155560 (revision: 3.6.3155560)"
Installing CMake 3.6.3155560 in /android-sdk-linux/cmake/3.6.3155560
"Install CMake 3.6.3155560 (revision: 3.6.3155560)" complete.
"Install CMake 3.6.3155560 (revision: 3.6.3155560)" finished.

<b>FAILURE: Build failed with an exception.</b>

* What went wrong:
A problem occurred configuring project ':Library'.
> java.lang.NullPointerException (no error message)

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':Library'.
    at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:89)
    ...
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
<b>Caused by: java.lang.NullPointerException
    at com.android.builder.sdk.DefaultSdkLoader.installSdkTool(DefaultSdkLoader.java:572)
    at com.android.build.gradle.internal.SdkHandler.installCMake(SdkHandler.java:302)</b>
    at com.android.build.gradle.tasks.ExternalNativeJsonGenerator.create(ExternalNativeJsonGenerator.java:628)
    at com.android.build.gradle.internal.TaskManager.createExternalNativeBuildJsonGenerators(TaskManager.java:1241)
    at com.android.build.gradle.internal.LibraryTaskManager.lambda$createTasksForVariantData$11(LibraryTaskManager.java:240)
    ...
    at com.sun.proxy.$Proxy15.afterEvaluate(Unknown Source)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:82)
    ... 56 more

BUILD FAILED

Total time: 1 mins 25.384 secs
Stopped 0 worker daemon(s).
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: A problem occurred configuring project ':Library'.] from daemon DaemonInfo{pid=39, address=[1f3b75f9-7080-48b5-b298-0e6136640a0a port:41964, addresses:[/127.0.0.1]],     state=Busy, lastBusy=1496784783851, context=DefaultDaemonContext[uid=0e3eadf0-a7bd-4ede-9eb8-0c2a96ebef58,javaHome=/usr/lib/jvm/java-8-openjdk-amd64,daemonRegistryDir=/root/.gradle/daemon,pid=39,idleTimeout=10800000,daemonOpts=-Xmx1536m,-Dfile.encoding=UTF-8,-Duser.country,-Duser.language=en,    -Duser.variant]} (build should be done).
ERROR: Job failed: exit code 1
```

Judging by the line

```<code>Caused by: java.lang.NullPointerException
    at com.android.builder.sdk.DefaultSdkLoader.installSdkTool(DefaultSdkLoader.java:572)
    at com.android.build.gradle.internal.SdkHandler.installCMake(SdkHandler.java:302)
</code>```

it looks like it is a problem with the CMake.  But it looks like it is installed and the licence is accepted as noted by the output at the start of that block above.

Can anyone give me some pointers on what is the problem?

* Is it that gradle doesn't know where CMake was installed?
* Is it a problem perhaps with the NDK?
* Or perhaps where I can find the source code for com.android.build.gradle.internal.SdkHandler.installCMake and com.android.builder.sdk.DefaultSdkLoader.installSdkTool.

My searches have been unfruitful.

I can provide more about my setup upon request. (i.e. android project, docker image, gitlab-ci.yml, etc.)

答:
Well, mbertin commented on Feb 2 at here that by using a lower gradle build tool, it solved the problem for him.  (i.e. classpath 'com.android.tools.build:gradle:2.2.2).

After giving it an attempt, my build script got passed that error!  (anyone know why?)

Thanks for the emotional support Stack Overflow! You are the best!

Body:
I'm trying to get simple Android Unit Tests to run on Gitlab CI, but I'm having troubles getting things to build correctly in the CI Docker image.  I have the master project which pulls from a Library project.  The Library has C code in it, so I need to use CMake to get it to build.  All of this is working locally on my windows machine when using Android Studio.  However, once I move to the CI server, things break with the following error:

Using incremental javac compilation for :Library debug.
Incremental java compilation is an incubating feature.
Checking the license for package CMake 3.6.3155560 in /android-sdk-linux/licenses
License for package CMake 3.6.3155560 accepted.
Preparing "Install CMake 3.6.3155560 (revision: 3.6.3155560)".
"Install CMake 3.6.3155560 (revision: 3.6.3155560)" ready.
Finishing "Install CMake 3.6.3155560 (revision: 3.6.3155560)"
Installing CMake 3.6.3155560 in /android-sdk-linux/cmake/3.6.3155560
"Install CMake 3.6.3155560 (revision: 3.6.3155560)" complete.
"Install CMake 3.6.3155560 (revision: 3.6.3155560)" finished.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':Library'.
> java.lang.NullPointerException (no error message)

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':Library'.
    at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:89)
    ...
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.NullPointerException
    at com.android.builder.sdk.DefaultSdkLoader.installSdkTool(DefaultSdkLoader.java:572)
    at com.android.build.gradle.internal.SdkHandler.installCMake(SdkHandler.java:302)
    at com.android.build.gradle.tasks.ExternalNativeJsonGenerator.create(ExternalNativeJsonGenerator.java:628)
    at com.android.build.gradle.internal.TaskManager.createExternalNativeBuildJsonGenerators(TaskManager.java:1241)
    at com.android.build.gradle.internal.LibraryTaskManager.lambda$createTasksForVariantData$11(LibraryTaskManager.java:240)
    ...
    at com.sun.proxy.$Proxy15.afterEvaluate(Unknown Source)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:82)
    ... 56 more

BUILD FAILED

Total time: 1 mins 25.384 secs
Stopped 0 worker daemon(s).
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: A problem occurred configuring project ':Library'.] from daemon DaemonInfo{pid=39, address=[1f3b75f9-7080-48b5-b298-0e6136640a0a port:41964, addresses:[/127.0.0.1]],     state=Busy, lastBusy=1496784783851, context=DefaultDaemonContext[uid=0e3eadf0-a7bd-4ede-9eb8-0c2a96ebef58,javaHome=/usr/lib/jvm/java-8-openjdk-amd64,daemonRegistryDir=/root/.gradle/daemon,pid=39,idleTimeout=10800000,daemonOpts=-Xmx1536m,-Dfile.encoding=UTF-8,-Duser.country,-Duser.language=en,    -Duser.variant]} (build should be done).
ERROR: Job failed: exit code 1

Judging by the line

Caused by: java.lang.NullPointerException
    at com.android.builder.sdk.DefaultSdkLoader.installSdkTool(DefaultSdkLoader.java:572)
    at com.android.build.gradle.internal.SdkHandler.installCMake(SdkHandler.java:302)

it looks like it is a problem with the CMake.  But it looks like it is installed and the licence is accepted as noted by the output at the start of that block above.

Can anyone give me some pointers on what is the problem?

* Is it that gradle doesn't know where CMake was installed?
* Is it a problem perhaps with the NDK?
* Or perhaps where I can find the source code for com.android.build.gradle.internal.SdkHandler.installCMake and com.android.builder.sdk.DefaultSdkLoader.installSdkTool.

My searches have been unfruitful.

I can provide more about my setup upon request. (i.e. android project, docker image, gitlab-ci.yml, etc.)


问:
Problems with menu OffScreen
I have an off canvas menu and he's always on the screen, but my main div is above him, só, when i click on the button, the main swipe to right and then u can see the menu, OK? OK. But i have 3 problems:

When the menu is activated the page automaticly scrolls to the top, but it should only disable the scroll.

When I close the menu, my body keeps not scrolling, even if I change it via Jquery

The links of the menu doesn't work.

I've tried to use TranslateX(), but It doesn't show the menu. Where I'm Wrong?

I'm using the menu of this website as inspiration, http://www.x-apps.com.br/ and that's my website https://tiagosilveiraa.github.io/

var menu = false;
$('#hamburguer').click(function() {
    if (menu === false) {
      mostraCanvas();
    } else {
      escondeCanvas();
    }
});

function escondeCanvas() {
    $("#main").css("padding-left", "0");
    $("html, body").css("overflow", "auto");

    menu = false;
}

function mostraCanvas() {
  $("#main").css("padding-left", "50vw");
  $("html, body").css("overflow", "hidden");
  menu = true;
}

$('.off-item').click(function() {
    escondeCanvas();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.off-canvas{
  padding-top: 10px;
  left: 0;
  background-color: #292929;
  height: 100vh;
  width: 50vw;
  position: fixed;
  text-align: left;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: -1;
}
#main{
  z-index: 9999;
  margin: 0 !important;
  transition: all .2s linear;
  -webkit-transition: padding .2s linear;
  -moz-transition: padding .2s linear;
  -o-transition: padding .2s linear;
}</code>```

      <button id="hamburguer">

<button>

Inicio

Sobre Mim

Portfólio

Habilidades

Contato

     ...body stuff here...

```

答:
Try the following code. I refactored the html because a tag cannot be inside ul. I changed also the overflow into overflow-x to avoid the scroll problem. I hope it helps.

var menu = false;
$('#hamburguer').click(function() {
    if (menu === false) {
      mostraCanvas();
    } else {
      escondeCanvas();
    }
});

function escondeCanvas() {
    $("#main").css("padding-left", "0");
    $("body").css("overflow-x", "");

    menu = false;
}

function mostraCanvas() {
  $("#main").css("padding-left", "50vw");
  $("body").css("overflow-x", "hidden");
  menu = true;
}

$('.off-item').click(function() {
    escondeCanvas();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.off-canvas{
  padding-top: 10px;
  left: 0;
  background-color: #292929;
  height: 100vh;
  width: 50vw;
  position: fixed;
  text-align: left;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: -1;
}
#main{
  z-index: 9999;
  margin: 0 !important;
  transition: all .2s linear;
  -webkit-transition: padding .2s linear;
  -moz-transition: padding .2s linear;
  -o-transition: padding .2s linear;
}</code>```

      <button id="hamburguer">

<button>

Inicio

Sobre Mim

Portfólio

Habilidades

Contato

     ...body stuff here...

```

Title: Problems with menu OffScreen

Body:
I have an off canvas menu and he's always on the screen, but my main div is above him, só, when i click on the button, the main swipe to right and then u can see the menu, OK? OK. But i have 3 problems:

When the menu is activated the page automaticly scrolls to the top, but it should only disable the scroll.

When I close the menu, my body keeps not scrolling, even if I change it via Jquery

The links of the menu doesn't work.

I've tried to use TranslateX(), but It doesn't show the menu. Where I'm Wrong?

I'm using the menu of this website as inspiration, http://www.x-apps.com.br/ and that's my website https://tiagosilveiraa.github.io/

var menu = false;
$('#hamburguer').click(function() {
    if (menu === false) {
      mostraCanvas();
    } else {
      escondeCanvas();
    }
});

function escondeCanvas() {
    $("#main").css("padding-left", "0");
    $("html, body").css("overflow", "auto");

    menu = false;
}

function mostraCanvas() {
  $("#main").css("padding-left", "50vw");
  $("html, body").css("overflow", "hidden");
  menu = true;
}

$('.off-item').click(function() {
    escondeCanvas();
});

.off-canvas{
  padding-top: 10px;
  left: 0;
  background-color: #292929;
  height: 100vh;
  width: 50vw;
  position: fixed;
  text-align: left;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: -1;
}
#main{
  z-index: 9999;
  margin: 0 !important;
  transition: all .2s linear;
  -webkit-transition: padding .2s linear;
  -moz-transition: padding .2s linear;
  -o-transition: padding .2s linear;
}

      <button id="hamburguer">

<button>

Inicio

Sobre Mim

Portfólio

Habilidades

Contato

     ...body stuff here...

Body:
Try the following code. I refactored the html because a tag cannot be inside ul. I changed also the overflow into overflow-x to avoid the scroll problem. I hope it helps.

var menu = false;
$('#hamburguer').click(function() {
    if (menu === false) {
      mostraCanvas();
    } else {
      escondeCanvas();
    }
});

function escondeCanvas() {
    $("#main").css("padding-left", "0");
    $("body").css("overflow-x", "");

    menu = false;
}

function mostraCanvas() {
  $("#main").css("padding-left", "50vw");
  $("body").css("overflow-x", "hidden");
  menu = true;
}

$('.off-item').click(function() {
    escondeCanvas();
});

.off-canvas{
  padding-top: 10px;
  left: 0;
  background-color: #292929;
  height: 100vh;
  width: 50vw;
  position: fixed;
  text-align: left;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: -1;
}
#main{
  z-index: 9999;
  margin: 0 !important;
  transition: all .2s linear;
  -webkit-transition: padding .2s linear;
  -moz-transition: padding .2s linear;
  -o-transition: padding .2s linear;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
      <div class="topo" id="topo">
      <button id="hamburguer"><h1><span class="glyphicon glyphicon-menu-hamburger blue btn-nav"></span></h1><button>
    </div>
      <nav class="navbar" id="navbar">
        <ul>
          <li class="nav-item">
            <a href="#banner" id="linkbanner">
              <h2>Inicio</h2>
            </a>
          </li>
          <li class="nav-item">
            <a href="#sobremim">
              <h2>Sobre Mim</h2>
            </a>
          </li>
          <li class="nav-item">
            <a href="#portfolio">
              <h2>Portfólio</h2>
            </a>
          </li>
          <li class="nav-item">
            <a href="#habilidades">
              <h2>Habilidades</h2>
            </a>
          </li>
          <li class="nav-item">
            <a href="#contato">
              <h2>Contato</h2>
            </a>
          </li>
        </ul>
      </nav>
     ...body stuff here...
  </div>


问:
install pil on virtualenv with libjpeg
Currently I'm installing PIL into my virtual env as follows:

```<code>pip install -E . -r ./releases/%s/requirements.txt
</code>```

where requirements.txt contains:

```<code>pil
</code>```

I can upload png images but not jpeg images currently.  From reading on the web it seems i may need libjpeg decoder?  Am i installing pil incorrectly?  What is the proper way to install pil for django in a virtual env with libjpeg?

答:
You must install the libraries: </p>

```<code>sudo aptitude install libjpeg62 libjpeg62-dev zlib1g-dev
</code>```

Title: install pil on virtualenv with libjpeg

Body:
Currently I'm installing PIL into my virtual env as follows:

pip install -E . -r ./releases/%s/requirements.txt

where requirements.txt contains:

pil

I can upload png images but not jpeg images currently.  From reading on the web it seems i may need libjpeg decoder?  Am i installing pil incorrectly?  What is the proper way to install pil for django in a virtual env with libjpeg?

Body:
You must install the libraries:

sudo aptitude install libjpeg62 libjpeg62-dev zlib1g-dev


问:
VB.NET Addin How do I select current worksheet
I'm trying to create an Excel VSTO Addin with VS2015 for a handful of VBA macros that I have.  I could do this using VBA, but want to get my feet wet in VB.NET.  The problem I'm facing though is how to get the active worksheet and assign it to a variable.  Then, I need to pass in a range that I converted to text previous.

The macro essentially enables a user to compare two lists of data by selecting the ranges and then highlighting items that appear in both lists.

Here's the code that executes when a user tries to select the range (works fine)

```<code>    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Try
        Me.Hide()
        Dim R As Microsoft.Office.Interop.Excel.Range
        Dim A As String
        'note how the Application.InputBox brings up different settings to just InputBox
        R = Globals.ThisAddIn.Application.InputBox(Prompt:="Please select the reference range", Type:=8)
        A = R.Address
        Me.TextBox1.Text = A
        Me.Show()
        Me.TopMost = True
        Exit Sub

    Catch
        MsgBox("Please select a valid range!")
        Me.Show()
    End Try
End Sub
</code>```

Here's the code behind the "Search and Highlight" button, that should compare the two ranges and highlight duplicates.  However, when I run this it highlights cells in a different workbook, presumable the first one that I have open.  How do I make sure it's opening the current workbook that I'm operating in?

```<code>    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim xlApp As New Excel.Application
    Dim ws As Excel.Worksheet
    Dim sheetName As String
    Dim cell_1 As Excel.Range
    Dim cell_2 As Excel.Range
    Dim rng_1 As Excel.Range
    Dim rng_2 As Excel.Range

    xlApp = GetObject(, "Excel.Application")
    ws = xlApp.ActiveSheet
    sheetName = ws.Name

    rng_1 = ws.Range(Me.TextBox2.Text)
    rng_2 = ws.Range(Me.TextBox1.Text)

    For Each cell_1 In rng_1
        For Each cell_2 In rng_2
            If cell_2.Text = cell_1.Text Then
                cell_2.Interior.ColorIndex = 6

            End If
        Next cell_2
    Next cell_1

    Me.Close()

End Sub
</code>```

答:
You must specify a workbook file name that you wish to interact with.

```<code>Dim ExcPro as New Excel.Application
Dim Excwrkbook as Excel.Workbook=ExcPro.Workbooks.Open("YoufileName")
</code>```

Dim ws As Excel.Worksheet = Excwrkbook.ActiveSheet

You can also iterate through the workbooks collection if it's already open if you know some details about the workbook such as its name.

```<code>Dim Exc_Books As Excel.Workbooks = Excpro.Workbooks
Dim Exc_book As Excel.Workbook = Exc_Books.Item(1)
</code>```

Body:
I'm trying to create an Excel VSTO Addin with VS2015 for a handful of VBA macros that I have.  I could do this using VBA, but want to get my feet wet in VB.NET.  The problem I'm facing though is how to get the active worksheet and assign it to a variable.  Then, I need to pass in a range that I converted to text previous.

The macro essentially enables a user to compare two lists of data by selecting the ranges and then highlighting items that appear in both lists.

Here's the code that executes when a user tries to select the range (works fine)

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Try
        Me.Hide()
        Dim R As Microsoft.Office.Interop.Excel.Range
        Dim A As String
        'note how the Application.InputBox brings up different settings to just InputBox
        R = Globals.ThisAddIn.Application.InputBox(Prompt:="Please select the reference range", Type:=8)
        A = R.Address
        Me.TextBox1.Text = A
        Me.Show()
        Me.TopMost = True
        Exit Sub

    Catch
        MsgBox("Please select a valid range!")
        Me.Show()
    End Try
End Sub

Here's the code behind the "Search and Highlight" button, that should compare the two ranges and highlight duplicates.  However, when I run this it highlights cells in a different workbook, presumable the first one that I have open.  How do I make sure it's opening the current workbook that I'm operating in?

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim xlApp As New Excel.Application
    Dim ws As Excel.Worksheet
    Dim sheetName As String
    Dim cell_1 As Excel.Range
    Dim cell_2 As Excel.Range
    Dim rng_1 As Excel.Range
    Dim rng_2 As Excel.Range

    xlApp = GetObject(, "Excel.Application")
    ws = xlApp.ActiveSheet
    sheetName = ws.Name

    rng_1 = ws.Range(Me.TextBox2.Text)
    rng_2 = ws.Range(Me.TextBox1.Text)

    For Each cell_1 In rng_1
        For Each cell_2 In rng_2
            If cell_2.Text = cell_1.Text Then
                cell_2.Interior.ColorIndex = 6

            End If
        Next cell_2
    Next cell_1

    Me.Close()

End Sub

Body:
You must specify a workbook file name that you wish to interact with.

Dim ExcPro as New Excel.Application
Dim Excwrkbook as Excel.Workbook=ExcPro.Workbooks.Open("YoufileName")

Dim ws As Excel.Worksheet = Excwrkbook.ActiveSheet

You can also iterate through the workbooks collection if it's already open if you know some details about the workbook such as its name.

Dim Exc_Books As Excel.Workbooks = Excpro.Workbooks
Dim Exc_book As Excel.Workbook = Exc_Books.Item(1)


问:
Bullets and numbered lists not working in my markdown
I'm setting up a Jekyll portfolio site and I'm working on converting my resume into markdown. I'm having an issue where I'm trying to create bullet points but they are not appearing on my page.

My markdown is the following:

```<code>### Languages and Technologies

-  Java, SQL, C#.NET, XML, JSON, git, SVN
-  Android Studio, Visual Studio, Microsoft SQL Server, Eclipse, Microsoft Office/Visio/Sharepoint
</code>```

But it shows up like this. I'm using the end2end jekyll theme and running locally to test. I'm not sure if the particular markdown processor I'm using doesn't support bullets or what. It doesn't even work for numbered lists either, if I replace the "-" with "1." I still get the same output. Any ideas? How can I get a bulleted list? I'm thinking this might have to do with the CSS the page is using.

答: Figured it out. It looks like list-style was set to "none" in a couple of the .scss files of the project. I commented them out and lists are working now.

Body:
I'm setting up a Jekyll portfolio site and I'm working on converting my resume into markdown. I'm having an issue where I'm trying to create bullet points but they are not appearing on my page.

My markdown is the following:

### Languages and Technologies

-  Java, SQL, C#.NET, XML, JSON, git, SVN
-  Android Studio, Visual Studio, Microsoft SQL Server, Eclipse, Microsoft Office/Visio/Sharepoint

But it shows up like this. I'm using the end2end jekyll theme and running locally to test. I'm not sure if the particular markdown processor I'm using doesn't support bullets or what. It doesn't even work for numbered lists either, if I replace the "-" with "1." I still get the same output. Any ideas? How can I get a bulleted list? I'm thinking this might have to do with the CSS the page is using.


问:
Child elements invisible in Microsoft Edge when parent revealed with jQuery slideDown
We have a page which works perfectly on all of the modern browsers EXCEPT for a couple of strange behaviors on Microsoft Edge only. Here is the URL:

http://www.oru.edu/online/

Scroll down to the section below "Earn a Fully Accredited Online Degree..." and click one of the photos or one of the degree names. Expected behavior is for a "details" section to slide down and the window to scroll down to it using jQuery's "slideDown" followed by "animate". The animations work well in all tested browsers.

The details section that comes down should contain a description of the degree on the left, and four rectangular clickable areas on the right: "Program Description", "Benefits of Degree", "Occupational Outlook", and "Degree Plan". Also, the background of the details areas should contain a blurred-out version of the picture you may have clicked to open it up.

All of the jQuery animations (slideDown, slideUp, animate, etc.) work in MS Edge, but when the details area slides down, sometimes (randomly, it seems) one or more of the four clickable rectangles does not appear until you hover the mouse over it.

Also at unpredictable intervals, the background image will only show behind part of the div, with the rest of it being a solid blue color.

I've tried changing the order of the jQuery events, I've researched possible changes to the CSS, I've tried it on two completely separate Windows 10 machines, and I can't seem to find anything that causes this to change in the least.

Thanks for any solutions or ideas!

答:
I may have a solution regarding the scrolling issue in jQuery. No promises, but I did have a similar problem as yours once with an auto scrolling issue working in every browser except one. The fix was so tiny that I couldn't believe that one thing was causing such a big problem.

Without seeing your jquery code, I don't know if this the actual solution, but here goes...

Do you have a section of code in the animation portion of your jquery that looks anything like this?

```<code>$("html body").animate({
  scrollTop: $("#" + sectionID).offset().top
}
</code>```

Of course, your code may not start with that "html body" or have "scrollTop" as the exact terms, but here is the point.

There needs to be a comma in between where the "html body" section of code is. In other words, like this...

```<code>$("html, body").animate({
    scrollTop: $("#" + sectionID).offset().top
}
</code>```

As I said, your code may be pointing to different divs or elements of your website than my code example is showing, but the concept holds true.

That little comma may be what's keeping your animation from working in Edge. That is what happened to me. In a site I was building I initially didn't have the comma and it worked in EVERY browser I could throw at it, except for Edge. I spent a week on the issue!!!! Finally, I stumbled upon a forum that mentioned the comma and BAM it worked!

Give it a try and please report your results. Good luck!

Body:
I may have a solution regarding the scrolling issue in jQuery. No promises, but I did have a similar problem as yours once with an auto scrolling issue working in every browser except one. The fix was so tiny that I couldn't believe that one thing was causing such a big problem.

Without seeing your jquery code, I don't know if this the actual solution, but here goes...

Do you have a section of code in the animation portion of your jquery that looks anything like this?

$("html body").animate({
  scrollTop: $("#" + sectionID).offset().top
}

Of course, your code may not start with that "html body" or have "scrollTop" as the exact terms, but here is the point.

There needs to be a comma in between where the "html body" section of code is. In other words, like this...

$("html, body").animate({
    scrollTop: $("#" + sectionID).offset().top
}

As I said, your code may be pointing to different divs or elements of your website than my code example is showing, but the concept holds true.

That little comma may be what's keeping your animation from working in Edge. That is what happened to me. In a site I was building I initially didn't have the comma and it worked in EVERY browser I could throw at it, except for Edge. I spent a week on the issue!!!! Finally, I stumbled upon a forum that mentioned the comma and BAM it worked!

Give it a try and please report your results. Good luck!


问:
Hide comments in R markdown
Is is possible to hide some comments in code when kniting using knitr / R markdown? Example:

```<code>---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document

---

```{r}

# Generate some data

rnorm(2)

## But keep this comment

```
</code>```

When kniting I would like the first comment to disapear, but keep the second one somehow.

答:
Here is a quick example of modifying the hook to change knitr behavior.

```<code>---
title: "SOSO"
author: "SO"
date: 2017-06-06
output: pdf_document
---

```{r setup-hook, echo=FALSE}
hook_in <- function(x, options) {
    x <- x[!grepl("^#\\s+", x)]
    paste0("```r\n",
          paste0(x, collapse="\n"),
          "\n```")
}
knitr::knit_hooks$set(source = hook_in)
```

```{r}

# Generate some data
# Lines that starts with `# ` will be removed from the rendered documents

rnorm(2)

## But keep this comment
## But lines that starts with `## ` will be kept

```
</code>```

produces this

Title: Hide comments in R markdown

Body:
Is is possible to hide some comments in code when kniting using knitr / R markdown? Example:

---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document

---

```{r}

# Generate some data

rnorm(2)

## But keep this comment

```

When kniting I would like the first comment to disapear, but keep the second one somehow.

Body:
Here is a quick example of modifying the hook to change knitr behavior.

---
title: "SOSO"
author: "SO"
date: 2017-06-06
output: pdf_document
---

```{r setup-hook, echo=FALSE}
hook_in <- function(x, options) {
    x <- x[!grepl("^#\\s+", x)]
    paste0("```r\n",
          paste0(x, collapse="\n"),
          "\n```")
}
knitr::knit_hooks$set(source = hook_in)
```

```{r}

# Generate some data
# Lines that starts with `# ` will be removed from the rendered documents

rnorm(2)

## But keep this comment
## But lines that starts with `## ` will be kept

```

produces this


问:
Where should I store files for my web-app?
I'm developing a web-app to deploying to Heroku. However, even if I start the application by Tomcat, my BufferedReader can't find it, because the current directory is /home/vladyour/Programs/apache-tomcat-9.0.0.M19/bin.

Where should I store files for my web-app? And how to address to them?

Thank you!

答:
you can add your war file or upacked files under
 /home/vladyour/Programs/apache-tomcat-9.0.0.M19/webapps

and you can address them by
"address-ip":"tomcat-port"/'name-of your-app-at-webapps-dir"


问:
How to implement exponentiation of a rational number without nth root?
Its available for me only log(base "e"), sin, tan and sqrt (only square root) functions and the basic arithmetical operators (+ - * / mod). I have also the "e" constant.

I'm experimenting several problems with Deluge (zoho.com) for these restrictions. I must implement exponentiation of rational (fraction) bases and exponents.

答:
Say you want to calculate pow(A, B)

Consider the representation of B in base 2:

```<code>B = b[n]   * pow(2, n    ) +
    b[n-1] * pow(2, n - 1) +
    ...
    b[2]   * pow(2, 2    ) +
    b[1]   * pow(2, 1    ) +
    b[0]   * pow(2, 0    ) +
    b[-1]  * pow(2, -1   ) +
    b[-2]  * pow(2, -2   ) +
    ...

 = sum(b[i] * pow(2, i))
</code>```

where b[x] can be 0 or 1 and pow(2, y) is an integer power of two (i.e., 1, 2, 4, 1/2, 1/4, 1/8).

Then,

```<code>pow(A, B) = pow(A, sum(b[i] * pow(2, i)) = mul(pow(A, b[i] * pow(2, i)))
</code>```

And so pow(A, B) can be calculated using only multiplications and square root operations

Body:
Say you want to calculate pow(A, B)

Consider the representation of B in base 2:

B = b[n]   * pow(2, n    ) +
    b[n-1] * pow(2, n - 1) +
    ...
    b[2]   * pow(2, 2    ) +
    b[1]   * pow(2, 1    ) +
    b[0]   * pow(2, 0    ) +
    b[-1]  * pow(2, -1   ) +
    b[-2]  * pow(2, -2   ) +
    ...

 = sum(b[i] * pow(2, i))

where b[x] can be 0 or 1 and pow(2, y) is an integer power of two (i.e., 1, 2, 4, 1/2, 1/4, 1/8).

Then,

pow(A, B) = pow(A, sum(b[i] * pow(2, i)) = mul(pow(A, b[i] * pow(2, i)))

And so pow(A, B) can be calculated using only multiplications and square root operations


问:
Call javascript in web view on Android
I made HTML file with JavaScript functions in and Android UI to call these functions. I don't know how to call JS in web views on Android. Please help.
Example:</p>

```<code>//JavaScript
<script>
function doSomething(){
//do something
}
</script>

//Android Java
Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //call JS function doSomething()
        }
});
</code>```

答:
First load the page containing JavaScript function(s) , then load the function you want.
Example:</p>

```<code>//JavaScript

<script type="text/javascript" >

function func(){

 alert("Hello World!");

}
</script>

//Android

WebView webView = (WebView) findViewById(R.id.myWebview);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/HTML.html");

Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {

    @Override
    public void onClick(View v) {

            WebView webView = (WebView) findViewById(R.id.myWebview);
            webView.loadUrl("javascript:func();");
    }
});
</code>```

Title: Call javascript in web view on Android

Body:
I made HTML file with JavaScript functions in and Android UI to call these functions. I don't know how to call JS in web views on Android. Please help.
Example:

//JavaScript

//Android Java
Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //call JS function doSomething()
        }
});

Body:
First load the page containing JavaScript function(s) , then load the function you want.
Example:

//JavaScript

<script type="text/javascript" >

function func(){

 alert("Hello World!");

}
</script>

//Android

WebView webView = (WebView) findViewById(R.id.myWebview);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/HTML.html");

Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {

    @Override
    public void onClick(View v) {

            WebView webView = (WebView) findViewById(R.id.myWebview);
            webView.loadUrl("javascript:func();");
    }
});


问:
How to make a certain number be counted rather than the length of the actual number?
What I want to happen is if the number is over 500 for the console to print something, but right now it counts how long the number is not how high its numerical value is. </p>

```<code>print ("What Is The Current Distance  In Meters?")
distance = input ()

if len (distance) >= 500:
    (print) ("Thanks")
</code>```

答:
You need to first convert distance to a number and then use the greater than operator > so you code becomes:

```<code>print ("What Is The Current Distance  In Meters?")
distance = input ()

if int(distance) > 500 :
    print ("Thanks")
</code>```

Hope I helped!

Body:
What I want to happen is if the number is over 500 for the console to print something, but right now it counts how long the number is not how high its numerical value is.

print ("What Is The Current Distance  In Meters?")
distance = input ()

if len (distance) >= 500:
    (print) ("Thanks")

Body:
You need to first convert distance to a number and then use the greater than operator > so you code becomes:

print ("What Is The Current Distance  In Meters?")
distance = input ()

if int(distance) > 500 :
    print ("Thanks")

Hope I helped!