问:
How to verify if rect is inside cv::Mat in OpenCV?
Is there anything like cv::Mat::contains(cv::Rect) in Opencv?

Background:
After detecting objects as contours and trying to access ROIs by using cv::boundingRect my application crashed. OK, that's because the bounding rects of the object close to image border may be not entirely within the image.

Now I skip the objects not entirely in image by this check:

```<code>if(
  cellRect.x>0 &&
  cellRect.y>0 &&
  cellRect.x + cellRect.width < m.cols &&
  cellRect.x + cellRect.width < m.rows) ...
</code>```

where cellRect is the bounding rect of the object and m is the image.
I hope there is a dedicated opencv function for this.

答:
Here is a method to judge whether a rectangle contains an other rectangle.
you can get the size info from cv::Mat first, and then use method below:

```<code>public bool rectContainsRect(Rectangle containerRect, Rectangle subRect)
{
    if( containerRect.Contains(new Point(subRect.Left, subRect.Top))
        && containerRect.Contains(new Point(subRect.Right, subRect.Top))
        && containerRect.Contains(new Point(subRect.Left, subRect.Bottom))
        && containerRect.Contains(new Point(subRect.Right, subRect.Bottom)))
    {
        return true;
    }
    return false;
}
</code>```

Body:
Is there anything like cv::Mat::contains(cv::Rect) in Opencv?

Background:
After detecting objects as contours and trying to access ROIs by using cv::boundingRect my application crashed. OK, that's because the bounding rects of the object close to image border may be not entirely within the image.

Now I skip the objects not entirely in image by this check:

if(
  cellRect.x>0 &&
  cellRect.y>0 &&
  cellRect.x + cellRect.width < m.cols &&
  cellRect.x + cellRect.width < m.rows) ...

where cellRect is the bounding rect of the object and m is the image.
I hope there is a dedicated opencv function for this.

Body:
Here is a method to judge whether a rectangle contains an other rectangle.
you can get the size info from cv::Mat first, and then use method below:

public bool rectContainsRect(Rectangle containerRect, Rectangle subRect)
{
    if( containerRect.Contains(new Point(subRect.Left, subRect.Top))
        && containerRect.Contains(new Point(subRect.Right, subRect.Top))
        && containerRect.Contains(new Point(subRect.Left, subRect.Bottom))
        && containerRect.Contains(new Point(subRect.Right, subRect.Bottom)))
    {
        return true;
    }
    return false;
}


来源: stackexchange

问:
Is it possible to use pbapply in parallel?
I have this code where I want to sum the columns of a matrix.

I also want to have a couple of features (my matrix is much bigger than the example below):

use multiple cores

have a progress bar

I tried pbapply from the pbapply package but without luck. My code is:

```<code>library(pbapply)
library(parallel)

mat <- matrix(ncol=20, nrow = 50, data = runif(1000))

# sum of the columns
matsum <- apply(mat,2,sum)

# now the same in parallel
cl <- makeCluster(2)
pboptions(type = "txt")
parmat <- pbapply(mat,2,sum, cl=cl)
stopCluster(cl)
</code>```

This leads to the error:

Error in FUN(newX[, i], ...) : invalid 'type' (list) of argument

My question is, is it possible at all to run pbapply in parallel?

答:
pbapply doesn't take the cl argument, so no. You can, however, convert your matrix to a data.frame (if that's feasible), and use sapply which should work on columns.

```<code>mat <- as.data.frame(mat)
parmat <- pbsapply(X = mat, FUN = sum, cl = cl)
</code>```

Or, you could try

```<code>colSums(mat)
</code>```

which is pretty pimped up workhorse.

ContentLicense: CC BY-SA 3.0

Body:
I have this code where I want to sum the columns of a matrix.

I also want to have a couple of features (my matrix is much bigger than the example below):

use multiple cores

have a progress bar

I tried pbapply from the pbapply package but without luck. My code is:

library(pbapply)
library(parallel)

mat <- matrix(ncol=20, nrow = 50, data = runif(1000))

# sum of the columns
matsum <- apply(mat,2,sum)

# now the same in parallel
cl <- makeCluster(2)
pboptions(type = "txt")
parmat <- pbapply(mat,2,sum, cl=cl)
stopCluster(cl)

This leads to the error:

Error in FUN(newX[, i], ...) : invalid 'type' (list) of argument

My question is, is it possible at all to run pbapply in parallel?

Body:
pbapply doesn't take the cl argument, so no. You can, however, convert your matrix to a data.frame (if that's feasible), and use sapply which should work on columns.

mat <- as.data.frame(mat)
parmat <- pbsapply(X = mat, FUN = sum, cl = cl)

Or, you could try

colSums(mat)

which is pretty pimped up workhorse.


问:
Raspberry Pi 3 Model B setup startx or sudo startx gives: command not found
How can I get startx to work?

I have my SD set -used pi filler and image raspbian jessie.

However, I did download the zip Raspbian Jessie Lite (usually I have done the full desktop image, not lite)

After I log in as pi I want to get to my GUI. I type:

```<code>$startx
-bash: startx: command not found
</code>```

So then I try with sudo, still: command not found.

I have done my steps in the sudo raspi-config to extend file system, set correct time and keyboard.

When I try to install some python packages

I want to configure my wi-fi by running the GUI. But, I cannot get to my gui with startx.

I know a few things (I've had startx work before on other pi 3s, but I'm a big noob, so please be detailed if you can help me out.

Thank you, in advance!

答:
My solution was to install these packages</p>

```<code>sudo apt-get --no-install-recommends install xserver-xorg xserver-xorg-video-fbdev xinit pciutils xinput xfonts-100dpi xfonts-75dpi xfonts-scalable
</code>```

Body:
How can I get startx to work?

I have my SD set -used pi filler and image raspbian jessie.

However, I did download the zip Raspbian Jessie Lite (usually I have done the full desktop image, not lite)

After I log in as pi I want to get to my GUI. I type:

$startx
-bash: startx: command not found

So then I try with sudo, still: command not found.

I have done my steps in the sudo raspi-config to extend file system, set correct time and keyboard.

When I try to install some python packages

I want to configure my wi-fi by running the GUI. But, I cannot get to my gui with startx.

I know a few things (I've had startx work before on other pi 3s, but I'm a big noob, so please be detailed if you can help me out.

Thank you, in advance!

Body:
My solution was to install these packages

sudo apt-get --no-install-recommends install xserver-xorg xserver-xorg-video-fbdev xinit pciutils xinput xfonts-100dpi xfonts-75dpi xfonts-scalable


问:
In c language, Embedded Application, how to compare members from an Array of structure
I have a Memory chip that has data read by an embedded system serially. The memory device has 10 locations with each location having the following information: customerID, NumOfParts, MFGName.
Here is my version of C code I wrote for this.

IN C FILE "PartName.h"

```<code>    //"PartName.h"
    #ifndef PartName_H
    #define PartName_H

    typedef UINT8 MFGName_Struct_t [10];

    typedef struct
    {
        UINT8 customerID;
        UINT8 NumOfParts;
        MFGName_Struct_t MFGName;
    }IDENT_Struct_t;

    typedef struct MFG_Struct_t
    {
        UINT8 <some other variable>;
        UINT8 <some other variable>;
        IDENT_Struct_t Ident1;
        IDENT_Struct_t Ident2;
        IDENT_Struct_t Ident3;
        IDENT_Struct_t Ident4;
        IDENT_Struct_t Ident5;
        IDENT_Struct_t Ident6;
        IDENT_Struct_t Ident7;
        IDENT_Struct_t Ident8;
        IDENT_Struct_t Ident9;
        IDENT_Struct_t Ident10;
    } MFG_Struct_t;

    #endif
</code>```

IN C FILE "HighNum.c"

```<code>    //"HighNum.c"
    #include "PartName.h"
    static MFG_Struct_t  MFG;
    UINT8 HighNum(void)
   {
     //UINT8 i;
       UINT8 highestNum = 0;
     //for (i = 0;(i < 10);i++)

       if (MFG.Ident1.NumOfParts > MFG.Ident2.NumOfParts)
       {
           highestNum = MFG.Ident1.NumOfParts;
       }
       if (MFG.Ident2.NumOfParts > MFG.Ident3.NumOfParts)
       {
           highestNum = MFG.Ident2.NumOfParts;
       }
       if (MFG.Ident3.NumOfParts > MFG.Ident4.NumOfParts)
       {
           highestNum = MFG.Ident3.NumOfParts;
       }
       if (MFG.Ident4.NumOfParts > MFG.Ident5.NumOfParts)
       {
           highestNum = MFG.Ident4.NumOfParts;
       }
       <and so on>
     return highestNum;
   }
</code>```

How can this be done more efficient in C? using for statements or While statements? I thought about concatenating the number portion and cycling through the variables...

答:
If you modify your structure to this:

```<code>#define IDENT_SIZE         10
typedef struct MFG_Struct_t
{
    UINT8 <some other variable>;
    UINT8 <some other variable>;
    IDENT_Struct_t Ident[IDENT_SIZE];
} MFG_Struct_t;
</code>```

Then you can do this:

```<code>size_t i = 0;
for (i = 0; i < IDENT_SIZE; i++) {
     if (MFG.Ident[i].NumOfParts > highestNum) {
           highestNum = MFG.Ident[i].NumOfParts;
     }
}
</code>```

Body:
I have a Memory chip that has data read by an embedded system serially. The memory device has 10 locations with each location having the following information: customerID, NumOfParts, MFGName.
Here is my version of C code I wrote for this.

IN C FILE "PartName.h"

    //"PartName.h"
    #ifndef PartName_H
    #define PartName_H

    typedef UINT8 MFGName_Struct_t [10];

    typedef struct
    {
        UINT8 customerID;
        UINT8 NumOfParts;
        MFGName_Struct_t MFGName;
    }IDENT_Struct_t;

    typedef struct MFG_Struct_t
    {
        UINT8 <some other variable>;
        UINT8 <some other variable>;
        IDENT_Struct_t Ident1;
        IDENT_Struct_t Ident2;
        IDENT_Struct_t Ident3;
        IDENT_Struct_t Ident4;
        IDENT_Struct_t Ident5;
        IDENT_Struct_t Ident6;
        IDENT_Struct_t Ident7;
        IDENT_Struct_t Ident8;
        IDENT_Struct_t Ident9;
        IDENT_Struct_t Ident10;
    } MFG_Struct_t;

    #endif

IN C FILE "HighNum.c"

    //"HighNum.c"
    #include "PartName.h"
    static MFG_Struct_t  MFG;
    UINT8 HighNum(void)
   {
     //UINT8 i;
       UINT8 highestNum = 0;
     //for (i = 0;(i < 10);i++)

       if (MFG.Ident1.NumOfParts > MFG.Ident2.NumOfParts)
       {
           highestNum = MFG.Ident1.NumOfParts;
       }
       if (MFG.Ident2.NumOfParts > MFG.Ident3.NumOfParts)
       {
           highestNum = MFG.Ident2.NumOfParts;
       }
       if (MFG.Ident3.NumOfParts > MFG.Ident4.NumOfParts)
       {
           highestNum = MFG.Ident3.NumOfParts;
       }
       if (MFG.Ident4.NumOfParts > MFG.Ident5.NumOfParts)
       {
           highestNum = MFG.Ident4.NumOfParts;
       }
       <and so on>
     return highestNum;
   }

How can this be done more efficient in C? using for statements or While statements? I thought about concatenating the number portion and cycling through the variables...

Body:
If you modify your structure to this:

#define IDENT_SIZE         10
typedef struct MFG_Struct_t
{
    UINT8 <some other variable>;
    UINT8 <some other variable>;
    IDENT_Struct_t Ident[IDENT_SIZE];
} MFG_Struct_t;

Then you can do this:

size_t i = 0;
for (i = 0; i < IDENT_SIZE; i++) {
     if (MFG.Ident[i].NumOfParts > highestNum) {
           highestNum = MFG.Ident[i].NumOfParts;
     }
}


问:
Posting build errors to slack or github
I am using Visual Studio Online for continuous integration. I've also enabled integration with Slack (posting build status) and GitHub (validating pull requests).

In both of these integrations I am missing one feature - posting build error log to either Slack or GitHub (for example, as a comment to the pull request). This might substantially improve reaction time, since you don't need to go to the failed build (often re-login to VSO), find errors in the log, etc.

Did any of you guys manage to get this working somehow?

答:
You can use web hook to return VSTS build error message to slack or do some actions (create issue, close pull request etc) on github.

Prerequisite:

Web hook for VSTS build failed.

Develop a website to receive information, queue VSTS build and close pull request on github.

Add a build definition with Post To Slack task, when your VSTS build failed, your website will queue this build.

Create web hook:

VSTS project -> Service Hooks -> Create subscription -> Web hooks -> Next -> select Build completed to trigger this event -> select your CI build definition -> set Build Status to Failed -> Next -> set your website address to URL -> test if it works for your website -> Finish.

Develop functions on your website:

After your website receiving message from web hooks, trigger below actions:

Queuing the build with Post To Slack task by REST API.

Close a pull request on github by REST API v3.

Title: Posting build errors to slack or github


问:
Umbraco Database size
We are hosting a new Umbraco 7 site with the database on SQL server 2012 Express. The database seems to be growing rapidly. It's currently about 5Gb and SQL 2012 express has a maximum database size of 10Gb so we are starting to get a little concerned. The cmsPropertyData and cmsPreviewXml seem to be taking up the most space at about 2.5Gb each. Is there any general housekeeping that needs to be done to keep these tables under control. Have tried shrinking the database but there is no unused space.

Any Advice?

答: I don't know for sure this is the problem in your case, but Umbraco creates a new version of the content node each time the node is saved. This can cause your database to grow rapidly. There's a cool package that automatically removes older versions called "UnVersion". https://our.umbraco.org/projects/website-utilities/unversion/</p>

Title: Umbraco Database size


问:
stratified sampling R: java.lang.OutOfMemoryError: Java heap space
I want to use this function here is the code on github to sample my dataset in 2 parts 90% traning data set ( for example) and 10% (the rest) are the test ( for example  tried this code :

```<code>library(XLConnect)
library(readxl)
library(xlsx)
library(readxl)
ybi <- read_excel("D:/ii.xls")
#View(ybi)
test= stratified(ybi, 8, .1)

 no= (test$ID_unit) # to get indices of the testdataset samples
 train = ybi [-no,] # the indices for training data

 write.xlsx(train,"D:/mm.xlsx",sheetName = "Newdata")
</code>```

in fact my data have 8 attributes and  65534 row.
I have selected by the code above just 10% based on the 8 eigth attribute which is the class it gives me without any problm the test set but not the training data ther error is on the figure (joined)error

how to fix it!

答:
It looks like you JVM has no enough memory allocated for the heap.

As a quick fix, export system variable _JAVA_OPTIONS

export _JAVA_OPTIONS="-Xmx8G -Xms1G -Xcheck:jni"

you can also use:

options(java.parameters = "-Xmx8G")

and set -Xmx to a value that will make R happy.

Body:
I want to use this function here is the code on github to sample my dataset in 2 parts 90% traning data set ( for example) and 10% (the rest) are the test ( for example  tried this code :

library(XLConnect)
library(readxl)
library(xlsx)
library(readxl)
ybi <- read_excel("D:/ii.xls")
#View(ybi)
test= stratified(ybi, 8, .1)

 no= (test$ID_unit) # to get indices of the testdataset samples
 train = ybi [-no,] # the indices for training data

 write.xlsx(train,"D:/mm.xlsx",sheetName = "Newdata")

in fact my data have 8 attributes and  65534 row.
I have selected by the code above just 10% based on the 8 eigth attribute which is the class it gives me without any problm the test set but not the training data ther error is on the figure (joined)error

how to fix it!


问:
cygwin installation Windows 8.1
I downloaded Eclipse Neon and tried to work sample program but it's giving issue at

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

Warning is:Unresolved inclusion:
I went through some posts and found out we should install Cygwin to proceed working. While Installing Cygwin,there is an option Choose a download site and there are many links .I can't move to next step until I choose one of the links. What link should be chosen here?
I have attached the screenshot of installation too.
enter image description here

答:
You can choose one of these links. It's exactly the same. After the installation, you have to change the PATH into your environment variables and add the path of the bin folder of Cygwin.
You can test your installation with typing sys into the shell.

Title: cygwin installation Windows 8.1

Body:
I downloaded Eclipse Neon and tried to work sample program but it's giving issue at

#include<stdio.h>

Warning is:Unresolved inclusion:
I went through some posts and found out we should install Cygwin to proceed working. While Installing Cygwin,there is an option Choose a download site and there are many links .I can't move to next step until I choose one of the links. What link should be chosen here?
I have attached the screenshot of installation too.
enter image description here


问:
Save last row number as variable after opening the workbook for the later use
I want to save the last row number used in a particular sheet at Workbook_Open() for the later use in other modules.
So far I have this code:

ThisWorkbook:

```<code>Public last_row as long

Private Sub Workbook_Open()
    last_row = Worksheets("Sheet1").Cells(Rows.count, 1).End(xlUp).Row
    MsgBox ("This is the last row number: " & last_row)
End Sub
</code>```

I get the pop-up message correctly, like "This is the last row number: 25", when I open the workbook. This is a desired output.

Module 1:

```<code>Sub ABC()
    MsgBox ("This is the last row number: " & last_row)
End Sub
</code>```

But when I run the Module 1, "This is the last row number: " message is what I get.

So, I am failing in storing the "last_row" variable as public. What am I doing wrong? Thanks in advance!

答:
What you want to do is a bad idea and definitely not recommended. Public variables reset the moment there is an error.

Recalculate it every time you want to use it. You can do it in two ways

lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row where ws is your worksheet object

Create a function if you do not want to write that "long code [pun intended :)]" every time

Paste this in a module

```<code>Function GetMeLastRow() As Long
    Dim ws As Worksheet

    Set ws = Sheet1 '<~~ Change this to relevant sheet or pass it as a parameter

    With ws
        GetMeLastRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
    End With
End Function
</code>```

And then use it like this

```<code>MsgBox GetMeLastRow
</code>```

Body:
I want to save the last row number used in a particular sheet at Workbook_Open() for the later use in other modules.
So far I have this code:

ThisWorkbook:

Public last_row as long

Private Sub Workbook_Open()
    last_row = Worksheets("Sheet1").Cells(Rows.count, 1).End(xlUp).Row
    MsgBox ("This is the last row number: " & last_row)
End Sub

I get the pop-up message correctly, like "This is the last row number: 25", when I open the workbook. This is a desired output.

Module 1:

Sub ABC()
    MsgBox ("This is the last row number: " & last_row)
End Sub

But when I run the Module 1, "This is the last row number: " message is what I get.

So, I am failing in storing the "last_row" variable as public. What am I doing wrong? Thanks in advance!

Body:
What you want to do is a bad idea and definitely not recommended. Public variables reset the moment there is an error.

Recalculate it every time you want to use it. You can do it in two ways

lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row where ws is your worksheet object

Create a function if you do not want to write that "long code [pun intended :)]" every time

Paste this in a module

Function GetMeLastRow() As Long
    Dim ws As Worksheet

    Set ws = Sheet1 '<~~ Change this to relevant sheet or pass it as a parameter

    With ws
        GetMeLastRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
    End With
End Function

And then use it like this

MsgBox GetMeLastRow


答:
I hope the following code can help you:</p>

```<code>typedef struct MFG_Struct_t
{
    UINT8 <some other variable>;
    UINT8 <some other variable>;
    IDENT_Struct_t Idents[10];
} MFG_Struct_t;

typedef enum _Idents
{
    Ident1 = 0,
    Ident2,
    Ident3,
    Ident4,
    Ident5,
    Ident6,
    Ident7,
    Ident8,
    Ident9,
    Ident10,
} IdentType;

   if (MFG.Idents[Ident1].NumOfParts > MFG.Idents[Ident2].NumOfParts)
   {
       highestNum = MFG.Idents[Ident1].NumOfParts;
   }

// or
for (index = Ident1; index < Ident10; index ++)
{
    if (MFG.Idents[index].NumOfParts > MFG.Idents[index +1].NumOfParts)
    {
        //......
    }
}
</code>```

Title: In c language, Embedded Application, how to compare members from an Array of structure

Body:
I hope the following code can help you:

typedef struct MFG_Struct_t
{
    UINT8 <some other variable>;
    UINT8 <some other variable>;
    IDENT_Struct_t Idents[10];
} MFG_Struct_t;

typedef enum _Idents
{
    Ident1 = 0,
    Ident2,
    Ident3,
    Ident4,
    Ident5,
    Ident6,
    Ident7,
    Ident8,
    Ident9,
    Ident10,
} IdentType;

   if (MFG.Idents[Ident1].NumOfParts > MFG.Idents[Ident2].NumOfParts)
   {
       highestNum = MFG.Idents[Ident1].NumOfParts;
   }

// or
for (index = Ident1; index < Ident10; index ++)
{
    if (MFG.Idents[index].NumOfParts > MFG.Idents[index +1].NumOfParts)
    {
        //......
    }
}


问:
When do you have to worry about thread safety?
What are some situations where you need to worry about whether a static method is thread safe?

For example, if I have static utility function that doesn't touch any static class level variables, is that method already thread safe? If I have a static method that does touch static class variables, is that method potentially not thread safe?

Thanks in advance.

答: You have to worry about thread safety whenever you have more than one thread accessing the same resources, and those resources are not immutable.</p>

ContentLicense: CC BY-SA 2.5


问:
how to swap queues in java when they have different number of elements?
how can we swap two queues in java with constant time complexity?
I thought of trying this out.
Is it possible to write:

```<code>temp=q1;
q1=q2;
q2=temp;
</code>```

here q1 ,q2 and q3 are linkedlist based queues.

答: Its not possible to swap two queues in constant time. If queues are of size n then it will take O(n) time to swap elements of one queue into another. However you can change front and rear of both queues which will take O(1) i.e. constant time. </p>

Body:
how can we swap two queues in java with constant time complexity?
I thought of trying this out.
Is it possible to write:

temp=q1;
q1=q2;
q2=temp;

here q1 ,q2 and q3 are linkedlist based queues.


问:
Django missing fields after initial makemigration
When I run python manage.py makemigrations myapp and check the 0001_initial.py file in my migrations folder, I expected to see every field in my models, however what I see is below:

```<code>from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Data',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('original_file', models.TextField(max_length=255)),
            ],
            options={
                'managed': False,
                'db_table': 'acoustic_data',
            },
        ),
        migrations.CreateModel(
            name='Sites',
            fields=[
                ('site_name', models.TextField(primary_key=True, serialize=False)),
            ],
            options={
                'managed': False,
                'db_table': 'site',
            },
        ),
    ]
</code>```

you can see that the Data model only has 'original_file' field while I was expecting also 'data_id', 'site_id', 'date_recorded', 'time_recorded' and 'average'. For the Site model 'site_id' is also missing. I am wondering why only the last field shows up?

Below is my models.py:

```<code>from django.db import models

# Create your models here.

class Sites(models.Model):
    site_id = models.TextField(primary_key=True)
    site_name = models.TextField(max_length=255)

    class Meta:
        managed = False # this means Django should never alter this table
        db_table = 'site'

class Data(models.Model):
    data_id = models.IntegerField(primary_key=True)
    site_id = models.ForeignKey(Sites, db_column='site_id', to_field='site_id')
    date_recorded = models.DateField('%Y-%m-%d')
    time_recorded = models.TimeField('%H:%M:%S')
    average = models.FloatField(null=True, blank=True, default=None)
    original_file = models.TextField(max_length=255)

    class Meta:
        managed = False # this means Django should never alter this table
        db_table = 'acoustic_data'
</code>```

I also referred to this question already Django makemigrations omists some fields from model  but it didn't seem to work for me.

答:
If it is 0001 version ~> You makemigrations for the first time.

Please delete it and create again (may be you makemigrations when the models don't complete yet)

If this problem stay still please edit for more detail (the console log)

Body:
When I run python manage.py makemigrations myapp and check the 0001_initial.py file in my migrations folder, I expected to see every field in my models, however what I see is below:

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Data',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('original_file', models.TextField(max_length=255)),
            ],
            options={
                'managed': False,
                'db_table': 'acoustic_data',
            },
        ),
        migrations.CreateModel(
            name='Sites',
            fields=[
                ('site_name', models.TextField(primary_key=True, serialize=False)),
            ],
            options={
                'managed': False,
                'db_table': 'site',
            },
        ),
    ]

you can see that the Data model only has 'original_file' field while I was expecting also 'data_id', 'site_id', 'date_recorded', 'time_recorded' and 'average'. For the Site model 'site_id' is also missing. I am wondering why only the last field shows up?

Below is my models.py:

from django.db import models

# Create your models here.

class Sites(models.Model):
    site_id = models.TextField(primary_key=True)
    site_name = models.TextField(max_length=255)

    class Meta:
        managed = False # this means Django should never alter this table
        db_table = 'site'

class Data(models.Model):
    data_id = models.IntegerField(primary_key=True)
    site_id = models.ForeignKey(Sites, db_column='site_id', to_field='site_id')
    date_recorded = models.DateField('%Y-%m-%d')
    time_recorded = models.TimeField('%H:%M:%S')
    average = models.FloatField(null=True, blank=True, default=None)
    original_file = models.TextField(max_length=255)

    class Meta:
        managed = False # this means Django should never alter this table
        db_table = 'acoustic_data'

I also referred to this question already Django makemigrations omists some fields from model  but it didn't seem to work for me.


问:
Android floating button not coming proper
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

```<code><android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>
</code>```

答:
Just try this way its working fine,</p>

```<code><android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        app:elevation="10dp"

        app:borderWidth="0dp"
        app:backgroundTint="#f0f0"
        android:src="@android:drawable/ic_dialog_email"/>
</code>```

Body:
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>

Body:
Just try this way its working fine,

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        app:elevation="10dp"

        app:borderWidth="0dp"
        app:backgroundTint="#f0f0"
        android:src="@android:drawable/ic_dialog_email"/>


问:
Block Scoped Function ECMAScript 6 Strange Behaviour
I was reading the new features in ECMA6. One of the new features is Block Scoped Functions . That means we can have a same name for functions in different blocks. As in the code below block1 foo() logs 1 then similarly block2 foo() logs 2 and block0 foo() or global scope logs 4. And that is the expected result. But what i can't understand is that Why does the last console.log(foo()) logs 1 and not 4 because it is under block0 or global scope instead it logs 1 which is block1 foo().

//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//should log 4 but logs 1 why?```
</div>
</div>
</p>

<p>Now again if I enclose the above code into a another block it works as expected. This is a bit confusing to me. What actually is causing this behviour?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//will log 4 but
}</code>```

答:
I think it depends on where you are running your code. Maybe this feature isn't supported just yet. Your code snippet logs 4, 1, 2, 2, 2 (Firefox browser).

Logically your code should log as you say.

Where exactly do you test the code?

Body:
I was reading the new features in ECMA6. One of the new features is Block Scoped Functions . That means we can have a same name for functions in different blocks. As in the code below block1 foo() logs 1 then similarly block2 foo() logs 2 and block0 foo() or global scope logs 4. And that is the expected result. But what i can't understand is that Why does the last console.log(foo()) logs 1 and not 4 because it is under block0 or global scope instead it logs 1 which is block1 foo().

//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//should log 4 but logs 1 why?

Now again if I enclose the above code into a another block it works as expected. This is a bit confusing to me. What actually is causing this behviour?

{//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//will log 4 but
}


答:
If I have static utility function that doesn't touch any static class level variables, is that method already thread safe?

Most of the time - what matters is if your method is reentrant. Something like this is reentrant because everything is local variables and each thread receives its own copy:

```<code>static int add(int a, int b)
{
    return a + b;
}
</code>```

There are still some things to be careful of. If you pass in an object to the method and the method mutates the object and before the method completes you call the same method again on a different thread but with the same object, then you have a problem.

If I have a static method that does touch static class variables, is that method potentially not thread safe?

The main issue again is if the variables are mutable. If you are only reading from immutable objects then there may not be any problem.

If you call a method and you are not sure if it is reentrant and the documentation doesn't say, it's best to assume that it isn't.

Title: When do you have to worry about thread safety?

Body:
What are some situations where you need to worry about whether a static method is thread safe?

For example, if I have static utility function that doesn't touch any static class level variables, is that method already thread safe? If I have a static method that does touch static class variables, is that method potentially not thread safe?

Thanks in advance.

Body:
If I have static utility function that doesn't touch any static class level variables, is that method already thread safe?

Most of the time - what matters is if your method is reentrant. Something like this is reentrant because everything is local variables and each thread receives its own copy:

static int add(int a, int b)
{
    return a + b;
}

There are still some things to be careful of. If you pass in an object to the method and the method mutates the object and before the method completes you call the same method again on a different thread but with the same object, then you have a problem.

If I have a static method that does touch static class variables, is that method potentially not thread safe?

The main issue again is if the variables are mutable. If you are only reading from immutable objects then there may not be any problem.

If you call a method and you are not sure if it is reentrant and the documentation doesn't say, it's best to assume that it isn't.


问:
How to Clear/Reset formData() using javascript?
I am using formData for Ajax Image Uploading, when I am submit first time it will successfully upload, and again click post button that image also posted to server, I think formData will not clear.

My Code

```<code>$("#postsubmitimage").click(function () {
                var formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    if (files[i].type.indexOf('image/') === 0) {
                        formData.append("files", files[i]);
                    }
                }
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/Fileupload/',
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (json) {
                            $('#textpostimage').val('');
                        }
                    });
            })
</code>```

答:
I think this happens because your files variable is not cleared after the ajax submission. In your click handler you create an empty FormData object indeed, but then you proceed to fill that object with old references from files, which apparently are not clear.

What I suggest is doing some cleanup after a successful ajax completion

```<code>success: function (json) {
    // Supposing #textpostimage is your file input, you are already clearing it
    $('#textpostimage').val('');
    // Also clear your "files" reference
    files = [];
}
</code>```

To clear the whole form you could do $('#myForm').get(0).reset()

I don't know at what time you populate files with values from #textpostimage, but make sure to do it not only on page load, if you want to have multiple form submissions working.

Body:
I am using formData for Ajax Image Uploading, when I am submit first time it will successfully upload, and again click post button that image also posted to server, I think formData will not clear.

My Code

$("#postsubmitimage").click(function () {
                var formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    if (files[i].type.indexOf('image/') === 0) {
                        formData.append("files", files[i]);
                    }
                }
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/Fileupload/',
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (json) {
                            $('#textpostimage').val('');
                        }
                    });
            })

Body:
I think this happens because your files variable is not cleared after the ajax submission. In your click handler you create an empty FormData object indeed, but then you proceed to fill that object with old references from files, which apparently are not clear.

What I suggest is doing some cleanup after a successful ajax completion

success: function (json) {
    // Supposing #textpostimage is your file input, you are already clearing it
    $('#textpostimage').val('');
    // Also clear your "files" reference
    files = [];
}

To clear the whole form you could do $('#myForm').get(0).reset()

I don't know at what time you populate files with values from #textpostimage, but make sure to do it not only on page load, if you want to have multiple form submissions working.


问:
setInterval usage causes strange infinite loop
I am trying a map lesson and got tripped up on setInterval causing an infinite loop. Since I am only going over a list with 5 elements, I don't understand why this is happening; it prints out all 5 numbers like:

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

over and over again forever with:

```<code>var list = [1, 2, 3, 4, 5];

function delayedPrint(text, delay = 400) {
    setInterval(function() {
        console.log(text);
    }, delay)
}

console.log('\nMap can take 1 argument, which is each item in the array:')

list.map(function(this_list_item) {
    delayedPrint(this_list_item);
});
</code>```

but changing delayedPrint(this_list_item); to console.log(this_list_item); the code works as normal, printing each item 1 time.

Why does this infinite loop happen and how can I print these items with an arbitrary delay?  `setInterval` Apparent Infinite Loop didn't help.

答:
That is what setInterval is supposed to do:

The setInterval() method of the WindowOrWorkerGlobalScope mixin repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

What you want, however, is setTimeout.

ContentLicense: CC BY-SA 4.0

Body:
I am trying a map lesson and got tripped up on setInterval causing an infinite loop. Since I am only going over a list with 5 elements, I don't understand why this is happening; it prints out all 5 numbers like:

1
2
3
4
5

over and over again forever with:

var list = [1, 2, 3, 4, 5];

function delayedPrint(text, delay = 400) {
    setInterval(function() {
        console.log(text);
    }, delay)
}

console.log('\nMap can take 1 argument, which is each item in the array:')

list.map(function(this_list_item) {
    delayedPrint(this_list_item);
});

but changing delayedPrint(this_list_item); to console.log(this_list_item); the code works as normal, printing each item 1 time.

Why does this infinite loop happen and how can I print these items with an arbitrary delay?  `setInterval` Apparent Infinite Loop didn't help.


问:
how to display a hidden table when submit button is clicked and data is inserted in database table in php?
I have one from through which I am entering project name and sheet name which will be saved in project table. Based on this I am inserting empty values on another table 'Data'. I am using editable table to update these empty values in database. I want to hide this table till project name and sheet name is submitted and once value is submitted then only table will be displayed. I have tried a lot but after clicking submit button my table gets displayed till page is reloaded and disappers when loading is completed. My code parts are like below.</p>

```<code>    <script>
     $(function(){
     $('button#showit').on('click',function(){
    $('#myform').show();
     });
     });
    </script>
    <form class="form-horizontal" action="db.php" id="#form1"
     onSubmit="function();" method="post">

    <input type="text" class="form-control1" name="projectname"
   id="projectname" required >
    <input type="text" class="form-control1" name="sheetname" id="sheetname"
    required >
    <button type="submit" name="submit" id="button" class="btn-
     success btn" >Submit</button>
        </form>
      <div class="tab-content"  id="myform" style="display:none">
     <div class="tab-pane active" id="horizontal-form">
     <?php

       $s4 = "SELECT * FROM data ORDER BY data_id DESC LIMIT 1";
     $res = mysqli_query($bd, $s4);
    while ($row = mysqli_fetch_array($res))
                                 {
                            ?>
   <table class="table table-bordered" style="width:50%;">
    <thead>
    <tr>
    <th>Sr.no</th>
    <th>Column Name</th>

       </tr>
     </thead>
     <tbody>

   <tr class="odd">
    <td>1</td>
     <td id="d1:<?php echo $row['data_id']; ?>" contenteditable="true"><?php
    echo $row['d1']; ?></td>
   </tr>

   .
   .
    .
   </tbody>
    </table>
   <?php } ?>
   </div>
   </div>
 on db.php I have used to get back on my previous page
    <script>
                    alert('Sheet Created Successfully');
                    window.location.href='index.php?success';

   </script>
</code>```

答:
I cant help you much in your code, maybe you should readjust some things, but, here´s some help:

```<code>$('#firstform').submit(function () {
//handle here a function to send data to db.php, then:
sendData();
$('#firstform').hide();
$('#hidedform').show();
     return false;
    });
</code>```

If you control the submit button not to refresh the page, you can hide first form and display second one. If you post more code I´ll try to be clearer.

("return false" makes submit function not to refresh the page)

here are another post about not refreshing...maybe it helps

Body:
I have one from through which I am entering project name and sheet name which will be saved in project table. Based on this I am inserting empty values on another table 'Data'. I am using editable table to update these empty values in database. I want to hide this table till project name and sheet name is submitted and once value is submitted then only table will be displayed. I have tried a lot but after clicking submit button my table gets displayed till page is reloaded and disappers when loading is completed. My code parts are like below.

    <form class="form-horizontal" action="db.php" id="#form1"
     onSubmit="function();" method="post">

    <input type="text" class="form-control1" name="projectname"
   id="projectname" required >
    <input type="text" class="form-control1" name="sheetname" id="sheetname"
    required >
    <button type="submit" name="submit" id="button" class="btn-
     success btn" >Submit</button>
        </form>

     <?php

       $s4 = "SELECT * FROM data ORDER BY data_id DESC LIMIT 1";
     $res = mysqli_query($bd, $s4);
    while ($row = mysqli_fetch_array($res))
                                 {
                            ?>

    Sr.no
    Column Name

    1
     <td id="d1:<?php echo $row['data_id']; ?>" contenteditable="true"><?php
    echo $row['d1']; ?>

   .
   .
    .

   <?php } ?>

 on db.php I have used to get back on my previous page

Body:
I cant help you much in your code, maybe you should readjust some things, but, here´s some help:

$('#firstform').submit(function () {
//handle here a function to send data to db.php, then:
sendData();
$('#firstform').hide();
$('#hidedform').show();
     return false;
    });

If you control the submit button not to refresh the page, you can hide first form and display second one. If you post more code I´ll try to be clearer.

("return false" makes submit function not to refresh the page)

here are another post about not refreshing...maybe it helps


问:
Bounds does not work for GMSAutocompleteFetcher in Google Place API in iOS Objective C
I made this autocomplete code for searching places. And search correctly but bounds and region not set. show places out of my bounds. </p>

```<code>#import "SearchViewController.h"
#import <GooglePlaces/GooglePlaces.h>
#import <GoogleMaps/GoogleMaps.h>
@import GooglePlaces;

@interface SearchViewController () <GMSAutocompleteViewControllerDelegate,GMSAutocompleteFetcherDelegate>
@end
@implementation SearchViewController{
    UITextField *_textField;
    UITextView *_resultText;
    GMSAutocompleteFetcher* _fetcher;
    GMSPlacesClient *_placesClient;
    GMSCoordinateBounds *_bounds;
    GMSAutocompleteFilter *_filter;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //APIkEy
    [GMSPlacesClient provideAPIKey:@"AIzaSyBYA7KlOZ3VqjQTG4x0R1jaCt9I1-1EVBc"];
_placesClient = [GMSPlacesClient sharedClient];
self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
// Set bounds
    CLLocationCoordinate2D neBoundsCorner = CLLocationCoordinate2DMake(35.818074, 51.586990);
    CLLocationCoordinate2D swBoundsCorner = CLLocationCoordinate2DMake(35.557071, 51.098099);
    _bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:neBoundsCorner coordinate:swBoundsCorner];
// Set up the autocomplete filter.
    _filter = [[GMSAutocompleteFilter alloc] init];
    _filter.type = kGMSPlacesAutocompleteTypeFilterNoFilter;
// Create the fetcher.
    _fetcher = [[GMSAutocompleteFetcher alloc] initWithBounds:_bounds filter:_filter];

    _fetcher.delegate = self;
// Set up the UITextField and UITextView.
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 0, self.view.bounds.size.width - 5.0f, 44.0f)];
    _textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    _resultText =[[UITextView alloc] initWithFrame:CGRectMake(0, 45.0f, self.view.bounds.size.width, self.view.bounds.size.height - 1.0f)];
    _resultText.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f];
    _resultText.text = @"No Results";
    _resultText.editable = NO;

    [self.view addSubview:_textField];
    [self.view addSubview:_resultText];
}

- (void)textFieldDidChange:(UITextField *)textField {
    NSLog(@"%@", textField.text);
    [_fetcher sourceTextHasChanged:textField.text];
}
#pragma mark - GMSAutocompleteFetcherDelegate
- (void)didAutocompleteWithPredictions:(NSArray *)predictions {
    NSMutableString *resultsStr = [NSMutableString string];

    for (GMSAutocompletePrediction *prediction in predictions) {
        [resultsStr appendFormat:@"%@\n", [prediction.attributedPrimaryText string]];
        NSLog(@"sec is: %@",[prediction.attributedSecondaryText string]);
        NSLog(@"placeID is: %@", prediction.placeID );

        [_placesClient lookUpPlaceID:prediction.placeID callback:^(GMSPlace *place, NSError *error) {
            if (error != nil) {
                NSLog(@"Place Details error %@", [error localizedDescription]);
                return;
            }

            if (place != nil) {
                NSLog(@"Place name %@", place.name);
                NSLog(@"Place address %@", place.formattedAddress);
                NSLog(@"Place placeID %@", place.placeID);
                NSLog(@"Place attributions %@", place.attributions);
                NSLog(@"Place latitude %f", place.coordinate.latitude);
                NSLog(@"Place longitude %f", place.coordinate.longitude);
            } else {
                NSLog(@"No place details for %@", prediction.placeID);
            }
        }];

    }
_resultText.text = resultsStr;
}
</code>```

答: Setting the bounds only biases results to that rectangle, it isn't a strict restrict.</p>

Body:
I made this autocomplete code for searching places. And search correctly but bounds and region not set. show places out of my bounds.

#import "SearchViewController.h"
#import <GooglePlaces/GooglePlaces.h>
#import <GoogleMaps/GoogleMaps.h>
@import GooglePlaces;

@interface SearchViewController () <GMSAutocompleteViewControllerDelegate,GMSAutocompleteFetcherDelegate>
@end
@implementation SearchViewController{
    UITextField *_textField;
    UITextView *_resultText;
    GMSAutocompleteFetcher* _fetcher;
    GMSPlacesClient *_placesClient;
    GMSCoordinateBounds *_bounds;
    GMSAutocompleteFilter *_filter;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //APIkEy
    [GMSPlacesClient provideAPIKey:@"AIzaSyBYA7KlOZ3VqjQTG4x0R1jaCt9I1-1EVBc"];
_placesClient = [GMSPlacesClient sharedClient];
self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
// Set bounds
    CLLocationCoordinate2D neBoundsCorner = CLLocationCoordinate2DMake(35.818074, 51.586990);
    CLLocationCoordinate2D swBoundsCorner = CLLocationCoordinate2DMake(35.557071, 51.098099);
    _bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:neBoundsCorner coordinate:swBoundsCorner];
// Set up the autocomplete filter.
    _filter = [[GMSAutocompleteFilter alloc] init];
    _filter.type = kGMSPlacesAutocompleteTypeFilterNoFilter;
// Create the fetcher.
    _fetcher = [[GMSAutocompleteFetcher alloc] initWithBounds:_bounds filter:_filter];

    _fetcher.delegate = self;
// Set up the UITextField and UITextView.
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 0, self.view.bounds.size.width - 5.0f, 44.0f)];
    _textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    _resultText =[[UITextView alloc] initWithFrame:CGRectMake(0, 45.0f, self.view.bounds.size.width, self.view.bounds.size.height - 1.0f)];
    _resultText.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f];
    _resultText.text = @"No Results";
    _resultText.editable = NO;

    [self.view addSubview:_textField];
    [self.view addSubview:_resultText];
}

- (void)textFieldDidChange:(UITextField *)textField {
    NSLog(@"%@", textField.text);
    [_fetcher sourceTextHasChanged:textField.text];
}
#pragma mark - GMSAutocompleteFetcherDelegate
- (void)didAutocompleteWithPredictions:(NSArray *)predictions {
    NSMutableString *resultsStr = [NSMutableString string];

    for (GMSAutocompletePrediction *prediction in predictions) {
        [resultsStr appendFormat:@"%@\n", [prediction.attributedPrimaryText string]];
        NSLog(@"sec is: %@",[prediction.attributedSecondaryText string]);
        NSLog(@"placeID is: %@", prediction.placeID );

        [_placesClient lookUpPlaceID:prediction.placeID callback:^(GMSPlace *place, NSError *error) {
            if (error != nil) {
                NSLog(@"Place Details error %@", [error localizedDescription]);
                return;
            }

            if (place != nil) {
                NSLog(@"Place name %@", place.name);
                NSLog(@"Place address %@", place.formattedAddress);
                NSLog(@"Place placeID %@", place.placeID);
                NSLog(@"Place attributions %@", place.attributions);
                NSLog(@"Place latitude %f", place.coordinate.latitude);
                NSLog(@"Place longitude %f", place.coordinate.longitude);
            } else {
                NSLog(@"No place details for %@", prediction.placeID);
            }
        }];

    }
_resultText.text = resultsStr;
}


问:
SQL Server 2005 Foreign Keys and Indices
I have a general question regarding table indices on foreign keys in database modeling. If I have a table, TABLE_A, created as:

```<code>CREATE TABLE [dbo].[TABLE_A](
 [ID] [int] IDENTITY(1,1) NOT NULL,
    [RelatedTableBID] [int] NOT NULL,
    CONSTRAINT [PK__TABLE_A] PRIMARY KEY CLUSTERED
    (
      [ID] ASC
     ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
     ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[TABLE_A]  WITH CHECK
ADD  CONSTRAINT [TABLE_A__RelatedTableB]
FOREIGN KEY([RelatedTableBID])
REFERENCES [dbo].[TABLE_B] ([ID])
</code>```

and Table_B as:

```<code>CREATE TABLE [dbo].[TABLE_B](
 [ID] [int] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK__TABLE_B] PRIMARY KEY CLUSTERED
    (
      [ID] ASC
     ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
     ON [PRIMARY]
) ON [PRIMARY]
</code>```

Will it in practice be more efficient if I create an index on the referencing table (Table A) referencing column (RelatedTableBID)? As in:

```<code>CREATE INDEX TABLE_A_FK_INDEX1 on TABLE_A(RelatedTableBID)
</code>```

Or am I thinking about this backwards? It seems that since the column being referenced is itself a clustered index, there shouldn't be any issues during joins - if anything, only deletes from TABLE_B seem susceptible to poor performance.

Thanks for any help in setting me straight.

-Mustafa

EDIT

So, in general, if I'm ever joining on or using a column in a where clause consistently when querying, should I consider adding an index on it? What are some best practices and "rules of thumb" for creating database indexes? Sounds like that's a generally sound decision.

答: You've got it right. That index on the foreign key should help whenever you need to join TABLE_A and TABLE_B.</p>

Body:
I have a general question regarding table indices on foreign keys in database modeling. If I have a table, TABLE_A, created as:

CREATE TABLE [dbo].[TABLE_A](
 [ID] [int] IDENTITY(1,1) NOT NULL,
    [RelatedTableBID] [int] NOT NULL,
    CONSTRAINT [PK__TABLE_A] PRIMARY KEY CLUSTERED
    (
      [ID] ASC
     ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
     ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[TABLE_A]  WITH CHECK
ADD  CONSTRAINT [TABLE_A__RelatedTableB]
FOREIGN KEY([RelatedTableBID])
REFERENCES [dbo].[TABLE_B] ([ID])

and Table_B as:

CREATE TABLE [dbo].[TABLE_B](
 [ID] [int] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK__TABLE_B] PRIMARY KEY CLUSTERED
    (
      [ID] ASC
     ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
     ON [PRIMARY]
) ON [PRIMARY]

Will it in practice be more efficient if I create an index on the referencing table (Table A) referencing column (RelatedTableBID)? As in:

CREATE INDEX TABLE_A_FK_INDEX1 on TABLE_A(RelatedTableBID)

Or am I thinking about this backwards? It seems that since the column being referenced is itself a clustered index, there shouldn't be any issues during joins - if anything, only deletes from TABLE_B seem susceptible to poor performance.

Thanks for any help in setting me straight.

-Mustafa

EDIT

So, in general, if I'm ever joining on or using a column in a where clause consistently when querying, should I consider adding an index on it? What are some best practices and "rules of thumb" for creating database indexes? Sounds like that's a generally sound decision.


问:
SSL HANDSHAKE FAILURE: A signer with SubjectDN CN=*.facebook.com
I am using Liberty 16.0.0.4 and i want to get image from facebook account image so i ran this next command to add facebook certificate to Liberty server

```<code>keytool  -importcert -keystore /pathToServer/Servers/'03- Liberty 16.0.0.4'/wlp/usr/servers/MyProjectServer/resources/key.jks -file facebook.crt -alias facebooksigner
</code>```

and the certificate successfully added to liberty key.jks file and i see it when list certificates on this file.

But my problem when i try to get image using URL url = new URL(pictureUrl);

it fires

[ERROR   ] CWPKI0022E: SSL HANDSHAKE FAILURE:  A signer with SubjectDN CN=*.facebook.com, O="Facebook, Inc.", L=Menlo Park, ST=California, C=US was sent from the target host.

Note: i added <keyStore id="defaultKeyStore" password="{xor}EzY9Oi0rJg=="/> into server.xml

So can u guess why this happen? thanks :)

答:
For SSL to work, the client needs to trust the chain that the server presents to it - from the top (root) level all the way down.

You say that you've put a Facebook cert into your trust store, but is the full chain trusted? At the very least, the root CA that signed the Facebook cert needs to be in the trust store.

Body:
I am using Liberty 16.0.0.4 and i want to get image from facebook account image so i ran this next command to add facebook certificate to Liberty server

keytool  -importcert -keystore /pathToServer/Servers/'03- Liberty 16.0.0.4'/wlp/usr/servers/MyProjectServer/resources/key.jks -file facebook.crt -alias facebooksigner

and the certificate successfully added to liberty key.jks file and i see it when list certificates on this file.

But my problem when i try to get image using URL url = new URL(pictureUrl);

it fires

[ERROR   ] CWPKI0022E: SSL HANDSHAKE FAILURE:  A signer with SubjectDN CN=*.facebook.com, O="Facebook, Inc.", L=Menlo Park, ST=California, C=US was sent from the target host.

Note: i added <keyStore id="defaultKeyStore" password="{xor}EzY9Oi0rJg=="/> into server.xml

So can u guess why this happen? thanks :)


答:
You have to use setTimeout to call a function once with a delay.

setInterval will call that function an unlimited number of times every delay milliseconds.

If what you are trying to achieve is printing an item, then another after delay milliseconds, and so on, this is a way to achieve it (manually incrementing the delay for each item):

```<code>var list = [1, 2, 3, 4, 5];
var delay = 400;

function delayedPrint(text, delay = 1000) {
    setTimeout(function() {
        console.log(text);
    }, delay)
}

list.map(function(this_list_item, index) {
    delayedPrint(this_list_item, index * delay);
});
</code>```

By the way, as Nina correctly points out, map may not be the best choice to convey what you are doing here, and forEach would be clearer:

```<code>list.forEach(function(this_list_item, index) {
    delayedPrint(this_list_item, index * delay);
});
</code>```

Title: setInterval usage causes strange infinite loop

Body:
You have to use setTimeout to call a function once with a delay.

setInterval will call that function an unlimited number of times every delay milliseconds.

If what you are trying to achieve is printing an item, then another after delay milliseconds, and so on, this is a way to achieve it (manually incrementing the delay for each item):

var list = [1, 2, 3, 4, 5];
var delay = 400;

function delayedPrint(text, delay = 1000) {
    setTimeout(function() {
        console.log(text);
    }, delay)
}

list.map(function(this_list_item, index) {
    delayedPrint(this_list_item, index * delay);
});

By the way, as Nina correctly points out, map may not be the best choice to convey what you are doing here, and forEach would be clearer:

list.forEach(function(this_list_item, index) {
    delayedPrint(this_list_item, index * delay);
});


问:
Send Textviews throught Whatsapp
I need to send all textview of a layout as string through whatsapp method, but if the textview is null must send a blank text.

this is my code:

```<code>public void sendButton(View view) {
    // Do something in response to button

    PackageManager pm = getPackageManager();
    try {

        TextView textview3 = (TextView) findViewById(R.id.textAmor3);
        TextView textview2 = (TextView) findViewById(R.id.textAmor2);

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");

        if (textview3 == null) {

        } else {

        }

        String both = textview2 + "-" + textview3;

        PackageInfo info = pm.getPackageInfo("com.whatsapp",
        PackageManager.GET_META_DATA);
        //Check if package exists or not. If not then code
        //in catch block will be called
        waIntent.setPackage("com.whatsapp");

        waIntent.putExtra(Intent.EXTRA_TEXT, both );

        startActivity(Intent.createChooser(waIntent, "Share with"));

    } catch (PackageManager.NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
    }
}
}
</code>```

What do i must to do ?

thanks

答:
You can't share Textviews with any app. you can share text written on that Textviews. so get Text using textview3.getText().toString() and then pass that to what's app Intent.

```<code>Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");

try {
    PackageInfo info = pm.getPackageInfo("com.whatsapp",
    PackageManager.GET_META_DATA);
    //Check if package exists or not. If not then code
    //in catch block will be called
    waIntent.setPackage("com.whatsapp");

    waIntent.putExtra(Intent.EXTRA_TEXT, "textString here" );

    startActivity(Intent.createChooser(waIntent, "Share with"));

} catch (PackageManager.NameNotFoundException e) {
    Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
            .show();
}
</code>```

Title: Send Textviews throught Whatsapp

Body:
I need to send all textview of a layout as string through whatsapp method, but if the textview is null must send a blank text.

this is my code:

public void sendButton(View view) {
    // Do something in response to button

    PackageManager pm = getPackageManager();
    try {

        TextView textview3 = (TextView) findViewById(R.id.textAmor3);
        TextView textview2 = (TextView) findViewById(R.id.textAmor2);

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");

        if (textview3 == null) {

        } else {

        }

        String both = textview2 + "-" + textview3;

        PackageInfo info = pm.getPackageInfo("com.whatsapp",
        PackageManager.GET_META_DATA);
        //Check if package exists or not. If not then code
        //in catch block will be called
        waIntent.setPackage("com.whatsapp");

        waIntent.putExtra(Intent.EXTRA_TEXT, both );

        startActivity(Intent.createChooser(waIntent, "Share with"));

    } catch (PackageManager.NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
    }
}
}

What do i must to do ?

thanks

Body:
You can't share Textviews with any app. you can share text written on that Textviews. so get Text using textview3.getText().toString() and then pass that to what's app Intent.

Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");

try {
    PackageInfo info = pm.getPackageInfo("com.whatsapp",
    PackageManager.GET_META_DATA);
    //Check if package exists or not. If not then code
    //in catch block will be called
    waIntent.setPackage("com.whatsapp");

    waIntent.putExtra(Intent.EXTRA_TEXT, "textString here" );

    startActivity(Intent.createChooser(waIntent, "Share with"));

} catch (PackageManager.NameNotFoundException e) {
    Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
            .show();
}


问:
PUT request (JAVA) with HttpUrlConnection
I'm trying to do a "PUT" request with Android Studio.
But, actually, it doesn't work, I received a "404 not found" whereas I got all the needed infos.

String url = "https://[...]";

```<code>        URL obj = null;
        try {
            obj = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        HttpURLConnection con = null;
        DataOutputStream dataOutputStream = null;
        try {
            con = (HttpURLConnection) obj.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // optional default is GET
        try {
            con.setRequestMethod("PUT");
            con.setDoInput(true);
            con.setDoOutput(true);
            System.out.println("Info User to update : " + params[0]);

            con.setRequestProperty("X-Auth-Token", params[0].get("token"));
            [...]

            con.setRequestProperty("shop_id", params[1].get("id"));

            dataOutputStream = new DataOutputStream(con.getOutputStream());
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
            osw.flush();
            osw.close();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.flush();
                    dataOutputStream.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }

        int responseCode = 0;
        try {
            responseCode = con.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

If I try the request on Symfony (web app), it's worked well, but with the code, not anymore... Do you see any problems with my request ?

答: Problem solved, I was able to do what I wanted using a PATCH request instead.</p>

Body:
I'm trying to do a "PUT" request with Android Studio.
But, actually, it doesn't work, I received a "404 not found" whereas I got all the needed infos.

String url = "https://[...]";

        URL obj = null;
        try {
            obj = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        HttpURLConnection con = null;
        DataOutputStream dataOutputStream = null;
        try {
            con = (HttpURLConnection) obj.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // optional default is GET
        try {
            con.setRequestMethod("PUT");
            con.setDoInput(true);
            con.setDoOutput(true);
            System.out.println("Info User to update : " + params[0]);

            con.setRequestProperty("X-Auth-Token", params[0].get("token"));
            [...]

            con.setRequestProperty("shop_id", params[1].get("id"));

            dataOutputStream = new DataOutputStream(con.getOutputStream());
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
            osw.flush();
            osw.close();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.flush();
                    dataOutputStream.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }

        int responseCode = 0;
        try {
            responseCode = con.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }

If I try the request on Symfony (web app), it's worked well, but with the code, not anymore... Do you see any problems with my request ?


答: If you have a method that writes to any state that's shared across multiple threads (for example, static variables, or any objects that multiple threads use), then that method needs to worry about thread-safety, and so do any methods that read any of that shared state.


问:
AspNet core MVC 1.1.3 Default selected radio button
I am trying to default a radio button to be checked.

```<code><div>@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", new { @class = "isActive", @checked="checked"})</div>
<div>@Html.RadioButtonFor(m => m.IsActive, "OofActive", new { @class = "isActive" })</div>
</code>```

Note that the model contains a property

```<code>public bool IsActive { get; set; }
</code>```

I have found the same issue here but for MVC6 although it is closed: https://github.com/aspnet/Mvc/issues/3098

Is this an issue or am I doing something wrong?

答:
The RadioButtonFor() (as do all the HtmlHelper methods) work by binding to the value of your property and its that value which determines which radio button is checked.

Your IsActive property is a bool which has only 2 possible values, true and false and cannot bind to string with values of "OofDeactive" or "OofActive". Change the code to

```<code>@Html.RadioButtonFor(m => m.IsActive, true, new { @class = "isActive", id = "" })
@Html.RadioButtonFor(m => m.IsActive, false, new { @class = "isActive", id = "" })
</code>```

And if the value of property IsActive is true the first radio button will be selected, otherwise the 2nd will be.

Note that the RadioButtonFor() method generates duplicate id attributes so either use new { id = "" } to remove the id attribute (or give them a unique id if needed for some other purpose). Setting the checked attribute is pointless since it will be ignored.

Body:
I am trying to default a radio button to be checked.

@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", new { @class = "isActive", @checked="checked"})

@Html.RadioButtonFor(m => m.IsActive, "OofActive", new { @class = "isActive" })

Note that the model contains a property

public bool IsActive { get; set; }

I have found the same issue here but for MVC6 although it is closed: https://github.com/aspnet/Mvc/issues/3098

Is this an issue or am I doing something wrong?

Body:
The RadioButtonFor() (as do all the HtmlHelper methods) work by binding to the value of your property and its that value which determines which radio button is checked.

Your IsActive property is a bool which has only 2 possible values, true and false and cannot bind to string with values of "OofDeactive" or "OofActive". Change the code to

@Html.RadioButtonFor(m => m.IsActive, true, new { @class = "isActive", id = "" })
@Html.RadioButtonFor(m => m.IsActive, false, new { @class = "isActive", id = "" })

And if the value of property IsActive is true the first radio button will be selected, otherwise the 2nd will be.

Note that the RadioButtonFor() method generates duplicate id attributes so either use new { id = "" } to remove the id attribute (or give them a unique id if needed for some other purpose). Setting the checked attribute is pointless since it will be ignored.


问:
How to encrypt a password field in django
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field.
I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

```<code>class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
</code>```

答:
Django added PasswordInput widget use that to make password field in your template

```<code>from django.forms import ModelForm, PasswordInput

class CrewForm(ModelForm):
    class Meta:
        model = Crew
        fields = '__all__'
        widgets = {
            'crew_password': PasswordInput(),
        }
</code>```

Also as @Exprator suggest to use the make_password to update the password field in view...

```<code>form.crew_password=make_password(crew_password)
form.save()
</code>```

Body:
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field.
I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)

Body:
Django added PasswordInput widget use that to make password field in your template

from django.forms import ModelForm, PasswordInput

class CrewForm(ModelForm):
    class Meta:
        model = Crew
        fields = '__all__'
        widgets = {
            'crew_password': PasswordInput(),
        }

Also as @Exprator suggest to use the make_password to update the password field in view...

form.crew_password=make_password(crew_password)
form.save()


问:
Floating point min/max in CUDA slower than CPU version. Why?
I wrote a kernel for computing the min and max values of an array of about 100,000 floats using reduction (see code below). I use thread blocks to reduce chunks of 1024 values to a single value (in shared memory), and then do the final reduction among the blocks on the CPU.

I then compared this with a serial calculation just on the CPU. The CUDA version takes 2.2ms, and the CPU version takes 0.21ms. Why is the CUDA version much slower? Is the array size not large enough to take advantage of the parallelism, or is my code not optimized somehow?

This is part of an exercise in the Udacity Parallel Programming class. I am running this through their web site, so I don't know what the exact hardware is, but they claim the code runs on actual GPUs.

Here is the CUDA code:

```<code>__global__ void min_max_kernel(const float* const d_logLuminance,
                            const size_t length,
                            float* d_min_logLum,
                            float* d_max_logLum) {
    // Shared working memory
    extern __shared__ float sh_logLuminance[];

    int blockWidth = blockDim.x;
    int x = blockDim.x * blockIdx.x + threadIdx.x;

    float* min_logLuminance = sh_logLuminance;
    float* max_logLuminance = sh_logLuminance + blockWidth;

    // Copy this block's chunk of the data to shared memory
    // We copy twice so we compute min and max at the same time
    if (x < length) {
        min_logLuminance[threadIdx.x] = d_logLuminance[x];
        max_logLuminance[threadIdx.x] = min_logLuminance[threadIdx.x];
    }
    else {
        // Pad if we're out of range
        min_logLuminance[threadIdx.x] = FLT_MAX;
        max_logLuminance[threadIdx.x] = -FLT_MAX;
    }

    __syncthreads();

    // Reduce
    for (int s = blockWidth/2; s > 0; s /= 2) {
        if (threadIdx.x < s) {
            if (min_logLuminance[threadIdx.x + s] < min_logLuminance[threadIdx.x]) {
                min_logLuminance[threadIdx.x] = min_logLuminance[threadIdx.x + s];
            }

            if (max_logLuminance[threadIdx.x + s] > max_logLuminance[threadIdx.x]) {
                max_logLuminance[threadIdx.x] = max_logLuminance[threadIdx.x + s];
            }
        }

        __syncthreads();
    }

    // Write to global memory
    if (threadIdx.x == 0) {
        d_min_logLum[blockIdx.x] = min_logLuminance[0];
        d_max_logLum[blockIdx.x] = max_logLuminance[0];
    }
}

size_t get_num_blocks(size_t inputLength, size_t threadsPerBlock) {
    return inputLength / threadsPerBlock +
        ((inputLength % threadsPerBlock == 0) ? 0 : 1);
}

/*
* Compute min, max over the data by first reducing on the device, then
* doing the final reducation on the host.
*/
void compute_min_max(const float* const d_logLuminance,
                    float& min_logLum,
                    float& max_logLum,
                    const size_t numRows,
                    const size_t numCols) {
    // Compute min, max
    printf("\n=== computing min/max ===\n");
    const size_t blockWidth = 1024;
    const size_t numPixels = numRows * numCols;
    size_t numBlocks = get_num_blocks(numPixels, blockWidth);

    printf("Num min/max blocks = %d\n", numBlocks);

    float* d_min_logLum;
    float* d_max_logLum;
    int alloc_size = sizeof(float) * numBlocks;
    checkCudaErrors(cudaMalloc(&d_min_logLum, alloc_size));
    checkCudaErrors(cudaMalloc(&d_max_logLum, alloc_size));

    min_max_kernel<<<numBlocks, blockWidth, sizeof(float) * blockWidth * 2>>>
        (d_logLuminance, numPixels, d_min_logLum, d_max_logLum);

    float* h_min_logLum = (float*) malloc(alloc_size);
    float* h_max_logLum = (float*) malloc(alloc_size);
    checkCudaErrors(cudaMemcpy(h_min_logLum, d_min_logLum, alloc_size, cudaMemcpyDeviceToHost));
    checkCudaErrors(cudaMemcpy(h_max_logLum, d_max_logLum, alloc_size, cudaMemcpyDeviceToHost));

    min_logLum = FLT_MAX;
    max_logLum = -FLT_MAX;

    // Reduce over the block results
    // (would be a bit faster to do it on the GPU, but it's just 96 numbers)
    for (int i = 0; i < numBlocks; i++) {
        if (h_min_logLum[i] < min_logLum) {
            min_logLum = h_min_logLum[i];
        }
        if (h_max_logLum[i] > max_logLum) {
            max_logLum = h_max_logLum[i];
        }
    }

    printf("min_logLum = %.2f\nmax_logLum = %.2f\n", min_logLum, max_logLum);

    checkCudaErrors(cudaFree(d_min_logLum));
    checkCudaErrors(cudaFree(d_max_logLum));
    free(h_min_logLum);
    free(h_max_logLum);
}
</code>```

And here is the host version:

```<code>void compute_min_max_on_host(const float* const d_logLuminance, size_t numPixels) {
    int alloc_size = sizeof(float) * numPixels;
    float* h_logLuminance = (float*) malloc(alloc_size);
    checkCudaErrors(cudaMemcpy(h_logLuminance, d_logLuminance, alloc_size, cudaMemcpyDeviceToHost));
    float host_min_logLum = FLT_MAX;
    float host_max_logLum = -FLT_MAX;
    printf("HOST ");
    for (int i = 0; i < numPixels; i++) {
        if (h_logLuminance[i] < host_min_logLum) {
            host_min_logLum = h_logLuminance[i];
        }
        if (h_logLuminance[i] > host_max_logLum) {
            host_max_logLum = h_logLuminance[i];
        }
    }
    printf("host_min_logLum = %.2f\nhost_max_logLum = %.2f\n",
        host_min_logLum, host_max_logLum);
    free(h_logLuminance);
}
</code>```

答:
As @talonmies suggests, behavior may be different for larger sizes; 100,000 is really not that much: Much of it fits within the combined overall L1 cache of the cores on a modern CPU; half of it fits in a single core's L2 cache.

Transfer over PCI express takes time; and in your case, double the time it might have, since you don't use pinned memory.

You're not overlapping computation and PCI express I/O (not that it would make much sense for only 100,000 elements)

Your kernel is rather slow, for more than one reason; not the least of which is the extensive use of shared memory, most of which is unnecessary

More generally: Always profile your code using nvvp (or nvprof for getting textual information for further analysis).

Body:
I wrote a kernel for computing the min and max values of an array of about 100,000 floats using reduction (see code below). I use thread blocks to reduce chunks of 1024 values to a single value (in shared memory), and then do the final reduction among the blocks on the CPU.

I then compared this with a serial calculation just on the CPU. The CUDA version takes 2.2ms, and the CPU version takes 0.21ms. Why is the CUDA version much slower? Is the array size not large enough to take advantage of the parallelism, or is my code not optimized somehow?

This is part of an exercise in the Udacity Parallel Programming class. I am running this through their web site, so I don't know what the exact hardware is, but they claim the code runs on actual GPUs.

Here is the CUDA code:

__global__ void min_max_kernel(const float* const d_logLuminance,
                            const size_t length,
                            float* d_min_logLum,
                            float* d_max_logLum) {
    // Shared working memory
    extern __shared__ float sh_logLuminance[];

    int blockWidth = blockDim.x;
    int x = blockDim.x * blockIdx.x + threadIdx.x;

    float* min_logLuminance = sh_logLuminance;
    float* max_logLuminance = sh_logLuminance + blockWidth;

    // Copy this block's chunk of the data to shared memory
    // We copy twice so we compute min and max at the same time
    if (x < length) {
        min_logLuminance[threadIdx.x] = d_logLuminance[x];
        max_logLuminance[threadIdx.x] = min_logLuminance[threadIdx.x];
    }
    else {
        // Pad if we're out of range
        min_logLuminance[threadIdx.x] = FLT_MAX;
        max_logLuminance[threadIdx.x] = -FLT_MAX;
    }

    __syncthreads();

    // Reduce
    for (int s = blockWidth/2; s > 0; s /= 2) {
        if (threadIdx.x < s) {
            if (min_logLuminance[threadIdx.x + s] < min_logLuminance[threadIdx.x]) {
                min_logLuminance[threadIdx.x] = min_logLuminance[threadIdx.x + s];
            }

            if (max_logLuminance[threadIdx.x + s] > max_logLuminance[threadIdx.x]) {
                max_logLuminance[threadIdx.x] = max_logLuminance[threadIdx.x + s];
            }
        }

        __syncthreads();
    }

    // Write to global memory
    if (threadIdx.x == 0) {
        d_min_logLum[blockIdx.x] = min_logLuminance[0];
        d_max_logLum[blockIdx.x] = max_logLuminance[0];
    }
}

size_t get_num_blocks(size_t inputLength, size_t threadsPerBlock) {
    return inputLength / threadsPerBlock +
        ((inputLength % threadsPerBlock == 0) ? 0 : 1);
}

/*
* Compute min, max over the data by first reducing on the device, then
* doing the final reducation on the host.
*/
void compute_min_max(const float* const d_logLuminance,
                    float& min_logLum,
                    float& max_logLum,
                    const size_t numRows,
                    const size_t numCols) {
    // Compute min, max
    printf("\n=== computing min/max ===\n");
    const size_t blockWidth = 1024;
    const size_t numPixels = numRows * numCols;
    size_t numBlocks = get_num_blocks(numPixels, blockWidth);

    printf("Num min/max blocks = %d\n", numBlocks);

    float* d_min_logLum;
    float* d_max_logLum;
    int alloc_size = sizeof(float) * numBlocks;
    checkCudaErrors(cudaMalloc(&d_min_logLum, alloc_size));
    checkCudaErrors(cudaMalloc(&d_max_logLum, alloc_size));

    min_max_kernel<<<numBlocks, blockWidth, sizeof(float) * blockWidth * 2>>>
        (d_logLuminance, numPixels, d_min_logLum, d_max_logLum);

    float* h_min_logLum = (float*) malloc(alloc_size);
    float* h_max_logLum = (float*) malloc(alloc_size);
    checkCudaErrors(cudaMemcpy(h_min_logLum, d_min_logLum, alloc_size, cudaMemcpyDeviceToHost));
    checkCudaErrors(cudaMemcpy(h_max_logLum, d_max_logLum, alloc_size, cudaMemcpyDeviceToHost));

    min_logLum = FLT_MAX;
    max_logLum = -FLT_MAX;

    // Reduce over the block results
    // (would be a bit faster to do it on the GPU, but it's just 96 numbers)
    for (int i = 0; i < numBlocks; i++) {
        if (h_min_logLum[i] < min_logLum) {
            min_logLum = h_min_logLum[i];
        }
        if (h_max_logLum[i] > max_logLum) {
            max_logLum = h_max_logLum[i];
        }
    }

    printf("min_logLum = %.2f\nmax_logLum = %.2f\n", min_logLum, max_logLum);

    checkCudaErrors(cudaFree(d_min_logLum));
    checkCudaErrors(cudaFree(d_max_logLum));
    free(h_min_logLum);
    free(h_max_logLum);
}

And here is the host version:

void compute_min_max_on_host(const float* const d_logLuminance, size_t numPixels) {
    int alloc_size = sizeof(float) * numPixels;
    float* h_logLuminance = (float*) malloc(alloc_size);
    checkCudaErrors(cudaMemcpy(h_logLuminance, d_logLuminance, alloc_size, cudaMemcpyDeviceToHost));
    float host_min_logLum = FLT_MAX;
    float host_max_logLum = -FLT_MAX;
    printf("HOST ");
    for (int i = 0; i < numPixels; i++) {
        if (h_logLuminance[i] < host_min_logLum) {
            host_min_logLum = h_logLuminance[i];
        }
        if (h_logLuminance[i] > host_max_logLum) {
            host_max_logLum = h_logLuminance[i];
        }
    }
    printf("host_min_logLum = %.2f\nhost_max_logLum = %.2f\n",
        host_min_logLum, host_max_logLum);
    free(h_logLuminance);
}


问:
Calculating categorical average with filtered data
I have following dataset:

```<code>A -1
A 10
B  8
D -1
A  0
A  4
B  2
C  6
</code>```

And I want to add column to it like this:

```<code>A -1 4,6
A 10 4,6
B  8 5,0
D -1 5,0
A  0 4,6
A  4 4,6
B  2 5,0
C  6 6,0
</code>```

What have happened here?

Well I have calculated average of each categorical letter variable but ignoring negative numbers and given this as new columns value.

If there is only negative values for category I have given value of total average (ignoring negative values).

In SQL this would have been done with filtered group funcion followed with join. In excel this would be conditional vlookup. How I do this in R?

Edit:

```<code># Create dataset
category <- c("A","A","B","D","A","A","B","C")
value <- c(-1,10,8,-1,0,4,2,6)
dataset <- data.frame(category, value)

# Calculated means

fdata <- dataset[dataset[,'value']>-1,]
aggregate(fdata[,2], list(fdata$category), mean)
</code>```

答:
Using dplyr</p>

```<code>dataset %>%
  mutate(
    x = ifelse(value < 0, NA_integer_, value),
    meanAll = mean(x, na.rm = TRUE)) %>%
  group_by(category) %>%
  mutate(meanGroup = mean(x, na.rm = TRUE),
         meanGroup = ifelse(is.nan(meanGroup), meanAll, meanGroup))

# Source: local data frame [8 x 5]
# Groups: category [4]
#
# # A tibble: 8 x 5
#   category value     x meanAll meanGroup
#     <fctr> <dbl> <dbl>   <dbl>     <dbl>
# 1        A    -1    NA       5  4.666667
# 2        A    10    10       5  4.666667
# 3        B     8     8       5  5.000000
# 4        D    -1    NA       5  5.000000
# 5        A     0     0       5  4.666667
# 6        A     4     4       5  4.666667
# 7        B     2     2       5  5.000000
# 8        C     6     6       5  6.000000
</code>```

Body:
I have following dataset:

A -1
A 10
B  8
D -1
A  0
A  4
B  2
C  6

And I want to add column to it like this:

A -1 4,6
A 10 4,6
B  8 5,0
D -1 5,0
A  0 4,6
A  4 4,6
B  2 5,0
C  6 6,0

What have happened here?

Well I have calculated average of each categorical letter variable but ignoring negative numbers and given this as new columns value.

If there is only negative values for category I have given value of total average (ignoring negative values).

In SQL this would have been done with filtered group funcion followed with join. In excel this would be conditional vlookup. How I do this in R?

Edit:

# Create dataset
category <- c("A","A","B","D","A","A","B","C")
value <- c(-1,10,8,-1,0,4,2,6)
dataset <- data.frame(category, value)

# Calculated means

fdata <- dataset[dataset[,'value']>-1,]
aggregate(fdata[,2], list(fdata$category), mean)

Body:
Using dplyr

dataset %>%
  mutate(
    x = ifelse(value < 0, NA_integer_, value),
    meanAll = mean(x, na.rm = TRUE)) %>%
  group_by(category) %>%
  mutate(meanGroup = mean(x, na.rm = TRUE),
         meanGroup = ifelse(is.nan(meanGroup), meanAll, meanGroup))

# Source: local data frame [8 x 5]
# Groups: category [4]
#
# # A tibble: 8 x 5
#   category value     x meanAll meanGroup
#     <fctr> <dbl> <dbl>   <dbl>     <dbl>
# 1        A    -1    NA       5  4.666667
# 2        A    10    10       5  4.666667
# 3        B     8     8       5  5.000000
# 4        D    -1    NA       5  5.000000
# 5        A     0     0       5  4.666667
# 6        A     4     4       5  4.666667
# 7        B     2     2       5  5.000000
# 8        C     6     6       5  6.000000