问:
Is it any way possible to do text shadows with current IE9 beta CSS?
So text shadows in FF and Chrome are grate. For example I have simple web page for simple video streaming server.. no shadows in IE9 for me(

my css code is like

```<code>p{color: #000;text-shadow: 0px 1px 1px #fff;padding-bottom:1em}
</code>```

so I wonder - may be there is some JS of special CSS way for creating text shadows for IE?

答: Text shadows are standard in CSS3: http://www.w3.org/Style/Examples/007/text-shadow.en.html</p>

Body:
So text shadows in FF and Chrome are grate. For example I have simple web page for simple video streaming server.. no shadows in IE9 for me(

my css code is like

p{color: #000;text-shadow: 0px 1px 1px #fff;padding-bottom:1em}

so I wonder - may be there is some JS of special CSS way for creating text shadows for IE?


来源: stackexchange

问:
MarkLogic Copy through MLCP - Errors
When I am doing bulk load from one db to another db using mlcp, I am getting below timeout errors. Any ideas

The commands to execute:

[root@mlcp bin]# sh mlcp.sh copy -mode local -input_host x.x.x.x -input_port 8000 -input_database p2a-aws-prod-00-content -copy_collections false -copy_permissions false -copy_properties false -copy_quality false -input_username admin -input_password admin -output_host x.x.x.x -output_port 8000 -output_database p2a-aws-bldstb-00-content -output_username admin -output_password admin

I see this in the logs:

17/03/31 05:49:05 INFO contentpump.LocalJobRunner:  completed 66%
  2017-03-31 05:49:16.951 SEVERE [13] (StreamingResultSequence.next): RequestException instantiating ResultItem 85129: Time limit exceeded
   com.marklogic.xcc.exceptions.XQueryException: SVC-EXTIME: Time limit exceeded
   [Session: user=admin, cb=#12474893908780766241 [ContentSource: user=admin, cb=p2a-aws-prod-00-content [provider: address=00-prod-db-02.highroads.local/10.46.13.182:8000, pool=0/64]]]
   [Client: XCC/8.0-6.3, Server: XDBC/8.0-5.1]

答:
Bit of a guess without knowing more about data sizes, and connection between the systems, but I'd expect there are a few big files in there, and it takes too long to copy them over in one transaction. Try decreasing batch_size and or transaction_size. You could also consider lowering thread_count as the threads might be competing for network bandwidth..

HTH!

ContentLicense: CC BY-SA 3.0

Title: MarkLogic Copy through MLCP - Errors


问:
Watson IoT HTTP Messaging API
Try to use the HTTP Messaging API for Watson IoT. https://docs.internetofthings.ibmcloud.com/apis/swagger/v0002/http-messaging.html

I have one application that should POST Mqtt msg from a device. Have generated API key in Watson iot and put it in the POST header e.g:

username: a-XYXYX-bvbcxgmz6d

password: XYXYX+6QY6OKw*J

Content-Type: application/json

I then send this POST to changed my real orgId in this post:
http://orgId.messaging.internetofthings.ibmcloud.com:1883/api/v0002/application/types/ecu/devices/ecu1/events/test

But I keep ending up in server response 403 Not allowed.

I use a HTTP REST Chrome application that I have successfully used before.
Have run out of ideas so pleas help!

答:
It looks good and the POST works for me.  I assume you have double checked device type/device id - that they actually exist in the platform.  Perhaps the event itself has something invalid in it messing it up.  This is what I send:

```<code>  POST /api/v0002/application/types/myType/devices/myDevice/events/test

    HTTP/1.1 Host: myOrg.messaging.internetofthings.ibmcloud.com:1883

    Authorization: Basic myAPIKeys

    Content-Type: application/json
</code>```

Body is:

```<code>{"temp":85}
</code>```

Title: Watson IoT HTTP Messaging API

Body:
It looks good and the POST works for me.  I assume you have double checked device type/device id - that they actually exist in the platform.  Perhaps the event itself has something invalid in it messing it up.  This is what I send:

  POST /api/v0002/application/types/myType/devices/myDevice/events/test

    HTTP/1.1 Host: myOrg.messaging.internetofthings.ibmcloud.com:1883

    Authorization: Basic myAPIKeys

    Content-Type: application/json

Body is:

{"temp":85}


问:
VBA identify first and last rows with data
I want first and last rows with non-blank cells.
My last row works fine, the first row is bust. Suggestions appreciated.</p>

```<code>Sub idDataRange()

Dim firstRow As Long
Dim lastRow As Long

Sheets("fileNames").Select

' this has been adapted from a Stack overflow answer. lastRow unedited
' first row I changed Up to Down = NOT the solution!
With ActiveSheet
    firstRow = .Range("B" & .Rows.Count).End(xlDown).row
    lastRow = .Range("B" & .Rows.Count).End(xlUp).row
    End With

    MsgBox "the first row is " & firstRow
    MsgBox "last row is " & lastRow

End Sub
</code>```

答:
This line works by starting at the bottom of the B column and then working up:

```<code>lastRow = .Range("B" & .Rows.Count).End(xlUp).row
</code>```

To find the first row, you need to start at the top of the sheet and then work down instead, but also checking that the first row doesn't have anything:

```<code>firstRow = iif(isempty(.Range("B1")),.Range("B1").End(xlDown).row,1)
</code>```

Note that the formula for lastRow assumes that there is no data in the very last cells of column B. Also, my formula for firstRow assumes there is at least one cell in column B with a value.

Body:
I want first and last rows with non-blank cells.
My last row works fine, the first row is bust. Suggestions appreciated.

Sub idDataRange()

Dim firstRow As Long
Dim lastRow As Long

Sheets("fileNames").Select

' this has been adapted from a Stack overflow answer. lastRow unedited
' first row I changed Up to Down = NOT the solution!
With ActiveSheet
    firstRow = .Range("B" & .Rows.Count).End(xlDown).row
    lastRow = .Range("B" & .Rows.Count).End(xlUp).row
    End With

    MsgBox "the first row is " & firstRow
    MsgBox "last row is " & lastRow

End Sub

Body:
This line works by starting at the bottom of the B column and then working up:

lastRow = .Range("B" & .Rows.Count).End(xlUp).row

To find the first row, you need to start at the top of the sheet and then work down instead, but also checking that the first row doesn't have anything:

firstRow = iif(isempty(.Range("B1")),.Range("B1").End(xlDown).row,1)

Note that the formula for lastRow assumes that there is no data in the very last cells of column B. Also, my formula for firstRow assumes there is at least one cell in column B with a value.


问:
Removing lead zeroes from an array
I seem to be having issues removing leading zeroes from an array that is created by the user. For example, the program I am writing will ask the user to input a mathematical expression (input received as a string):

Eg : 1234 + 1234

Before going into creating a function to solve this problem, I can't seem to get my array to ignore the leading zeroes. This is because I am switching the user input from string to integer and then positioning these values at the end of the array (constant size is 20). Below is how I convert from string to an integer array.

```<code>void stringToInt(int arr[], string value1, int SIZE){
    for (int i = 0; i < SIZE; i++){
         if (arr[i] < 0)
             arr[i] = 0;
         arr[SIZE - 1 - i] = value1[value1.length() - 1 - i] - 48;
}
</code>```

This is how I tried to remove zeroes:

```<code>void removeLeadZeroes(int arr[], string value1, int SIZE){
    bool print = true;
    int carry = 0;
    for (int i = 0; i < (SIZE - 1); i++){
        if (arr[i] == 0
            print = false;
        if (print)
            cout << arr[i];
    }
}
</code>```

答:
Another simple approach using C. arr2 contains the array without leading zeros. 48 being the ASCII value for 0 can be used to check for zeros in the given array. However I recommend to use built-in atoi as suggested by @Ronald.

```<code>#include<stdio.h>

int main(){

        const char *arr1 = "01234+123";
        char *arr2 = (char *)malloc(20);
        int i,j=0;

        for(i=0; arr1[i] != '\0'; i++){
                if((arr1[i] - 48) != 0){
                        arr2[++j] = arr1[i];
                }
        }
return 0;

}
</code>```

Title: Removing lead zeroes from an array

Body:
I seem to be having issues removing leading zeroes from an array that is created by the user. For example, the program I am writing will ask the user to input a mathematical expression (input received as a string):

Eg : 1234 + 1234

Before going into creating a function to solve this problem, I can't seem to get my array to ignore the leading zeroes. This is because I am switching the user input from string to integer and then positioning these values at the end of the array (constant size is 20). Below is how I convert from string to an integer array.

void stringToInt(int arr[], string value1, int SIZE){
    for (int i = 0; i < SIZE; i++){
         if (arr[i] < 0)
             arr[i] = 0;
         arr[SIZE - 1 - i] = value1[value1.length() - 1 - i] - 48;
}

This is how I tried to remove zeroes:

void removeLeadZeroes(int arr[], string value1, int SIZE){
    bool print = true;
    int carry = 0;
    for (int i = 0; i < (SIZE - 1); i++){
        if (arr[i] == 0
            print = false;
        if (print)
            cout << arr[i];
    }
}

Body:
Another simple approach using C. arr2 contains the array without leading zeros. 48 being the ASCII value for 0 can be used to check for zeros in the given array. However I recommend to use built-in atoi as suggested by @Ronald.

#include<stdio.h>

int main(){

        const char *arr1 = "01234+123";
        char *arr2 = (char *)malloc(20);
        int i,j=0;

        for(i=0; arr1[i] != '\0'; i++){
                if((arr1[i] - 48) != 0){
                        arr2[++j] = arr1[i];
                }
        }
return 0;

}


问:
Can CNNs be faster than classic descriptors?
Disclamer: I don't know almost nothing on CNNs and I have no idea where I could ask this.

My research is focused on high performance on computer vision applications. We generate codes representing an image in less than 20 ms on images with the largest size of 500pxs.

This is done by combining SURF descriptors and VLAD codes, obtaining a vector representing an image that will be used in our object recognition application.

Can CNNs be faster? According to this benchmark (which is based on much smaller images) the times needed is longer, almost double considering that the size of the image is half of ours.

答:
Answer to your question: Yes, they can. They can be slower and they can be faster than classic descriptors. For example, using only a single filter and several max-poolings will almost certainly be faster. But the results will also certainly be crappy.

You should ask a much more specific question. Relevant parts are:

Problem: Classification / Detection / Semantic Segmentation / Instance Segmentation / Face verification / ... ?

Constraints: Minimum accuracy / maximum speed / maximum latency?

Evaluation specifics:

Which hardware is available (GPUs)?

Do you evaluate on a single image? Often you can evaluate up to 512 images in about the same time as one image.

Also: The input image size should not be relevant. If CNNs achieve better results on smaller inputs than classic descriptors, why should you care?

Papers

Please note that CNNs are usually not tweaked towards speed, but towards accuracy.

Detection: Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks: 600px x ~800px in 200ms on a GPU

InverseFaceNet: Deep Single-Shot Inverse Face Rendering From A Single Image: 9.79ms with GeForce GTX Titan and AlexNet to get FC7 features

Semantic segmentation: Pixel-wise Segmentation of Street with Neural
Networks 20ms with GeForce GTX 980


问:
Powershell script in VSTS Build Definition not updating AssemblyVersion.cs
I have a Project hosted in VSTS and I'm experimenting with the Build Definitions. I'm trying to execute a powershell script that updates the AssemblyVersion.cs before the Project is built. When I run the script locally it works fine, but when it's ran during the Build process, the script runs without error, but the AssemblyVersion.cs is not updated.

```<code>$regex = '\[assembly: AssemblyVersion\("(.*)"\)\]'
$assemblyInfoPath = "..\Properties\AssemblyInfo.cs"

(Get-Content $assemblyInfoPath) | ForEach-Object {
    if($_ -match $regex)
    {
        # Get current version, and update revision number
        $version = [version]$matches[1]
        $newVersion = "{0}.{1}.{2}.{3}" -f $version.Major, $version.Minor, $version.Build, ($version.Revision + 1)
        '[assembly: AssemblyVersion("{0}")]' -f $newVersion

        Write-Host "Version updated to: $newVersion"
    }
    else
    {
        $_
    }
} | Set-Content $assemblyInfoPath
</code>```

The Build output states that the version has been updated, but when I view AssemblyInfo.cs in the File Viewer it shows the old version.

答:
You need to checkin or push changes to remote repository.

If you are using TFVC, there is TFVC Build Tasks extension that includes TFVC-Check-in Changes step/task that can check in changes.

If you are using Git, you can add these steps/tasks to push changes:

Command Line (Tool: git; Arguments: add **\*.*; Working folder: $(build.sourcesdirectory))

Command Line (Tool: git; Arguments: commit -m "update"; Working folder: $(build.sourcesdirectory))

Command Line (Tool: git; Arguments: push origin HEAD:$(Build.SourceBranchName); Working folder: $(build.sourcesdirectory))

On the other hand, you also could build a custom build/release task and use it in your build/release. More information about custom build/release task, you can refer to: Add a build task

Note: It is not recommended to checkin/push changes to the remote repository in build or release.

Body:
I have a Project hosted in VSTS and I'm experimenting with the Build Definitions. I'm trying to execute a powershell script that updates the AssemblyVersion.cs before the Project is built. When I run the script locally it works fine, but when it's ran during the Build process, the script runs without error, but the AssemblyVersion.cs is not updated.

$regex = '\[assembly: AssemblyVersion\("(.*)"\)\]'
$assemblyInfoPath = "..\Properties\AssemblyInfo.cs"

(Get-Content $assemblyInfoPath) | ForEach-Object {
    if($_ -match $regex)
    {
        # Get current version, and update revision number
        $version = [version]$matches[1]
        $newVersion = "{0}.{1}.{2}.{3}" -f $version.Major, $version.Minor, $version.Build, ($version.Revision + 1)
        '[assembly: AssemblyVersion("{0}")]' -f $newVersion

        Write-Host "Version updated to: $newVersion"
    }
    else
    {
        $_
    }
} | Set-Content $assemblyInfoPath

The Build output states that the version has been updated, but when I view AssemblyInfo.cs in the File Viewer it shows the old version.


问:
C# Do I need TRY/CATCH in order to throw?
If all I want to do is throw the exception up a level when it occurs?

```<code>private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}
</code>```

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

答: If all you do is rethrow the exception you don't need the try/catch block. Generally you should only catch exceptions when you can handle them. Otherwise let them propagate upwards. </p>

OwnerDisplayName: Petrolios

LastEditorDisplayName: Jon Skeet

ContentLicense: CC BY-SA 2.5

Body:
If all I want to do is throw the exception up a level when it occurs?

private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

OwnerDisplayName: Brian Rasmussen


问:
How to identify an anonymous function
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

```<code> public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}
</code>```

I need some way to identify

```<code>   p => { fake.Test(p); counter++; }
</code>```

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

答:
There is no way to reliably determine whether a function is "anonymous" because all functions have names to the CLR. It's only anonymous within the language that generates it, and that's compiler-dependent. You may be able to determine the algorithm used by Microsoft's current C# compiler, only to have it stop working on C# 5 or Mono.

Since you want to prevent users of your type from writing code that uses it wrong, you just need to throw an exception at some point that will make their program crash. What I would do is throw the exception in the Remove function when the target delegate isn't found. At that point your users will still get a crash and the only way to fix it is to write the delegate in some way that it's removable.

As an added bonus, you will catch bugs where somebody tries to remove delegates twice or that were never added in the first place. The code would look like this:

```<code>public bool Remove(Action<int> del)
{
    if (m_Container.Contains(del))
    {
        m_Container.Remove(del);
        return true;
    }

    throw new ArgumentException("Attempt to remove nonexistent delegate");
}
</code>```

Title: How to identify an anonymous function

Body:
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

 public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}

I need some way to identify

   p => { fake.Test(p); counter++; }

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

Body:
There is no way to reliably determine whether a function is "anonymous" because all functions have names to the CLR. It's only anonymous within the language that generates it, and that's compiler-dependent. You may be able to determine the algorithm used by Microsoft's current C# compiler, only to have it stop working on C# 5 or Mono.

Since you want to prevent users of your type from writing code that uses it wrong, you just need to throw an exception at some point that will make their program crash. What I would do is throw the exception in the Remove function when the target delegate isn't found. At that point your users will still get a crash and the only way to fix it is to write the delegate in some way that it's removable.

As an added bonus, you will catch bugs where somebody tries to remove delegates twice or that were never added in the first place. The code would look like this:

public bool Remove(Action<int> del)
{
    if (m_Container.Contains(del))
    {
        m_Container.Remove(del);
        return true;
    }

    throw new ArgumentException("Attempt to remove nonexistent delegate");
}


问:
gallery style layout with css flex-box?
How can I do this sort of a gallery style layout with flex box?

I have a
 with
 in them. The first
 I want to be double size and have the rest of the items flow around it.

I can layout the items using flexbox with the following code, but when I go double size on the first item I can't figure out how to reflow the boxes to fit around it as pictured.

```<code>ul, li {
    padding: 0;
    margin: 0;
}

ul {
    display: flex;
    justify-content: flex-start;
    list-style-type: none;
    align-items: flex-start;
    flex-wrap: wrap;
    flex-direction: row;
}

ul > li {
    width: 15rem;
    height: 15rem;
    order: 2;
}

ul > li.active {
    width: 30rem;
    height: 30rem;
    order: 1;
}
</code>```

I have some javascript that cycles through the
 tags and adds the .active class. Using order: 1 I can move the currently active image to the first spot (the double-sized version).

答:
I don' really know about flex, but you can do this with 'float'

```<code>ul, li {
    padding: 0;
    margin: 0;
}

ul {
}

ul > li {
    width: 50px;
    height: 50px;
    background-color: black;
    margin-right: 5px;
    margin-bottom: 5px;
    float: left
}

ul li:nth-child(1) {
    width: calc( 50px * 2 + 5px);
    height: calc( 50px * 2 + 5px);
}
</code>```

https://jsfiddle.net/vcqp8an6/

Title: gallery style layout with css flex-box?

Body:
How can I do this sort of a gallery style layout with flex box?

I have a
 with
 in them. The first
 I want to be double size and have the rest of the items flow around it.

I can layout the items using flexbox with the following code, but when I go double size on the first item I can't figure out how to reflow the boxes to fit around it as pictured.

ul, li {
    padding: 0;
    margin: 0;
}

ul {
    display: flex;
    justify-content: flex-start;
    list-style-type: none;
    align-items: flex-start;
    flex-wrap: wrap;
    flex-direction: row;
}

ul > li {
    width: 15rem;
    height: 15rem;
    order: 2;
}

ul > li.active {
    width: 30rem;
    height: 30rem;
    order: 1;
}

I have some javascript that cycles through the
 tags and adds the .active class. Using order: 1 I can move the currently active image to the first spot (the double-sized version).

Body:
I don' really know about flex, but you can do this with 'float'

ul, li {
    padding: 0;
    margin: 0;
}

ul {
}

ul > li {
    width: 50px;
    height: 50px;
    background-color: black;
    margin-right: 5px;
    margin-bottom: 5px;
    float: left
}

ul li:nth-child(1) {
    width: calc( 50px * 2 + 5px);
    height: calc( 50px * 2 + 5px);
}

https://jsfiddle.net/vcqp8an6/


问:
Should I make different layout (xml files) for different android mobiles
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

```<code>res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
</code>```

This is my layout xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>
</code>```

Manifest file:

```<code><supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>
</code>```

but it does not work on 4 inch screen.

答:
This should be helpful : https://developer.android.com/guide/practices/screens_support.html

Anyway I think that you should use max 2 layouts xmls (1 for horizontal view, 1 for vertical view) for activity.

Body:
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

This is my layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>

Manifest file:

<supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>

but it does not work on 4 inch screen.


问:
Is it secure to use url.parse to check redirectURL to be only within domain?
I need to make secure redirects only within common domain example.local. So for example the following are valid: http://blog.example.local, http://www.example.local/dashboardwhereas the following are not: http://blog.example.local http://blog.example.local.fake.com

```<code>var url = require('url');

app.post('/login', function (req, res, next) {
    var redirect = req.query.redirect,
        targetUrl = url.parse(redirect);

   if (targetUrl.host !== 'example.local') {
      return next(new Error('Open redirect attack detected'));
   }

   return res.redirect(redirect);
});
</code>```

Is it secure enough to use in production or should I fix something?

答:
Following is the whole code to prevent Open Redirection attack issue, It will check your URL and validate that it is under same domain or not.

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script>
               function LaunchHelp() {
            try {

                var surl = "http://www.google.com";
                if (validateURL(surl))
                    window.open(surl, '_blank', 'toolbar=no,menubar=no,status=yes');
                else {
                    throw new InvalidURLException();
                }
            } catch (e) {
                if (e instanceof InvalidURLException)
                    alert(e.message);
            }
        }

        function InvalidURLException() {
            this.message = "An attempt was made to open a webpage of foreign domain. No allowed.";
            this.toString = function () {
                return this.message
            };
        }

        function validateURL(surl) {
            var url = parseURL(surl);
            var urlHostname = url.hostname.trim();

            if (urlHostname == '') {
                return true;
            }
            else {
                if (urlHostname.toUpperCase() == location.hostname.trim().toUpperCase()) {
                    return true;
                }
                else
                    return false;
            }
        }

        function parseURL(url) {
            var a = document.createElement('a');
            a.href = url;
            return {
                source: url,
                protocol: a.protocol.replace(':', ''),
                hostname: a.hostname,
                host: a.host,
                port: a.port,
                query: a.search,
                params: (function () {
                    var ret = {},
                        seg = a.search.replace(/^\?/, '').split('&'),
                        len = seg.length, i = 0, s;
                    for (; i < len; i++) {
                        if (!seg[i]) { continue; }
                        s = seg[i].split('=');
                        ret[s[0]] = s[1];
                    }
                    return ret;
                })(),
                file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
                hash: a.hash.replace('#', ''),
                path: a.pathname.replace(/^([^\/])/, '/$1'),
                relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
                segments: a.pathname.replace(/^\//, '').split('/')
            };
        }

    </script>
</head>
<body>
    <h1>This is Test 1 Page.</h1>
    <button id="btnRedirect" name="btnRedirect" onclick="LaunchHelp()">Redirect</button>
</body>
</html>
</code>```

You can just replace your url in place of this line of code.

```<code>var surl = "http://www.google.com";
</code>```

Hope this will help you.
thanks

Body:
I need to make secure redirects only within common domain example.local. So for example the following are valid: http://blog.example.local, http://www.example.local/dashboardwhereas the following are not: http://blog.example.local http://blog.example.local.fake.com

var url = require('url');

app.post('/login', function (req, res, next) {
    var redirect = req.query.redirect,
        targetUrl = url.parse(redirect);

   if (targetUrl.host !== 'example.local') {
      return next(new Error('Open redirect attack detected'));
   }

   return res.redirect(redirect);
});

Is it secure enough to use in production or should I fix something?

Body:
Following is the whole code to prevent Open Redirection attack issue, It will check your URL and validate that it is under same domain or not.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script>
               function LaunchHelp() {
            try {

                var surl = "http://www.google.com";
                if (validateURL(surl))
                    window.open(surl, '_blank', 'toolbar=no,menubar=no,status=yes');
                else {
                    throw new InvalidURLException();
                }
            } catch (e) {
                if (e instanceof InvalidURLException)
                    alert(e.message);
            }
        }

        function InvalidURLException() {
            this.message = "An attempt was made to open a webpage of foreign domain. No allowed.";
            this.toString = function () {
                return this.message
            };
        }

        function validateURL(surl) {
            var url = parseURL(surl);
            var urlHostname = url.hostname.trim();

            if (urlHostname == '') {
                return true;
            }
            else {
                if (urlHostname.toUpperCase() == location.hostname.trim().toUpperCase()) {
                    return true;
                }
                else
                    return false;
            }
        }

        function parseURL(url) {
            var a = document.createElement('a');
            a.href = url;
            return {
                source: url,
                protocol: a.protocol.replace(':', ''),
                hostname: a.hostname,
                host: a.host,
                port: a.port,
                query: a.search,
                params: (function () {
                    var ret = {},
                        seg = a.search.replace(/^\?/, '').split('&'),
                        len = seg.length, i = 0, s;
                    for (; i < len; i++) {
                        if (!seg[i]) { continue; }
                        s = seg[i].split('=');
                        ret[s[0]] = s[1];
                    }
                    return ret;
                })(),
                file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
                hash: a.hash.replace('#', ''),
                path: a.pathname.replace(/^([^\/])/, '/$1'),
                relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
                segments: a.pathname.replace(/^\//, '').split('/')
            };
        }

    </script>
</head>
<body>
    <h1>This is Test 1 Page.</h1>
    <button id="btnRedirect" name="btnRedirect" onclick="LaunchHelp()">Redirect</button>
</body>
</html>

You can just replace your url in place of this line of code.

var surl = "http://www.google.com";

Hope this will help you.
thanks


问:
Work out the type of c# application a class contained in a DLL is being used by
Is there any way to know in C# the type of application that is running.

Windows Service
ASP.NET
Windows Form
Console

I would like to react to the application type but cannot find a way to determine it.

答:
To check for a Forms, WPF, WCF or Console application:

```<code>if (System.Windows.Forms.Application.OpenForms.Count > 0)
{
    return ApplicationType.WindowsForms;
}

if (System.Windows.Application.Current != null)
{
    return ApplicationType.Wpf;
}

if (System.ServiceModel.OperationContext.Current != null)
{
    return ApplicationType.Wcf;
}

try
{
    int windowHeight = Console.WindowHeight; // an exception could occur
    return ApplicationType.Console;
}
catch (IOException)
{
}

return ApplicationType.Unknown;
</code>```

OwnerDisplayName: John Selkirk

Body:
To check for a Forms, WPF, WCF or Console application:

if (System.Windows.Forms.Application.OpenForms.Count > 0)
{
    return ApplicationType.WindowsForms;
}

if (System.Windows.Application.Current != null)
{
    return ApplicationType.Wpf;
}

if (System.ServiceModel.OperationContext.Current != null)
{
    return ApplicationType.Wcf;
}

try
{
    int windowHeight = Console.WindowHeight; // an exception could occur
    return ApplicationType.Console;
}
catch (IOException)
{
}

return ApplicationType.Unknown;


问:
Underscore.js - Looping through Object Array
I have the following object array:

```<code>var products = [
    {
        id: 1,
        name: "Product 1",
        subTypes: [
            {
                id: 1,
                name: "Product 1 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 1 - Sub Type 2"
            }
        ]
    },
    {
        id: 2,
        name: "Product 2",
        subTypes: [
            {
                id: 1,
                name: "Product 2 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 2 - Sub Type 2"
            }
        ]
    }
];
</code>```

Using underscore.js why does the following dot notation not log anything to console:

```<code>_.each(products.subTypes, function(subType) {
       console.log(subType.name);
 });
</code>```

I can only get it to work by doing nesting the foreach loops as follows?

```<code>_.each(products, function (product) {
    _.each(product.subTypes, function (subType) {
        console.log(subType.name);
    });
});
</code>```

答:
You can check it</p>

```<code>console.log('Subtypes:', products.subTypes.name);
</code>```

Body:
I have the following object array:

var products = [
    {
        id: 1,
        name: "Product 1",
        subTypes: [
            {
                id: 1,
                name: "Product 1 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 1 - Sub Type 2"
            }
        ]
    },
    {
        id: 2,
        name: "Product 2",
        subTypes: [
            {
                id: 1,
                name: "Product 2 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 2 - Sub Type 2"
            }
        ]
    }
];

Using underscore.js why does the following dot notation not log anything to console:

_.each(products.subTypes, function(subType) {
       console.log(subType.name);
 });

I can only get it to work by doing nesting the foreach loops as follows?

_.each(products, function (product) {
    _.each(product.subTypes, function (subType) {
        console.log(subType.name);
    });
});

Body:
You can check it

console.log('Subtypes:', products.subTypes.name);


问:
How to know if a point belongs more or less to a circle?
I know the formula to know if a point is inside, outside and on a circle : https://math.stackexchange.com/q/198769 This quote explains that we must compare d to r (please read the quote, it's only 5 lines).

But I just want to know if a point is ON a circle. Moreover, and that's the real problem : if a point is a bit inside/outside a circle, I want to consider it as ON the circle.

How could I do that ? I tried to delimit d-r (ie. : the comparison) in a range. Example :

if(d-r > -100 && d-r < 100) { point is on the circle }

It works, with -100 and 100, for circles with a little radius (ie. : ALL the points that are a bit outside/inside the circle are considered as being on the circle).

But for circles for a big radius, only SOME points are considered as being on the circle (ie. : only some of the points that are a bit outside/inside the circle are considered as being on the circle)...

So I would want that ALL the points that are a bit outside/inside the circle are considered as being on the circle, independently of the circle's radius. How ?

答:
From a probabilistic perspective, you could define a sort of distance map (as proposed by @Mbo) adopting the relative distance and use it to build a probability distribution on each point. The probability would represent a sort of likelihood of the point to belong to the circle. Intuitively, the closer the point, the more likely it is to be part of the circle. For example:</p>

```<code>rel_d = (d-r)/r;

//  P(x on the circle) = 1 - rel_d
if(rel_d < 1){
     P_on_circle = 1 - rel_d;
}else{
     P_on_circle = 0;
}
</code>```

Body:
From a probabilistic perspective, you could define a sort of distance map (as proposed by @Mbo) adopting the relative distance and use it to build a probability distribution on each point. The probability would represent a sort of likelihood of the point to belong to the circle. Intuitively, the closer the point, the more likely it is to be part of the circle. For example:

rel_d = (d-r)/r;

//  P(x on the circle) = 1 - rel_d
if(rel_d < 1){
     P_on_circle = 1 - rel_d;
}else{
     P_on_circle = 0;
}


问:
Branching in Mercurial
I have starting using Mercurial for my (our) versioning needs. I have now come to the point that I need to create a feature branch. However, now that I have started working on it -- and I try to push my changes, I keep getting a warning about new remote heads. That's stupid, I know that there will be new remote head(s) that's what a branch after all is?

How am I supposed to create branches and push them without this problem, without using force push as it is surely not the right way to go, right?

I thought about using separate repositories, but that feels just stupid especially for feature branches.

Any help welcome!

答:
This tutorial by Joel Spolsky helped me a bunch when I just started out with mercurial. It might be helpful for you as well:

http://hginit.com/

Title: Branching in Mercurial


问:
No module named 'info' on fresh Python 3 installation
I did a fresh python3 installation on OSX via homebrew:

```<code>brew install python3
</code>```

Then I created a virtual environment for my project and installed scipy and scikits.samplerate:

```<code>virtualenv -p /usr/local/bin/python3 pythen_env
pip install scipy
pip install scikits.samplerate
</code>```

However, when I try to import a function from scikits.samplerate, I get the following error:

```<code>>>> from scikits.samplerate import resample
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/__init__.py", line 4, in <module>
    from info import __doc__
ModuleNotFoundError: No module named 'info'
</code>```

Info happens to be the first module from the package itself that is imported in __init__.py.

Strangely, the module info.py exists in /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/:

```<code>ls /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/
__init__.py    setup.py        tests        __pycache__
info.py        setuphelp.py    version.py
</code>```

The error also happens when I try the same without virtualenv, as well as for other packages. How could I start to debug this issue?

答:
the git version does support py3

https://github.com/cournape/samplerate

(merged the PR from @gregorias)

I should find the time and procedure to update pypi too...

Body:
I did a fresh python3 installation on OSX via homebrew:

brew install python3

Then I created a virtual environment for my project and installed scipy and scikits.samplerate:

virtualenv -p /usr/local/bin/python3 pythen_env
pip install scipy
pip install scikits.samplerate

However, when I try to import a function from scikits.samplerate, I get the following error:

>>> from scikits.samplerate import resample
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/__init__.py", line 4, in <module>
    from info import __doc__
ModuleNotFoundError: No module named 'info'

Info happens to be the first module from the package itself that is imported in __init__.py.

Strangely, the module info.py exists in /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/:

ls /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/
__init__.py    setup.py        tests        __pycache__
info.py        setuphelp.py    version.py

The error also happens when I try the same without virtualenv, as well as for other packages. How could I start to debug this issue?


问:
How to get line count of a large file cheaply in Python?
How do I get a line count of a large file in the most memory- and time-efficient manner?</p>
```<code>def file_len(filename):
    with open(filename) as f:
        for i, _ in enumerate(f):
            pass
    return i + 1
</code>```

答:
A one-line bash solution similar to this answer, using the modern subprocess.check_output function:

```<code>def line_count(filename):
    return int(subprocess.check_output(['wc', '-l', filename]).split()[0])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I get a line count of a large file in the most memory- and time-efficient manner?

def file_len(filename):
    with open(filename) as f:
        for i, _ in enumerate(f):
            pass
    return i + 1

Body:
A one-line bash solution similar to this answer, using the modern subprocess.check_output function:

def line_count(filename):
    return int(subprocess.check_output(['wc', '-l', filename]).split()[0])


问:
QueryParams Not Working With Angular2 Router v 3.4.10
With Router V 3.0.0 I can do this

```<code>this.router.routerState.snapshot.root.queryParams["someParameter"];
</code>```

Bu I can't achieve the same with Router V 3.4.10.

Any ideas?

答:
Write in constructor of the component

constructor(private router: Router,
        private route: ActivatedRoute
    ) {
        this.route.queryParams.forEach((params: Params) => {
            let someParameter = params['someParameter'];
             console.log(someParameter);
        });
    }

Body:
With Router V 3.0.0 I can do this

this.router.routerState.snapshot.root.queryParams["someParameter"];

Bu I can't achieve the same with Router V 3.4.10.

Any ideas?


问:
Failed to load Info.plist from bundle
Cannot run app. Failed to load Info.plist from bundle error occurs.
When I CMD+K clean the project, it runs fine. But I have to clean the project every time I make changes and run the app.

Following is the screenshot of my podfile:

答:
This error occurs due to 'RealmSwift'. When you try to write in realm in certain directory, this error occurs, due to the conflicts in overwriting with realm.

You may want to Reset Content & Settings in simulator and also try cleaning your build folder in Xcode using Cmd+Shift+Option+K

Title: Failed to load Info.plist from bundle


问:
How to scroll collectionview horizontal?
I'm using camera and gallery to take image and add it to collection view, i want to add image to collection view to horizontal direction only so i add image to array and change collection frame to increase collection view width increase, but collection is not scroll to horizontal as i increase height of it, so what is way to do it?

Here is my code :

```<code>UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[arrayPictures addObject:image];
_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, arrayPictures.count*76, 76);
[_collPic reloadData];
</code>```

答:
try this line of code in view did load

```<code>[yourCollectionView setScrollDirection:UICollectionViewScrollDirectionVertical];
</code>```

Body:
I'm using camera and gallery to take image and add it to collection view, i want to add image to collection view to horizontal direction only so i add image to array and change collection frame to increase collection view width increase, but collection is not scroll to horizontal as i increase height of it, so what is way to do it?

Here is my code :

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[arrayPictures addObject:image];
_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, arrayPictures.count*76, 76);
[_collPic reloadData];

Body:
try this line of code in view did load

[yourCollectionView setScrollDirection:UICollectionViewScrollDirectionVertical];


问:
Nearest match merge on two columns (pandas)
Similar to one of my previous questions (Merge dataframes on nearest datetime / timestamp), I would like to merge two pandas data frames on two datetime columns using nearest match:

Let A and B be two dataframes as follows:

```<code>A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "init_date":["01/01/2015","07/02/2014","08/02/1999","01/01/1991","06/22/2014"], "fin_date":["04/16/1923","09/24/1945","06/24/1952","11/26/1988","10/05/1990"]})

 In [15]: A
Out[15]:
  ID    fin_date   init_date
0  A  04/16/1923  01/01/2015
1  A  09/24/1945  07/02/2014
2  C  06/24/1952  08/02/1999
3  B  11/26/1988  01/01/1991
4  B  10/05/1990  06/22/2014

B = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["02/15/2015","06/30/2014","07/02/1999","10/05/1990","06/24/2014"],"fin_date":["12/10/1926","01/01/1944","08/21/1955","12/12/1987","11/05/1991"], "value": ["3","5","1","7","8"] })

 In [11]: B
Out[11]:
  ID        date    fin_date value
0  A  02/15/2015  12/10/1926     3
1  A  06/30/2014  01/01/1944     5
2  C  07/02/1999  08/21/1955     1
3  B  10/05/1990  12/12/1987     7
4  B  06/24/2014  11/05/1991     8
</code>```

The resulting data frame should look like the following:

```<code>In [21]: C
Out[21]:
  ID    fin_date   init_date value
0  A  04/16/1923  01/01/2015     3
1  A  09/24/1945  07/02/2014     5
2  C  06/24/1952  08/02/1999     1
3  B  11/26/1988  01/01/1991     7
4  B  10/05/1990  06/22/2014     8
</code>```

The general problem would potentially not have a close match for neither init_date nor fin_date, however, I would also be interested in a solution when there are exact matches for init_date, for example.

Note that one difficulty is that one match might be closer to the value in init_date than on final date, while a competing match might be the opposite. In that case, I prefer the one that is closer to init_date. To my knowledge, after attempting a similar approach as the one in the link, I get that reindexing by "nearest" is not implemented for multi-indexing.

Thank you and I appreciate your help,

Body:
Similar to one of my previous questions (Merge dataframes on nearest datetime / timestamp), I would like to merge two pandas data frames on two datetime columns using nearest match:

Let A and B be two dataframes as follows:

A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "init_date":["01/01/2015","07/02/2014","08/02/1999","01/01/1991","06/22/2014"], "fin_date":["04/16/1923","09/24/1945","06/24/1952","11/26/1988","10/05/1990"]})

 In [15]: A
Out[15]:
  ID    fin_date   init_date
0  A  04/16/1923  01/01/2015
1  A  09/24/1945  07/02/2014
2  C  06/24/1952  08/02/1999
3  B  11/26/1988  01/01/1991
4  B  10/05/1990  06/22/2014

B = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["02/15/2015","06/30/2014","07/02/1999","10/05/1990","06/24/2014"],"fin_date":["12/10/1926","01/01/1944","08/21/1955","12/12/1987","11/05/1991"], "value": ["3","5","1","7","8"] })

 In [11]: B
Out[11]:
  ID        date    fin_date value
0  A  02/15/2015  12/10/1926     3
1  A  06/30/2014  01/01/1944     5
2  C  07/02/1999  08/21/1955     1
3  B  10/05/1990  12/12/1987     7
4  B  06/24/2014  11/05/1991     8

The resulting data frame should look like the following:

In [21]: C
Out[21]:
  ID    fin_date   init_date value
0  A  04/16/1923  01/01/2015     3
1  A  09/24/1945  07/02/2014     5
2  C  06/24/1952  08/02/1999     1
3  B  11/26/1988  01/01/1991     7
4  B  10/05/1990  06/22/2014     8

The general problem would potentially not have a close match for neither init_date nor fin_date, however, I would also be interested in a solution when there are exact matches for init_date, for example.

Note that one difficulty is that one match might be closer to the value in init_date than on final date, while a competing match might be the opposite. In that case, I prefer the one that is closer to init_date. To my knowledge, after attempting a similar approach as the one in the link, I get that reindexing by "nearest" is not implemented for multi-indexing.

Thank you and I appreciate your help,

Body: pd.merge(A,B['value'],on=['ID','fin_date'],how='left')


问:
How do I make a command line program using click in python that takes separates command parameters that run different scripts?
I have the following code:

```<code>import click

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)
</code>```

At the command line I want to be able to do something like the following:

```<code>python clicktest.py cli initdb
</code>```

and have the following happen echo at the terminal:

```<code>Initialized the database
</code>```

Or to enter into the terminal:

```<code>python clicktest.py cli dropdb
</code>```

and have the following happen on the terminal:

```<code>Dropped the database
</code>```

My problem is currently when I do this at the terminal:

```<code> python clicktest.py cli initdb
</code>```

Nothing happens at the terminal, nothing prints when I think something should, namely the 'Initialized Database' echo. What am i doing wrong??

答:
First, you should use it in command line like:

```<code>python clicktest.py initdb
python clicktest.py dropdb
</code>```

And in your clicktest.py file, place these lines at the bottom of your code:

```<code>if __name__ == '__main__':
    cli()
</code>```

Unless, your code won't get work.

EDIT:

If you really want to use it in a way python clicktest.py cli initdb, then you have another choice:

```<code>@click.group()
def main():
    pass

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)
main.add_command(cli)

if __name__ == '__main__':
    main()
</code>```

Or even better (Using decorators instead):

```<code>@click.group()
def main():
    pass

@main.group()
def cli():
    pass

@cli.command()
def initdb():
    click.echo('Initialized the database')

@cli.command()
def dropdb():
    click.echo('Dropped the database')

if __name__ == '__main__':
    main()
</code>```

Body:
I have the following code:

import click

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)

At the command line I want to be able to do something like the following:

python clicktest.py cli initdb

and have the following happen echo at the terminal:

Initialized the database

Or to enter into the terminal:

python clicktest.py cli dropdb

and have the following happen on the terminal:

Dropped the database

My problem is currently when I do this at the terminal:

 python clicktest.py cli initdb

Nothing happens at the terminal, nothing prints when I think something should, namely the 'Initialized Database' echo. What am i doing wrong??

Body:
First, you should use it in command line like:

python clicktest.py initdb
python clicktest.py dropdb

And in your clicktest.py file, place these lines at the bottom of your code:

if __name__ == '__main__':
    cli()

Unless, your code won't get work.

EDIT:

If you really want to use it in a way python clicktest.py cli initdb, then you have another choice:

@click.group()
def main():
    pass

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)
main.add_command(cli)

if __name__ == '__main__':
    main()

Or even better (Using decorators instead):

@click.group()
def main():
    pass

@main.group()
def cli():
    pass

@cli.command()
def initdb():
    click.echo('Initialized the database')

@cli.command()
def dropdb():
    click.echo('Dropped the database')

if __name__ == '__main__':
    main()


问:
Check if the string contains all the characters from a to z
I have to write a C# code to check if a string contains all the alphabets from a to z ."this is a test" (without quotes). It doesn't contain all alphabets from a to z so the  output is no.
 "abcdefghijklmnopqrstuvwxyz". It contains all alphabets from a to z so the  output is yes.</p>

答:
You can use an extension method like this</p>

```<code>public static class StringExtensions
{
    private static char[] _alphabet;

    static StringExtensions()
    {
        _alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
    }

    public static bool ContainsAlphabet(this string input)
    {
        return !_alphabet
            .Except(new HashSet<char>(input))
            .Any();
    }
}

"asdasd".ContainsAlphabet(); //false
"abcdeffffghijklmnopqrstuvwxyzzz".ContainsAlphabet(); //true
</code>```

Body:
You can use an extension method like this

public static class StringExtensions
{
    private static char[] _alphabet;

    static StringExtensions()
    {
        _alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
    }

    public static bool ContainsAlphabet(this string input)
    {
        return !_alphabet
            .Except(new HashSet<char>(input))
            .Any();
    }
}

"asdasd".ContainsAlphabet(); //false
"abcdeffffghijklmnopqrstuvwxyzzz".ContainsAlphabet(); //true


问:
How to upload zip file to azure blob then unzip it there
I have lot of zip files, which will have few folders and 50+ files in it. How can I upload those zip files to azure blob then unzip it there.

Unzipping the file in server and uploading files in it one by one to azure blob will be a cumbersome process.

Does azure has any easy way to achieve this or is there any workaround?

I'm implementing this in PHP.

答:
AS @Gaurav mentions, unzipping is not naively supported. There was a feedback item to include this as a feature but it was declined. I can think of two alternatives that may be of interest.

1) Build an Azure Data Factory custom activity that does the unzipping. As files are uploaded to a temporary location, you can then unzip then in a pipeline and write them to your application container. This will require a batch service instance but Data Factory will take care of all the orchestration and give you a management facility to alert for failures etc.

2) Move your blobs from Azure Blob Storage to Azure Data Lake Store using adlcopy.exe. Once in Data Lake Storage, you can then build your own custom extractor and query the zip/gzip files. After another look through the documentation it does seem that USQL may be able to do this natively. Look for the section Extraction from compressed data in the EXTRACT expression.

3) Use PolyBase with SQL Data Warehouse which can read zip/gzip files natively. This is the easiest but probably the most expensive option. See CREATE EXTERNAL TABLE and CREATE EXTERNAL FILE FORMAT.

4) And as @EvertonMc just mentioned, you could do it with an Azure function on a trigger, which is also a good option.

Good luck and let us know how you get on.


问:
JavaFX 8: Changing title of primary stage
How can the title of the primary stage be changed, when the window is already showen?

Stage#setTitle(String) apparently does not the trick.

答:
You can make Main class as singleton and to contact him via Main.getInstance()

For example:

```<code>public class Main extends Application {

    private static Main instance;
    public static Main getInstance() {
        return instance;
    }

    private Stage primaryStage;

    @Override
    public void start(Stage primaryStage) throws Exception{
        instance = this;
        this.primaryStage = primaryStage;
        Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
        this.primaryStage.setTitle("Init title");
        this.primaryStage.setScene(new Scene(root, 900, 650));
        this.primaryStage.show();
        FlatterFX.style();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public void updateTitle(String title) {
        primaryStage.setTitle(title);
    }
}
</code>```

Body:
You can make Main class as singleton and to contact him via Main.getInstance()

For example:

public class Main extends Application {

    private static Main instance;
    public static Main getInstance() {
        return instance;
    }

    private Stage primaryStage;

    @Override
    public void start(Stage primaryStage) throws Exception{
        instance = this;
        this.primaryStage = primaryStage;
        Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
        this.primaryStage.setTitle("Init title");
        this.primaryStage.setScene(new Scene(root, 900, 650));
        this.primaryStage.show();
        FlatterFX.style();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public void updateTitle(String title) {
        primaryStage.setTitle(title);
    }
}


问:
How to make multiple validation on field in angular 2?
I am building a model driven form in angular 2 and i want a specific field to have a range validation between 1-1000 and can also have values of 2000 and 2001,

I tried to put it in compose:

this.configForm.controls["field"].setValidators(Validators.compose([Validators.required,CustomValidators.equal(2000),CustomValidators.equal(2001), CustomValidators.range([1,1000])]));```

But it didn't work..

How to do it?

Thanks.

答:
If you are using FormBuilder, then consider implementing a group validator that validates a group of controls rather than individual ones:

How to do simple cross field validation in Angular 2 form to pass validation if one of the control in group has value?

The second argument to FormBuilder's  group method allows you to specify a group validator:

```<code> this.fb.group({
     field1: [''],
     field2: [''],
     },
     {
         validator: (c:FormGroup) => {
              return {'whateveryouwant': true};
         }
     }
 );
</code>```

If you need to clear the fields validation flags:

```<code>let field1 = c.get('field1');
field1.setErrors(null);
</code>```

Body:
I am building a model driven form in angular 2 and i want a specific field to have a range validation between 1-1000 and can also have values of 2000 and 2001,

I tried to put it in compose:

this.configForm.controls["field"].setValidators(Validators.compose([Validators.required,CustomValidators.equal(2000),CustomValidators.equal(2001), CustomValidators.range([1,1000])]));

But it didn't work..

How to do it?

Thanks.

Body:
If you are using FormBuilder, then consider implementing a group validator that validates a group of controls rather than individual ones:

How to do simple cross field validation in Angular 2 form to pass validation if one of the control in group has value?

The second argument to FormBuilder's  group method allows you to specify a group validator:

 this.fb.group({
     field1: [''],
     field2: [''],
     },
     {
         validator: (c:FormGroup) => {
              return {'whateveryouwant': true};
         }
     }
 );

If you need to clear the fields validation flags:

let field1 = c.get('field1');
field1.setErrors(null);


问:
Should I make different layout (xml files) for different android mobiles
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

```<code>res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
</code>```

This is my layout xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>
</code>```

Manifest file:

```<code><supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>
</code>```

but it does not work on 4 inch screen.

答:
If the layout is the same, there's no need to create multiple layout files, you should use different dimens files to adjust the size of your elements.

If you want your application to look different on a hdpi device than it looks on a xxxhdpi or if you have a mobile and a tablet version of the screen, then you should use multiple layout files.

Body:
Should I create different layout folders to store my xml layout files. To support my application over different screen sizes?

I developed an application and when adding drawables it automatically creates different sizes like xdpi ldpi and more but layouts xml file are not auto created to support different screen sizes. should I do it? and also i will edit manifest file to support different sizes by using support-screen tag. and is this all?? And will it also support my landscape or portrait mode.  Please confirm me. I am new to stack and android development.

Edit:
I believe different layout files in different folders.. will just be a copy of each other with only folder name change ad shown in code

res/layout/my_layout.xml             // layout for normal screen size ("default")
res/layout-small/my_layout.xml       // layout for small screen size
res/layout-large/my_layout.xml       // layout for large screen size
res/layout-xlarge/my_layout.xml      // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

This is my layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main"
    tools:context="com.example.root.meeransunday.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="Send Mobile"
        android:drawableLeft="@mipmap/sms"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-3dp"
        android:layout_marginBottom="-4dp"
        android:onClick="message"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:text="QR Code"
        android:drawableLeft="@mipmap/qr"
        android:layout_marginLeft="190dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-4dp"
        android:layout_alignParentBottom="true"
        android:onClick="scan"
        />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:text="        My Account Balance"
    android:textColor="#0D47A1"
    />
    <TextView
        android:text="PKR 1527.87"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
          android:drawableLeft="@mipmap/money"
        android:textSize="35sp"
        android:id="@+id/textView2"

        />
</RelativeLayout>

Manifest file:

<supports-screens android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"
            android:resizeable="true"/>

but it does not work on 4 inch screen.


问:
Recyclerview Changing Items During Scroll
I have a RecyclerView. Each row has a play button, textview and Progressbar. when click on the play button have to play audio from my sdcard and have to progress Progressbar
The problem is when i scroll down the recyclerview change the Progressbar in next row.means  I can fit 5 items on the screen at once. When I scroll to the 6th, 6th row seekbar changes suddenly.</p>

```<code>public class ListAdapter extends RecyclerView.Adapter {

    private List<Historyitem> stethitems;
    public Context mContext;
    public Activity activity;
    public Handler mHandler;

    static MediaPlayer mPlayer;
    static Timer mTimer;

    public ListAdapter(Activity activity,Context mContext,List<Historyitem> stethitems) {
        this.stethitems = stethitems;
        this.mContext = mContext;
        this.activity = activity;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View rootView = LayoutInflater.
                from(mContext).inflate(R.layout.stethoscopeadapteritem, null, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        rootView.setLayoutParams(lp);
        mHandler = new Handler();
        return new MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {

        final Historyitem dataItem = stethitems.get(position);
        final MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
        myViewHolder.progressplay.setProgress(0);
        myViewHolder.stethdatetime.setText(dataItem.getReported_Time());
        myViewHolder.stethhosname.setText(dataItem.getdiv());

        if(dataItem.getPatient_Attribute().replaceAll(" ","").equals("")){
            myViewHolder.stethdoctorname.setText(dataItem.getunit());
        } else {
            myViewHolder.stethdoctorname.setText(dataItem.getPatient_Attribute());
        }

        myViewHolder.stethstreamplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                   FileDownload(dataItem.getmsg(),
                            myViewHolder.progressplay);

            }
        });
    }

    @Override
    public int getItemCount() {

        return stethitems.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        final CustomTextRegular stethdatetime;
        final CustomTextView stethhosname;
        final CustomTextBold stethdoctorname;
        final ImageButton stethstreamplay;
        final NumberProgressBar progressplay;

        public MyViewHolder(View itemView) {
            super(itemView);

            stethdatetime = (CustomTextRegular)
                    itemView.findViewById(R.id.stethdatetime);
            stethhosname = (CustomTextView)
                    itemView.findViewById(R.id.stethhosname);
            stethdoctorname = (CustomTextBold)
                    itemView.findViewById(R.id.stethdoctorname);
            stethstreamplay = (ImageButton)
                    itemView.findViewById(R.id.stethstreamplay);
            progressplay= (NumberProgressBar)
                    itemView.findViewById(R.id.progressplay);

        }
    }
    public void  FileDownload(final String downloadpath,

                                     final NumberProgressBar progressplay) {

        new AsyncTask<NumberProgressBar, Integer, NumberProgressBar>() {
            NumberProgressBar progress;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                try {
                    if(mPlayer!=null){
                        mPlayer.stop();
                    }
                }catch (Exception e){
                }
                try {
                    if(mTimer != null){
                        mTimer.purge();
                        mTimer.cancel();
                    }
                }catch (Exception e){
                }
            }

            @Override
            protected NumberProgressBar doInBackground(NumberProgressBar... params) {
                int count;
                progress = progressplay;
                try {

                    final List<NameValuePair> list = new ArrayList<NameValuePair>();
                    list.add(new BasicNameValuePair("pid",id));

                    URL url = new URL(Config.requestfiledownload + "?path=" +
                            downloadpath);
                    URLConnection connection = url.openConnection();
                    connection.connect();

                    int lenghtOfFile = connection.getContentLength();
                    // download the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() +
                            "record.wav");
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {

                }
                return progress;
            }
            @Override
            protected void onPostExecute(final NumberProgressBar numberProgressBar) {
                super.onPostExecute(numberProgressBar);

                        try {
                            StartMediaPlayer(numberProgressBar);
                        } catch (Exception e){
                            e.printStackTrace();
                        }

            }
        }.execute();
    }

    public void StartMediaPlayer(final NumberProgressBar progressbar){
        Uri playuri = Uri.parse("file:///sdcard/record.wav");
        mPlayer = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.reset();
        try {
            mPlayer.setDataSource(mContext, playuri);
        } catch (IllegalArgumentException e) {

        } catch (SecurityException e) {

        } catch (IllegalStateException e) {

        } catch (Exception e) {

        }
        try {
            mPlayer.prepare();
        } catch (Exception e) {

        }

        mPlayer.start();
        progressbar.setMax(mPlayer.getDuration());
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if(mPlayer!=null) {
                    mPlayer.release();
                    progressbar.setProgress(0);
                }
                if(mTimer != null){
                    mTimer.purge();
                    mTimer.cancel();
                }
            }
        });
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressbar.setProgress(mPlayer.getCurrentPosition());
                    }
                });
            }
        },0,500);
    }}
</code>```

答:
Add setHasStableIds(true); in your adapter constructor and Override these two methods in adapter. It also worked if anyone using a RecyclerView inside a ViewPager which is also inside a NestedScrollView.

```<code>@Override
public long getItemId(int position) {
            return position;
}

@Override
public int getItemViewType(int position) {
       return position;
}
</code>```

Body:
I have a RecyclerView. Each row has a play button, textview and Progressbar. when click on the play button have to play audio from my sdcard and have to progress Progressbar
The problem is when i scroll down the recyclerview change the Progressbar in next row.means  I can fit 5 items on the screen at once. When I scroll to the 6th, 6th row seekbar changes suddenly.

public class ListAdapter extends RecyclerView.Adapter {

    private List<Historyitem> stethitems;
    public Context mContext;
    public Activity activity;
    public Handler mHandler;

    static MediaPlayer mPlayer;
    static Timer mTimer;

    public ListAdapter(Activity activity,Context mContext,List<Historyitem> stethitems) {
        this.stethitems = stethitems;
        this.mContext = mContext;
        this.activity = activity;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View rootView = LayoutInflater.
                from(mContext).inflate(R.layout.stethoscopeadapteritem, null, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        rootView.setLayoutParams(lp);
        mHandler = new Handler();
        return new MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {

        final Historyitem dataItem = stethitems.get(position);
        final MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
        myViewHolder.progressplay.setProgress(0);
        myViewHolder.stethdatetime.setText(dataItem.getReported_Time());
        myViewHolder.stethhosname.setText(dataItem.getdiv());

        if(dataItem.getPatient_Attribute().replaceAll(" ","").equals("")){
            myViewHolder.stethdoctorname.setText(dataItem.getunit());
        } else {
            myViewHolder.stethdoctorname.setText(dataItem.getPatient_Attribute());
        }

        myViewHolder.stethstreamplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                   FileDownload(dataItem.getmsg(),
                            myViewHolder.progressplay);

            }
        });
    }

    @Override
    public int getItemCount() {

        return stethitems.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        final CustomTextRegular stethdatetime;
        final CustomTextView stethhosname;
        final CustomTextBold stethdoctorname;
        final ImageButton stethstreamplay;
        final NumberProgressBar progressplay;

        public MyViewHolder(View itemView) {
            super(itemView);

            stethdatetime = (CustomTextRegular)
                    itemView.findViewById(R.id.stethdatetime);
            stethhosname = (CustomTextView)
                    itemView.findViewById(R.id.stethhosname);
            stethdoctorname = (CustomTextBold)
                    itemView.findViewById(R.id.stethdoctorname);
            stethstreamplay = (ImageButton)
                    itemView.findViewById(R.id.stethstreamplay);
            progressplay= (NumberProgressBar)
                    itemView.findViewById(R.id.progressplay);

        }
    }
    public void  FileDownload(final String downloadpath,

                                     final NumberProgressBar progressplay) {

        new AsyncTask<NumberProgressBar, Integer, NumberProgressBar>() {
            NumberProgressBar progress;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                try {
                    if(mPlayer!=null){
                        mPlayer.stop();
                    }
                }catch (Exception e){
                }
                try {
                    if(mTimer != null){
                        mTimer.purge();
                        mTimer.cancel();
                    }
                }catch (Exception e){
                }
            }

            @Override
            protected NumberProgressBar doInBackground(NumberProgressBar... params) {
                int count;
                progress = progressplay;
                try {

                    final List<NameValuePair> list = new ArrayList<NameValuePair>();
                    list.add(new BasicNameValuePair("pid",id));

                    URL url = new URL(Config.requestfiledownload + "?path=" +
                            downloadpath);
                    URLConnection connection = url.openConnection();
                    connection.connect();

                    int lenghtOfFile = connection.getContentLength();
                    // download the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() +
                            "record.wav");
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {

                }
                return progress;
            }
            @Override
            protected void onPostExecute(final NumberProgressBar numberProgressBar) {
                super.onPostExecute(numberProgressBar);

                        try {
                            StartMediaPlayer(numberProgressBar);
                        } catch (Exception e){
                            e.printStackTrace();
                        }

            }
        }.execute();
    }

    public void StartMediaPlayer(final NumberProgressBar progressbar){
        Uri playuri = Uri.parse("file:///sdcard/record.wav");
        mPlayer = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.reset();
        try {
            mPlayer.setDataSource(mContext, playuri);
        } catch (IllegalArgumentException e) {

        } catch (SecurityException e) {

        } catch (IllegalStateException e) {

        } catch (Exception e) {

        }
        try {
            mPlayer.prepare();
        } catch (Exception e) {

        }

        mPlayer.start();
        progressbar.setMax(mPlayer.getDuration());
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if(mPlayer!=null) {
                    mPlayer.release();
                    progressbar.setProgress(0);
                }
                if(mTimer != null){
                    mTimer.purge();
                    mTimer.cancel();
                }
            }
        });
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressbar.setProgress(mPlayer.getCurrentPosition());
                    }
                });
            }
        },0,500);
    }}

Body:
Add setHasStableIds(true); in your adapter constructor and Override these two methods in adapter. It also worked if anyone using a RecyclerView inside a ViewPager which is also inside a NestedScrollView.

@Override
public long getItemId(int position) {
            return position;
}

@Override
public int getItemViewType(int position) {
       return position;
}


问:
Unusual setdefault's in Django
Here's a piece of code from Django's authentification models (UserManager):

```<code>def create_superuser(self, username, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)

    if extra_fields.get('is_staff') is not True:
        raise ValueError('Superuser must have is_staff=True.')
    if extra_fields.get('is_superuser') is not True:
        raise ValueError('Superuser must have is_superuser=True.')

    return self._create_user(username, email, password, **extra_fields)
</code>```

Why set a key-value pair and check it immediately afterwards? In what scenario would these conditions be met?

答:
setdefault sets the value only if the key is not already present in the dict. The caller of the function could still pass extra_fields with some values of id_staff or is_superuser.

What this function does is that while creating a superuser if the calling function is not providing any values then set is_staff and is_superuser both to True for this user.

But, if the values are provided then check if those are True and raise exceptions otherwise.

Title: Unusual setdefault's in Django

Body:
Here's a piece of code from Django's authentification models (UserManager):

def create_superuser(self, username, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)

    if extra_fields.get('is_staff') is not True:
        raise ValueError('Superuser must have is_staff=True.')
    if extra_fields.get('is_superuser') is not True:
        raise ValueError('Superuser must have is_superuser=True.')

    return self._create_user(username, email, password, **extra_fields)

Why set a key-value pair and check it immediately afterwards? In what scenario would these conditions be met?


问:
Excluding specific iPhone types from App Store submission
I created a SpriteKit game that needs large screen area to be played so I decided not to write the code for the iPhone SE, but now I'm not sure if I can submit it to the App Store for all devices except the SE. Please let me know whether it's possible, and if so how to do it (i.e. where on iTunes Connect would you do it).

I looked up a lot but I couldn't find anything that could help.
I also couldn't find anything in the API.

答:
Unfortunately, there is no support from Apple for this kind of thing. But you can do something like detecting whether the user's device is an iPhone SE and if so show a full screen alert saying "App is not supported for this device" and block the UI (which is not recommended unless it's required).

Just a thought:
If you are lucky to find out one device capability which distinguish iPhone SE, you can set that to value in UIDeviceRequiredCapabilities key in info.plist.

Example: Adding an item to UIRequiredDeviceCapabilities in your Info.plist with the requirement of "bluetooth-le" should limit your app to iPhone 4S/5 and iPad 3, 4 and mini. You could also throw in a "camera-flash" requirement to limit the app to iPhones only, should you need that.

More info: Device Compatibility Matrix


问:
Cannot stop loading if url iframe offline or not found
How to stop the spinner when url is offline and display a warning that the offline or not found url??

CSS

```<code>#loadImg {
    position: absolute;
    z-index: 999;
}
#loadImg div {
    display: table-cell;
    background: #fff;
    height: 633px;
    text-align: center;
    vertical-align: middle;
    width: 2000px;
}
</code>```

HTML

```

答: A method to do this is to create a page which sends a request to the target and displays its response. If there was no response, then handle the error. Your new proxy page will be used as the target inside your iframe, but you will need to make sure you handle the relative URLs of the target page, that is, you rewrite those URLs to absolute paths. You will need to take a look at the src attribute of img and script tags and you will also need to take a look at the href of a and link tags. In case a CSS rule uses url() with a relative path, you will need to write your own CSS which overrides those rules.

Body:
How to stop the spinner when url is offline and display a warning that the offline or not found url??

CSS

#loadImg {
    position: absolute;
    z-index: 999;
}
#loadImg div {
    display: table-cell;
    background: #fff;
    height: 633px;
    text-align: center;
    vertical-align: middle;
    width: 2000px;
}

HTML


问:
Regex Image url
I'm trying to pre replace to get dynamic url,

Code is:

```<code><span>
  <img src="/List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455" />
</span>
</code>```

I need to extract: only /List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455

Ive tried: \/Listing\/AdDetail\/

答:
```<code>public static Set<String> getImgStr(String htmlStr) {
    Set<String> pics = new HashSet<>();
    String img = "";
    Pattern p_image;
    Matcher m_image;
    String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
    p_image = Pattern.compile
            (regEx_img, Pattern.CASE_INSENSITIVE);
    m_image = p_image.matcher(htmlStr);
    while (m_image.find()) {
        img = m_image.group();
        Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
        while (m.find()) {
            pics.add(m.group(1));
        }
    }
    return pics;
}
</code>```

Title: Regex Image url

Body:
I'm trying to pre replace to get dynamic url,

Code is:

I need to extract: only /List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455

Ive tried: \/Listing\/AdDetail\/