问:
jquery can't alert ajax response
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

```<code>    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }
</code>```

However, if the above code was written without

```<code>    if (response == 'false') {

    }
</code>```

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

答:
You don't need the double (" ") quotes for a boolean value.

```<code>if (response == false) {
  alert(response);
}
</code>```

You can use:

```<code> error: function(response){
    alert(response);
 }
</code>```

Title: jquery can't alert ajax response

Body:
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }

However, if the above code was written without

    if (response == 'false') {

    }

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

Body:
You don't need the double (" ") quotes for a boolean value.

if (response == false) {
  alert(response);
}

You can use:

 error: function(response){
    alert(response);
 }


来源: stackexchange

问:
Cocoa macro-- unique question
I need help with a #define to do the following:

```<code>for (int i = 0; i < 47; ++i)  {     SETLABEL(i)     }
</code>```

the SETLABEL() macro should take the intValue of "i" and paste it into a label name:

when i == 1-->    label1.text = (stuff)

when i == 2-->    label2.text = (stuff)

Is this possible? The following fails miserably, because it pastes "i" in, rather than the value of "i":

```<code>#define SETLABEL(x)    [label##x setText: [foo stringValue]];
</code>```

EDIT:  Thanks for all the help. My code looks like this now:

the declaration for the int is iB[25]

```<code>-(void)stuff {
int x;
int labelGo = 1;

for (int i = 1; i < 25; ++i) {
    NSString * labelName = [NSString stringWithFormat:@"magicItemBoughtTot%d", i];
    UILabel * currentLabel = [self valueForKey:labelName];
    if (iB[i] == itemPH) { // if label is not empty
        [currentLabel setText: [NSString stringWithFormat:@"%i",
                                        ([currentLabel.text intValue] + 1)]];
        labelGo = 0;
    }
}
utilityNum = nil;
utilityNum = [NSNumber numberWithInt:labelGo];
</code>```

}

答:
The "real" answer to this question is to declare your labels with @property (which they probably already are), and then do:

```<code>for (int i = 0; i < 47; ++i) {
  NSString * labelName = [NSString stringWithFormat:@"label%d", i];
  UILabel * currentLabel = [self valueForKey:labelName];
  [currentLabel setText:(stuff)];
}
</code>```

However, the real question here is: Why on earth do you have 47 labels that are all showing the same thing, and why on earth don't they have better names?

edit retrieving primitives:

While it's possible to retrieve the values of primitive ivars using stuff like valueForKey: or object_getInstanceVariable(), the fact that you're requesting this is (in my book) a sign of poorly designed code.  Even without looking at your code, I guarantee you that there's a better way to be doing this.

That being said, here's a loaded gun on how to get primitive values out of instance variables by name:

```<code>#import <objc/runtime.h>

//self has an ivar named "i"
int *iPtr = 0;
object_getInstanceVariable(self, "i", (void**)&iPtr);
NSLog(@"%d", (int)iPtr);
</code>```

However, if you ever use this code in a production environment for anything beyond explicitly debugging something, then I'd say you deserve any crashes you get.  (Not that this code is crash-prone, but rather that it'd be probably be representative of the rest of the code)

ContentLicense: CC BY-SA 2.5

Title: Cocoa macro-- unique question

Body:
I need help with a #define to do the following:

for (int i = 0; i < 47; ++i)  {     SETLABEL(i)     }

the SETLABEL() macro should take the intValue of "i" and paste it into a label name:

when i == 1-->    label1.text = (stuff)

when i == 2-->    label2.text = (stuff)

Is this possible? The following fails miserably, because it pastes "i" in, rather than the value of "i":

#define SETLABEL(x)    [label##x setText: [foo stringValue]];

EDIT:  Thanks for all the help. My code looks like this now:

the declaration for the int is iB[25]

-(void)stuff {
int x;
int labelGo = 1;

for (int i = 1; i < 25; ++i) {
    NSString * labelName = [NSString stringWithFormat:@"magicItemBoughtTot%d", i];
    UILabel * currentLabel = [self valueForKey:labelName];
    if (iB[i] == itemPH) { // if label is not empty
        [currentLabel setText: [NSString stringWithFormat:@"%i",
                                        ([currentLabel.text intValue] + 1)]];
        labelGo = 0;
    }
}
utilityNum = nil;
utilityNum = [NSNumber numberWithInt:labelGo];

}

Body:
The "real" answer to this question is to declare your labels with @property (which they probably already are), and then do:

for (int i = 0; i < 47; ++i) {
  NSString * labelName = [NSString stringWithFormat:@"label%d", i];
  UILabel * currentLabel = [self valueForKey:labelName];
  [currentLabel setText:(stuff)];
}

However, the real question here is: Why on earth do you have 47 labels that are all showing the same thing, and why on earth don't they have better names?

edit retrieving primitives:

While it's possible to retrieve the values of primitive ivars using stuff like valueForKey: or object_getInstanceVariable(), the fact that you're requesting this is (in my book) a sign of poorly designed code.  Even without looking at your code, I guarantee you that there's a better way to be doing this.

That being said, here's a loaded gun on how to get primitive values out of instance variables by name:

#import <objc/runtime.h>

//self has an ivar named "i"
int *iPtr = 0;
object_getInstanceVariable(self, "i", (void**)&iPtr);
NSLog(@"%d", (int)iPtr);

However, if you ever use this code in a production environment for anything beyond explicitly debugging something, then I'd say you deserve any crashes you get.  (Not that this code is crash-prone, but rather that it'd be probably be representative of the rest of the code)


问:
IIS not finding an external DLL
I have a C# .NET Core WebAPI and I'm using IIS. In my code I load an external DLL at runtime, like this:

```<code>var res = new LoadMyDLL("mydll.dll");
</code>```

I have to do it because the LoadMyDLL function accepts a string which is the path to the DLL itself. Ideally I'd like to have the DLL in the same folder as the main app so that's why no path is provided, just the name of the dll file.

Now, when I run the application in console mode everything is file, the dll is in the same folder of the main .exe. When I run the application as a class library in IIS it doesn't find the dll anymore. What's the working dir when running under IIS? What could be a post build step in VS2015 to copy the dll into the correct IIS folder?

答:
For ASP.NET websites, the root directory is the project directory. If it's hosted in IIS, there should be a web.config inside it.

Here you can put where your library DLLs will be copied:

ContentLicense: CC BY-SA 3.0

Title: IIS not finding an external DLL

Body:
I have a C# .NET Core WebAPI and I'm using IIS. In my code I load an external DLL at runtime, like this:

var res = new LoadMyDLL("mydll.dll");

I have to do it because the LoadMyDLL function accepts a string which is the path to the DLL itself. Ideally I'd like to have the DLL in the same folder as the main app so that's why no path is provided, just the name of the dll file.

Now, when I run the application in console mode everything is file, the dll is in the same folder of the main .exe. When I run the application as a class library in IIS it doesn't find the dll anymore. What's the working dir when running under IIS? What could be a post build step in VS2015 to copy the dll into the correct IIS folder?


问:
How to reference another put action method in the same controller file?
my project involves two models - User and Request - where a user can create a food delivery request and attach tokens as rewards, while another user can help to deliver and claim the tokens.

In the same controller.js file, I have a method transferTokens (put action) and another delete (delete action) method. My question is how can I call the delete method at the end of transferTokens? I am separating both methods as there would be instances where user can delete his own requests without any token transfer (that is, before any other user agrees to deliver that request).

The code is:

```<code>let controller = {
  transferTokens: (req, res) => {
   // Request.findOne({ _id: req.params.id })
   // ...
   // User.findOneAndUpdate...
   // ... add tokens to user-helper
   // controller.delete();
  },
  delete: (req,res) => {
   // Request.findOneAndRemove
   // ...
   // res.redirect('/home');
  }
}
module.exports = controller
</code>```

So, this is definitely wrong. The request does get deleted, but the error message is res is undefined. Usually, the user clicks on the delete button in the view, but in this case, the user-helper clicks on the 'claim tokens' button which initiates the transferTokens put action.

edit: I managed to find a way out using app.set

app.set('res', res);
controller.delete(req, app.get('res'))

答:
// please specify more clearly</p>

```<code>transferTokens :function(req,res){
   var model = req.allParams();

   Request
   .findOne({ _id: req.params.id })
   .exec(function(err,request){
      if(err) err

      if(request){

        //in this you should match any condition with your another table
        // so supose we have User table
        var userFilter ={
         id :request.id(as ur key)
        }

        User
        .findOne(userFilter)
        .exec(function(err,user){
           if(err) return err

           if(user){
             user.destroy(function (err) {
                                if (err) return res.toJson(false, [], "Error.");

                                return res.toJson(true, user, "Sucess.");
                            });
           }
        })

      }
      else{
        return  empty
      }
   })
}
</code>```

Body:
my project involves two models - User and Request - where a user can create a food delivery request and attach tokens as rewards, while another user can help to deliver and claim the tokens.

In the same controller.js file, I have a method transferTokens (put action) and another delete (delete action) method. My question is how can I call the delete method at the end of transferTokens? I am separating both methods as there would be instances where user can delete his own requests without any token transfer (that is, before any other user agrees to deliver that request).

The code is:

let controller = {
  transferTokens: (req, res) => {
   // Request.findOne({ _id: req.params.id })
   // ...
   // User.findOneAndUpdate...
   // ... add tokens to user-helper
   // controller.delete();
  },
  delete: (req,res) => {
   // Request.findOneAndRemove
   // ...
   // res.redirect('/home');
  }
}
module.exports = controller

So, this is definitely wrong. The request does get deleted, but the error message is res is undefined. Usually, the user clicks on the delete button in the view, but in this case, the user-helper clicks on the 'claim tokens' button which initiates the transferTokens put action.

edit: I managed to find a way out using app.set

app.set('res', res);
controller.delete(req, app.get('res'))

Body:
// please specify more clearly

transferTokens :function(req,res){
   var model = req.allParams();

   Request
   .findOne({ _id: req.params.id })
   .exec(function(err,request){
      if(err) err

      if(request){

        //in this you should match any condition with your another table
        // so supose we have User table
        var userFilter ={
         id :request.id(as ur key)
        }

        User
        .findOne(userFilter)
        .exec(function(err,user){
           if(err) return err

           if(user){
             user.destroy(function (err) {
                                if (err) return res.toJson(false, [], "Error.");

                                return res.toJson(true, user, "Sucess.");
                            });
           }
        })

      }
      else{
        return  empty
      }
   })
}


问:
YOLO object detection model?
Currently, I am reading the Yolo9000 model "https://arxiv.org/pdf/1612.08242.pdf" and I am very confused about how the model can predict the bounding box for object detection, I did many examples with Tensorflow, and in most of them we give to the model "Images and Label of images".

My questions are:
  1- How we can pass the bounding box instead of labels to the model?
  2- How can the the model learn that many boxes belong to one images?

答:
In YOLO, we divide the image into 7X7 grid. For each of the grid location, the network predicts three things -

Probability of an object being present in that grid

If an object lies in this grid, what would be the co-ordinates of the
bounding box?

If an object lies in this grid, which class does it
belong to?

If we apply regression for all the above variables for all 49 grid locations, we will be able tell which grid locations have objects(using first parameter). For the grid locations that have objects, we can tell the bounding box co-ordinates and correct class using the second and third parameters.

Once we have designed a network that can output all the information we need, prepare the training data in this format i.e. find these parameters for every 7X7 grid location in every image in your dataset. Next you simply train the deep neural network to regress for these parameters.

Title: YOLO object detection model?


问:
Datatable refresh not working if page state is true
I have data table which is saving current page state.

```<code>var tbl = $('#datatable').dataTable({
  "bStateSave": true,
  "fnStateSave": function(oSettings, oData) {
    localStorage.setItem('datatable', JSON.stringify(oData));
  },
  "fnStateLoad": function(oSettings) {
    return JSON.parse(localStorage.getItem('datatable'));
  },
  "order": [
    [6, "desc"]
  ],
  "columnDefs": [{
    "targets": [6],
    "visible": false,
    "searchable": false
  }]
});
</code>```

I refreshed my page.It's not refreshing because I saved page state.
I searched by using search box and refreshed it.Still not working.

I have 10 pages. for each raw I have inner page. If I want to see some data from 4th page's inner page, and coming back to the list page I need to save the page state.

Please suggest to solve this.

答:
```<code> $('#<%=anchrefrsh.ClientID%>').click(function () {
  location.reload();
  var table = $('#datatable').DataTable();
  table.state.clear();
  table.fnDestroy();
  table = $("#datatable").dataTable();
  table.fnDraw();
  return false;
 });
</code>```

Body:
I have data table which is saving current page state.

var tbl = $('#datatable').dataTable({
  "bStateSave": true,
  "fnStateSave": function(oSettings, oData) {
    localStorage.setItem('datatable', JSON.stringify(oData));
  },
  "fnStateLoad": function(oSettings) {
    return JSON.parse(localStorage.getItem('datatable'));
  },
  "order": [
    [6, "desc"]
  ],
  "columnDefs": [{
    "targets": [6],
    "visible": false,
    "searchable": false
  }]
});

I refreshed my page.It's not refreshing because I saved page state.
I searched by using search box and refreshed it.Still not working.

I have 10 pages. for each raw I have inner page. If I want to see some data from 4th page's inner page, and coming back to the list page I need to save the page state.

Please suggest to solve this.


问:
Why do I get a back-ground thread 'Invoke' warning when I install a NuGet package?
This happens at least once a day, without visibly interfering with any other aspect of the packages facet of this project. When I enter an install-package command, this is the package manager's response in the console:

```<code>PM> Install-Package UmbracoCms
Invoke must be called on a background thread.
  GET https://api.nuget.org/v3/registration1-gz/umbracocms/index.json
  OK https://api.nuget.org/v3/registration1-gz/umbracocms/index.json 306ms
  GET https://api.nuget.org/v3/registration1-gz/umbracocms/page/7.6.0/7.6.3.json
</code>```

All else seems to work fine, most of the time, after that. I have a fair suspicion that the installation of the dotnet and nuget CLIs may have played a role.

答:
This issue is currently under investigation:
https://developercommunity.visualstudio.com/content/problem/65296/invoke-must-be-called-on-a-background-thread.html

https://github.com/NuGet/Home/issues/5348

Body:
This happens at least once a day, without visibly interfering with any other aspect of the packages facet of this project. When I enter an install-package command, this is the package manager's response in the console:

PM> Install-Package UmbracoCms
Invoke must be called on a background thread.
  GET https://api.nuget.org/v3/registration1-gz/umbracocms/index.json
  OK https://api.nuget.org/v3/registration1-gz/umbracocms/index.json 306ms
  GET https://api.nuget.org/v3/registration1-gz/umbracocms/page/7.6.0/7.6.3.json

All else seems to work fine, most of the time, after that. I have a fair suspicion that the installation of the dotnet and nuget CLIs may have played a role.


问:
Get page by name or by number interop Word
I'm trying to access a page in Word by it's name or number. I thought I was going in the right direction but there doesn't seem to be a page.name or page.number property. The issue is in my if statement where I'm trying to say if there is a page named Page 4 Content then select it.

```<code>    var wordApplication = (word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
    string path = CommonMethods.getFile(fileName);

    myDoc = wordApplication.Documents.Open(path);
    wordApplication.Visible = true;
    wordApplication.WindowState = word.WdWindowState.wdWindowStateMaximize;

    word.Pages pages = myDoc.ActiveWindow.ActivePane.Pages;

    foreach (word.Page p in pages )
    {
        if (p.)
        {

        }
    }
</code>```

答:
I ended up doing the following and it works like a charm.</p>

```<code>        object What = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
        object Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
        object Miss = System.Reflection.Missing.Value;
        word.Pages pages = doc.ActiveWindow.ActivePane.Pages;

        for (int i = 0; i < pages.Count; i++)
        {

            if (i == pageNumber)
            {
                doc.Application.Selection.GoTo(ref What, ref Which, pageNumber, ref Miss);
            }

        }
    }
</code>```

Body:
I'm trying to access a page in Word by it's name or number. I thought I was going in the right direction but there doesn't seem to be a page.name or page.number property. The issue is in my if statement where I'm trying to say if there is a page named Page 4 Content then select it.

    var wordApplication = (word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
    string path = CommonMethods.getFile(fileName);

    myDoc = wordApplication.Documents.Open(path);
    wordApplication.Visible = true;
    wordApplication.WindowState = word.WdWindowState.wdWindowStateMaximize;

    word.Pages pages = myDoc.ActiveWindow.ActivePane.Pages;

    foreach (word.Page p in pages )
    {
        if (p.)
        {

        }
    }

Body:
I ended up doing the following and it works like a charm.

        object What = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
        object Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
        object Miss = System.Reflection.Missing.Value;
        word.Pages pages = doc.ActiveWindow.ActivePane.Pages;

        for (int i = 0; i < pages.Count; i++)
        {

            if (i == pageNumber)
            {
                doc.Application.Selection.GoTo(ref What, ref Which, pageNumber, ref Miss);
            }

        }
    }


问:
Error when using std::make_move_iterator to insert a std::list<std::unique_ptr>> into another one
I've been reading this answer about moving elements from a std::vector<std::unique_ptr<T>> to another one using std::make_move_iterator. It works flawlessly:

```<code>std::vector<std::unique_ptr<int>> c1;
std::vector<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
c2.insert(c2.end(), std::make_move_iterator(c1.begin()), std::make_move_iterator(c1.end()));
</code>```

Now I tried to change it to use a different container (std::list):

```<code>std::list<std::unique_ptr<int>> c1;
std::list<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
c2.insert(c2.end(), std::make_move_iterator(c1.begin()), std::make_move_iterator(c1.end()));
</code>```

But compilation fails with:

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

However, it does work if lists contain other objects (like std::string):

```<code>std::list<std::string> s1;
std::list<std::string> s2;
s2.insert(s2.end(), std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()));
</code>```

Now, if I use another answer from the same question, which uses std::back_inserter and std::move, it works with both std::vector and std::list:

```<code>std::list<std::unique_ptr<int>> c1;
std::list<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
std::move(c1.begin(), c1.end(), std::back_inserter(c2));
</code>```

As far as I understand, this solution basically moves each item individually when back inserting on the second container.

My question is, why using std::make_move_iterator on a std::list of std::unique_ptr doesn't work but it does with std::vector or if the list element is of a different type?

Note: I'm using Visual Studio 2010.

答:
The core problem is that Visual Studio 2010's implementation of std::list::insert doesn't support moving semantics. Internally, the std::list::insert invokes a method called _Insert, which is declared as follows in VS 2010:

```<code>void _Insert(const_iterator _Where, const _Ty& _Val)
</code>```

In VS 2017 (not checked for other versions), it calls the same method but it is declared as:

```<code>void _Insert(_Unchecked_const_iterator _Where, _Valty&&... _Val)
</code>```

As seen, VS 2017 uses an rvalue reference, therefore calling the moving constructor of std::unique_ptr when making the insertion. On the other hand, VS 2010 uses an lvalue reference instead, so at some moment the copy constructor is called, which is declared private for std::unique_ptr, generating the compilation error.

Conclusion

In VS 2010 there is no way to use the solution based on std::make_move_iterator because how std::list::insert is implemented. Options for appending a std::list<std::unique_ptr<T>> into another one include:

Using the back_inserter:

```<code>std::move(c1.begin(), c1.end(), std::back_inserter(c2));
</code>```

Using std::list::splice (credit to @T.C.), which is very useful since it can be directly used with lists returned by functions:

```<code>c2.splice(c2.end(), c1);
</code>```

Body:
I've been reading this answer about moving elements from a std::vector<std::unique_ptr<T>> to another one using std::make_move_iterator. It works flawlessly:

std::vector<std::unique_ptr<int>> c1;
std::vector<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
c2.insert(c2.end(), std::make_move_iterator(c1.begin()), std::make_move_iterator(c1.end()));

Now I tried to change it to use a different container (std::list):

std::list<std::unique_ptr<int>> c1;
std::list<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
c2.insert(c2.end(), std::make_move_iterator(c1.begin()), std::make_move_iterator(c1.end()));

But compilation fails with:

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

However, it does work if lists contain other objects (like std::string):

std::list<std::string> s1;
std::list<std::string> s2;
s2.insert(s2.end(), std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()));

Now, if I use another answer from the same question, which uses std::back_inserter and std::move, it works with both std::vector and std::list:

std::list<std::unique_ptr<int>> c1;
std::list<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
std::move(c1.begin(), c1.end(), std::back_inserter(c2));

As far as I understand, this solution basically moves each item individually when back inserting on the second container.

My question is, why using std::make_move_iterator on a std::list of std::unique_ptr doesn't work but it does with std::vector or if the list element is of a different type?

Note: I'm using Visual Studio 2010.

Body:
The core problem is that Visual Studio 2010's implementation of std::list::insert doesn't support moving semantics. Internally, the std::list::insert invokes a method called _Insert, which is declared as follows in VS 2010:

void _Insert(const_iterator _Where, const _Ty& _Val)

In VS 2017 (not checked for other versions), it calls the same method but it is declared as:

void _Insert(_Unchecked_const_iterator _Where, _Valty&&... _Val)

As seen, VS 2017 uses an rvalue reference, therefore calling the moving constructor of std::unique_ptr when making the insertion. On the other hand, VS 2010 uses an lvalue reference instead, so at some moment the copy constructor is called, which is declared private for std::unique_ptr, generating the compilation error.

Conclusion

In VS 2010 there is no way to use the solution based on std::make_move_iterator because how std::list::insert is implemented. Options for appending a std::list<std::unique_ptr<T>> into another one include:

Using the back_inserter:

std::move(c1.begin(), c1.end(), std::back_inserter(c2));

Using std::list::splice (credit to @T.C.), which is very useful since it can be directly used with lists returned by functions:

c2.splice(c2.end(), c1);


问:
Stub out address geocoding during unit test

This is my user.rb file, where I have use geocoded_by :full_address.Which give me follwing error on running minitest cases "ArgumentError: unknown stub request 2000 h st nw room 1 washington district of columbia 20037". Following is code of unit test.

```<code>def full_address
@address = ""
@address << " " << self.street_address_1.to_s unless self.street_address_1.blank?
@address << " " << self.street_address_2.to_s unless self.street_address_2.blank?
@address << " " << self.city.to_s unless self.city.blank?
@address << " " << self.state.name.to_s unless self.state_id.blank?
@address << " " << self.zip.to_s unless self.zip.blank?
@address.strip.downcase
</code>```

end

```<code>  test "in_user_range? returns false if not in range" do
item = items(:protein_only_item)
user = users(:user2)
user.latitude = 41.542517 # west des moines ia
user.longitude = -93.760625 # west des moines ia
user.geocode
item.in_user_range?(user)
</code>```

end

答:
We just need to add stub before geocode

```<code>Geocoder.configure(:lookup => :test)

Geocoder::Lookup::Test.add_stub(
 "New York, NY", [
  {
   'latitude'     => 40.7143528,
   'longitude'    => -74.0059731,
   'address'      => 'New York, NY, USA',
   'state'        => 'New York',
   'state_code'   => 'NY',
   'country'      => 'United States',
   'country_code' => 'US'
 }])
</code>```

Body:
This is my user.rb file, where I have use geocoded_by :full_address.Which give me follwing error on running minitest cases "ArgumentError: unknown stub request 2000 h st nw room 1 washington district of columbia 20037". Following is code of unit test.

def full_address
@address = ""
@address << " " << self.street_address_1.to_s unless self.street_address_1.blank?
@address << " " << self.street_address_2.to_s unless self.street_address_2.blank?
@address << " " << self.city.to_s unless self.city.blank?
@address << " " << self.state.name.to_s unless self.state_id.blank?
@address << " " << self.zip.to_s unless self.zip.blank?
@address.strip.downcase

end

  test "in_user_range? returns false if not in range" do
item = items(:protein_only_item)
user = users(:user2)
user.latitude = 41.542517 # west des moines ia
user.longitude = -93.760625 # west des moines ia
user.geocode
item.in_user_range?(user)

end

Body:
We just need to add stub before geocode

Geocoder.configure(:lookup => :test)

Geocoder::Lookup::Test.add_stub(
 "New York, NY", [
  {
   'latitude'     => 40.7143528,
   'longitude'    => -74.0059731,
   'address'      => 'New York, NY, USA',
   'state'        => 'New York',
   'state_code'   => 'NY',
   'country'      => 'United States',
   'country_code' => 'US'
 }])


问:
Python: variables assigned before for loop
I'm new to python but not programming in general. Checking "Dive into Python" I have found this example (which works) but I don't get the syntax.

```<code>return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
</code>```

Simply put, it's using variables k and v as strings for the "%s=%s" (nothing weird here) but those variables don't have any value yet. And just like that there is a for loop which iterates and assigns values to k and v. So this is what puzzles me:
1. The for loop is "returning" somehow values k and v to the previous statement (k,v).
2. Both statements (1. "%s=%s" % (k, v) and 2. for k, v in params.items()) can be in the same line with no syntax error.

I have checked the "for" syntax reference and it doesn't even hint in this direction, so I'm sure I have to check somewhere else, but don't know where.

Thank you in advance.

答:
```<code>param.items() = [(key1, val1), (key2, val2) ... ]
</code>```

Extended code for this list comprehension.. Generate the list inside the square brackets first, then join the list together by passing it to the join method.

```<code>new_list = []
for each_tuple in param.items():
    k = each_tuple(0)
    v = each_tuple(1)
    new_list.append("%s==%s" % (k, v,))
":".join(new_list)         # new_list = ['k1==v1', 'k2==v2', 'k3==v3',...]

>>> 'key1==value1:key2==value2:key3==value3....'
</code>```

Body:
I'm new to python but not programming in general. Checking "Dive into Python" I have found this example (which works) but I don't get the syntax.

return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

Simply put, it's using variables k and v as strings for the "%s=%s" (nothing weird here) but those variables don't have any value yet. And just like that there is a for loop which iterates and assigns values to k and v. So this is what puzzles me:
1. The for loop is "returning" somehow values k and v to the previous statement (k,v).
2. Both statements (1. "%s=%s" % (k, v) and 2. for k, v in params.items()) can be in the same line with no syntax error.

I have checked the "for" syntax reference and it doesn't even hint in this direction, so I'm sure I have to check somewhere else, but don't know where.

Thank you in advance.

Body:
param.items() = [(key1, val1), (key2, val2) ... ]

Extended code for this list comprehension.. Generate the list inside the square brackets first, then join the list together by passing it to the join method.

new_list = []
for each_tuple in param.items():
    k = each_tuple(0)
    v = each_tuple(1)
    new_list.append("%s==%s" % (k, v,))
":".join(new_list)         # new_list = ['k1==v1', 'k2==v2', 'k3==v3',...]

>>> 'key1==value1:key2==value2:key3==value3....'


问:
Create a person with alfresco RESTApi using xmlhttprequest
So I'm creating a custom share page for alfresco and I want to create a person using javascript thanks to the REST API (You will find all the doc about the api and why I shaped my var this way here) so I wrote this code which contains a xmlhttprequest to post the data :

```<code>var boby = "{ \"id\": \"bob\",\"firstName\": \"Bob\", \"lastName\": \"LeBricoleur\", \"email\": \"bob@lebricoleur.com\", \"telephone\": \"6666666666\", \"enabled\": true,\"emailNotificationsEnabled\": true, \"password\": \"bob\" }";
                        console.log(boby);
                        function loadDoc() {
                            var xhttp = new XMLHttpRequest();
                            xhttp.onreadystatechange = function() {
                            if (this.readyState == 4 && this.status == 200) {
                              document.getElementById("creatingperson").innerHTML = this.responseText;
                            }
                            };
                            xhttp.open("POST", 'http://localhost:8081/share/proxy/alfresco-api/-default-/public/alfresco/versions/1/people', true);
                            xhttp.setRequestHeader("Content-Type", "application/json");    //curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Basic YWRtaW46YWRtaW4=' -d '[...]
                            xhttp.send(boby);
                        }
</code>```

Ok so this doesn't give me anything.. Not even an error message. At first I thought it was because of my whole code so I created the variable boby that I would send to the server to simplify the debug but I still don't know where the error comes from.

Is it a problem from my code ? From my way of using the api ? From alfresco share itself ? If you can help me thanks a lot !

P.S : I wrote a code to list people (instead of creating one) which works using the same url if that can help

[EDIT]

I've found another way to make my request and it works but I don't know why.. here is the code :

```<code>var createperson = "{ \"id\": \"" + document.getElementById('login').value + "\",\"firstName\": \"" + document.getElementById('firstName').value + "\", \"lastName\": \"" + document.getElementById('lastName').value + "\", \"email\": \"" + document.getElementById('mail').value + "\", \"telephone\": \"" + document.getElementById('telephone').value + "\", \"enabled\": true,\"emailNotificationsEnabled\": true, \"password\": \"" + document.getElementById('pwd2').value + "\" }";
                        console.log(createperson);
                            var url = "http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/people";
                            var method = "POST";
                            var async = true;
                            //var postData = "{ \"id\": \"bob\",\"firstName\": \"Bob\", \"lastName\": \"LeBricoleur\", \"email\": \"bob@lebricoleur.com\", \"telephone\": \"6666666666\", \"enabled\": true,\"emailNotificationsEnabled\": true, \"password\": \"bob\" }";

                            var request = new XMLHttpRequest();
                            request.onload = function () {
                               var status = request.status; // HTTP response status, e.g., 201 for "201 OK"
                               var data = request.responseText; // Returned data, e.g., an HTML document.
                                console.log("status :");
                                console.log(status);
                                console.log("data :");
                                console.log(data);
                            }

                            request.open(method, url, async);
                            request.setRequestHeader("Content-Type", "application/json");
                            request.setRequestHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
                            request.send(createperson);
</code>```

Moreover when I try to use this type of request to list the people (just to use the method everywhere) it doesn't work.. here is a part of what I wrote to list people :

```<code>var url = "http://192.168.1.103:8080/alfresco/api/-default-/public/alfresco/versions/1/people";
         var method = "GET";
         var async = true;
         var request = new XMLHttpRequest();
         request.onload = function () {
               var status = request.status; // HTTP response status, e.g., 201 for "201 OK"
           objet = JSON.parse(request.responseText);
               console.log("status :");
               console.log(status);
               console.log("data :");
               console.log(objet);
         }

         request.open(method, url, async); //, "admin", "admin");
         request.setRequestHeader("Content-Type", "application/json");
         request.setRequestHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
</code>```

So if anyone knows why it worked for creating someone and why it doesn't for listing thank you for your answer !

答:
Maybe this information could be useful. Take a look.

https://community.alfresco.com/community/ecm/blog/2017/04/18/v1-rest-api-part-10-people

Regards,

Body:
So I'm creating a custom share page for alfresco and I want to create a person using javascript thanks to the REST API (You will find all the doc about the api and why I shaped my var this way here) so I wrote this code which contains a xmlhttprequest to post the data :

var boby = "{ \"id\": \"bob\",\"firstName\": \"Bob\", \"lastName\": \"LeBricoleur\", \"email\": \"bob@lebricoleur.com\", \"telephone\": \"6666666666\", \"enabled\": true,\"emailNotificationsEnabled\": true, \"password\": \"bob\" }";
                        console.log(boby);
                        function loadDoc() {
                            var xhttp = new XMLHttpRequest();
                            xhttp.onreadystatechange = function() {
                            if (this.readyState == 4 && this.status == 200) {
                              document.getElementById("creatingperson").innerHTML = this.responseText;
                            }
                            };
                            xhttp.open("POST", 'http://localhost:8081/share/proxy/alfresco-api/-default-/public/alfresco/versions/1/people', true);
                            xhttp.setRequestHeader("Content-Type", "application/json");    //curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Basic YWRtaW46YWRtaW4=' -d '[...]
                            xhttp.send(boby);
                        }

Ok so this doesn't give me anything.. Not even an error message. At first I thought it was because of my whole code so I created the variable boby that I would send to the server to simplify the debug but I still don't know where the error comes from.

Is it a problem from my code ? From my way of using the api ? From alfresco share itself ? If you can help me thanks a lot !

P.S : I wrote a code to list people (instead of creating one) which works using the same url if that can help

[EDIT]

I've found another way to make my request and it works but I don't know why.. here is the code :

var createperson = "{ \"id\": \"" + document.getElementById('login').value + "\",\"firstName\": \"" + document.getElementById('firstName').value + "\", \"lastName\": \"" + document.getElementById('lastName').value + "\", \"email\": \"" + document.getElementById('mail').value + "\", \"telephone\": \"" + document.getElementById('telephone').value + "\", \"enabled\": true,\"emailNotificationsEnabled\": true, \"password\": \"" + document.getElementById('pwd2').value + "\" }";
                        console.log(createperson);
                            var url = "http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/people";
                            var method = "POST";
                            var async = true;
                            //var postData = "{ \"id\": \"bob\",\"firstName\": \"Bob\", \"lastName\": \"LeBricoleur\", \"email\": \"bob@lebricoleur.com\", \"telephone\": \"6666666666\", \"enabled\": true,\"emailNotificationsEnabled\": true, \"password\": \"bob\" }";

                            var request = new XMLHttpRequest();
                            request.onload = function () {
                               var status = request.status; // HTTP response status, e.g., 201 for "201 OK"
                               var data = request.responseText; // Returned data, e.g., an HTML document.
                                console.log("status :");
                                console.log(status);
                                console.log("data :");
                                console.log(data);
                            }

                            request.open(method, url, async);
                            request.setRequestHeader("Content-Type", "application/json");
                            request.setRequestHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
                            request.send(createperson);

Moreover when I try to use this type of request to list the people (just to use the method everywhere) it doesn't work.. here is a part of what I wrote to list people :

var url = "http://192.168.1.103:8080/alfresco/api/-default-/public/alfresco/versions/1/people";
         var method = "GET";
         var async = true;
         var request = new XMLHttpRequest();
         request.onload = function () {
               var status = request.status; // HTTP response status, e.g., 201 for "201 OK"
           objet = JSON.parse(request.responseText);
               console.log("status :");
               console.log(status);
               console.log("data :");
               console.log(objet);
         }

         request.open(method, url, async); //, "admin", "admin");
         request.setRequestHeader("Content-Type", "application/json");
         request.setRequestHeader("Authorization", "Basic YWRtaW46YWRtaW4=");

So if anyone knows why it worked for creating someone and why it doesn't for listing thank you for your answer !


问:
Can I use JOIN instead of a subquery to get COUNT() across tables in MySQL?
I have one table that stores posts. Each post object has a postTypeId that denotes if it's a question post or an answer post. I would like to get question posts and count the number of answer posts each question post has. Can I do this using a JOIN instead of a subquery as shown below? The schema assumes the following: postsTable(id, postTypeId, parentId, title)

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.title
    , (SELECT COUNT(answers.id) AS answerCount FROM posts AS answers WHERE posts.id = answers.parentId GROUP BY posts.postTypeId)
    FROM posts
    WHERE posts.postTypeId = '1'
</code>```

Also, is the GROUP By necessary in the subquery?

答:
How about this?</p>

```<code>SELECT questions.id, questions.posttypeID, questions.parentID, questions.title, count(questions.id) AS NUM_OF_ANSWERS
FROM posts AS questions
LEFT JOIN posts AS answers on (answers.parentID = questions.id)
WHERE questions.postTypeID = '1';
ORDER BY questions.id, questions.posttypeID, questions.parentID, questions.title;
</code>```

Body:
I have one table that stores posts. Each post object has a postTypeId that denotes if it's a question post or an answer post. I would like to get question posts and count the number of answer posts each question post has. Can I do this using a JOIN instead of a subquery as shown below? The schema assumes the following: postsTable(id, postTypeId, parentId, title)

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.title
    , (SELECT COUNT(answers.id) AS answerCount FROM posts AS answers WHERE posts.id = answers.parentId GROUP BY posts.postTypeId)
    FROM posts
    WHERE posts.postTypeId = '1'

Also, is the GROUP By necessary in the subquery?

Body:
How about this?

SELECT questions.id, questions.posttypeID, questions.parentID, questions.title, count(questions.id) AS NUM_OF_ANSWERS
FROM posts AS questions
LEFT JOIN posts AS answers on (answers.parentID = questions.id)
WHERE questions.postTypeID = '1';
ORDER BY questions.id, questions.posttypeID, questions.parentID, questions.title;


问:
Count Characters after a certain pattern
I have a database that contains a column "Code" where the records have the following format "xx-xxx" and "xx-xx", for the later format i want to add a zero after the "-" to make it "xx-0xx", is there anyway to count the characters after a certain pattern in Mysql</p>

答:
Hmmm.  If those are your only two possibilities, you can use case:

```<code>select (case when length(code) = 5
             then replace(code, '-', '-0')
             else code
        end) as new_code
</code>```

If you want to be more general, deconstruct the string and build it back again:

```<code>select concat_ws('-', substring_index(code, '-', 1),
                 lpad(substring_index(code, '-', -1), 3, '0')
                )
</code>```

Body:
Hmmm.  If those are your only two possibilities, you can use case:

select (case when length(code) = 5
             then replace(code, '-', '-0')
             else code
        end) as new_code

If you want to be more general, deconstruct the string and build it back again:

select concat_ws('-', substring_index(code, '-', 1),
                 lpad(substring_index(code, '-', -1), 3, '0')
                )


问:
Bicubic interpolation beyond grid values in Matlab
Is it possible to achieve bi-cubic interpolation beyond grid values?
For example:

```<code>L = [5,10,20,25,40];
W= 1:3;
S= [50 99 787
    779 795 850
    803 779 388
    886 753 486
    849 780 598];
size1 = griddata(W,L,S,2,40,'cubic')
sizeBeyond = griddata(W,L,S,2,41,'cubic')
sizeV4 = griddata(W,L,S,2,41,'v4')
</code>```

returns:

```<code>size1 = 780

sizeBeyond = NaN

sizeV4 = 721.57
</code>```

答:
What I was suggesting is, you can input the values which are extrapolated. Check the below code. But note that, as suggested by flawr, the extrapolation behave really bad.

```<code>l = [5,10,20,25,40];
w = 1:3;

li = [l 41] ;

S = [50 99 787
    779 795 850
    803 779 388
    886 753 486
    849 780 598];
[W,L] = meshgrid(w,l) ;
[Wi,Li] = meshgrid(w,li) ;
Si = interp2(W,L,S,Wi,Li,'spline') ;

size1 = griddata(W,L,S,2,40,'cubic')
sizeBeyond = griddata(Wi,Li,Si,2,41,'cubic')
sizeV4 = griddata(W,L,S,2,41,'v4')
</code>```

Note: Don't use inbuilt commands like length,size etc as variables in the code, even for demonstration, it is trouble some.

Though, this is not answer, I have to post it here as for discussion.

Body:
Is it possible to achieve bi-cubic interpolation beyond grid values?
For example:

L = [5,10,20,25,40];
W= 1:3;
S= [50 99 787
    779 795 850
    803 779 388
    886 753 486
    849 780 598];
size1 = griddata(W,L,S,2,40,'cubic')
sizeBeyond = griddata(W,L,S,2,41,'cubic')
sizeV4 = griddata(W,L,S,2,41,'v4')

returns:

size1 = 780

sizeBeyond = NaN

sizeV4 = 721.57

Body:
What I was suggesting is, you can input the values which are extrapolated. Check the below code. But note that, as suggested by flawr, the extrapolation behave really bad.

l = [5,10,20,25,40];
w = 1:3;

li = [l 41] ;

S = [50 99 787
    779 795 850
    803 779 388
    886 753 486
    849 780 598];
[W,L] = meshgrid(w,l) ;
[Wi,Li] = meshgrid(w,li) ;
Si = interp2(W,L,S,Wi,Li,'spline') ;

size1 = griddata(W,L,S,2,40,'cubic')
sizeBeyond = griddata(Wi,Li,Si,2,41,'cubic')
sizeV4 = griddata(W,L,S,2,41,'v4')

Note: Don't use inbuilt commands like length,size etc as variables in the code, even for demonstration, it is trouble some.

Though, this is not answer, I have to post it here as for discussion.


问:
vue files without NodeJS?
I want to host my app outside of node JS, but I want to use .vue files and possible npm as build system (if it's needed). Is it's possible to do?

I do not need any backward compatibility and if it work on latest Chrome dev it's ok for me.

Is there any examples how it can be done?

I tried to build some webpack template, but it's work only inside NodeJS. On other server I am getting 404 when I am accessing to URLs that placed in .vue files. It's seems that they can't be handled by the other server.

答:
Your starting point is wrong. Vue + node.js can build a complete site. Vue is the front-end framework, node's server language. The two can be used in combination. But not vue must rely on node to use. The two of them can be perfect to achieve the front and back separation of the development model.

In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.

Vue-cli

If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!

Vue Demo

Title: vue files without NodeJS?


问:
Rendering an element in a different zoom level or screen size
I'm creating a (react) component library for documentation and testing purposes for our company. A kind of style guide. Some of our components have styles that depend on media queries to scale up and down nicely.

Our style guide site is responsive but I would like to be able to render different screen sizes. As an example, I wanted to show how the site header looks like in desktop and mobile without having to resize the window, as if they were multiple iframes with different zoom levels.

So I was thinking if it was somehow possible to make html elements think they are being rendered in a larger or smaller screen by changing their zoom level. A sort of scaling, while staying within the same limits.

答:
In google chrome there is a tool who do this.

```<code>Right Click > Inspect the element > The mobile icon at the top corner right
</code>```

Check my screenshot below.

Cheers mate ;)

Body:
In google chrome there is a tool who do this.

Right Click > Inspect the element > The mobile icon at the top corner right

Check my screenshot below.

Cheers mate ;)


问:
How to print Label For Only true boolean values in a class in .Net MVC?
I have a class named AccessRole

```<code>namespace InnovatorYoung.Models
{
    public class AccessRole
    {
        public bool SuperAdmin { get; set; }
        public bool Admin { get; set; }
        public bool Mentors { get; set; }
        public bool Innovators { get; set; }
        public bool AcadPartner { get; set; }
        public bool Guest { get; set; }
    }
}
</code>```

I need to print Labels for only the Booleans which are true. Not sure how to do that !

答:
Hardcode, check each properties by name and print out if it's true.

Use reflection to get all properties and print out (recommended).

```<code>AccessRole instance = new AccessRole();
//...
Type type = typeof(AccessRole);

// Loop over properties.
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
    string name = propertyInfo.Name;
    object value = propertyInfo.GetValue(instance, null);
    if (value is bool and (bool)value)
    {
        // print...
    }
}
</code>```

Body:
I have a class named AccessRole

namespace InnovatorYoung.Models
{
    public class AccessRole
    {
        public bool SuperAdmin { get; set; }
        public bool Admin { get; set; }
        public bool Mentors { get; set; }
        public bool Innovators { get; set; }
        public bool AcadPartner { get; set; }
        public bool Guest { get; set; }
    }
}

I need to print Labels for only the Booleans which are true. Not sure how to do that !

Body:
Hardcode, check each properties by name and print out if it's true.

Use reflection to get all properties and print out (recommended).

AccessRole instance = new AccessRole();
//...
Type type = typeof(AccessRole);

// Loop over properties.
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
    string name = propertyInfo.Name;
    object value = propertyInfo.GetValue(instance, null);
    if (value is bool and (bool)value)
    {
        // print...
    }
}


Title: Merge two lines conditionally

Body:
200005251|AAAAAA
200005252|BBBBB
200005261|CCCCCC
200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF
200005302|VVVVVV
200005311|AAAAAA
200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS
200006022|HHHHHH
200006051|OOOOOO
200006052|GGGGGG
200006061|KKKKKK
200006062|FFFFF
200006071|TTTTTT

I have a file in first field as above. I need to merge every two lines if they only end ......1 and ......2. and leave the others as is. Desired output:

200005251|AAAAAA 200005252|BBBBB
200005261|CCCCCC 200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF 200005302|VVVVVV
200005311|AAAAAA 200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS 200006022|HHHHHH
200006051|OOOOOO 200006052|GGGGGG
200006061|KKKKKK 200006062|FFFFF
200006071|TTTTTT

Thanks in advance.

Body:
Simple awk script may achieve your goal,

awk_file:

{
  if($1%2==1) {
    if(odd==1){
      printf "\n";
    }
    printf "%s ",$0;
    odd=1;
  } else {
    printf "%s\n",$0;
    odd=0;
  }
} END {printf "\n"}

Then execute:

$ awk -v FS='|' -f awk_file file
200005251|AAAAAA 200005252|BBBBB
200005261|CCCCCC 200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF 200005302|VVVVVV
200005311|AAAAAA 200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS 200006022|HHHHHH
200006051|OOOOOO 200006052|GGGGGG
200006061|KKKKKK 200006062|FFFFF
200006071|TTTTTT


问:
SignalR - Could not establish trust relationship for the SSL/TLS secure channel
I'm trying to Invoke my signalR hub method from server code and its giving me an error

Could not establish trust relationship for the SSL/TLS secure channel.

my server side code is something like this

```<code>private void InvokeNotification(string methodName, params object[] args)
{
    try
    {
        string serverIp = ConfigurationManager.AppSettings["ServerIp"];
        var connection = new HubConnection(serverIp, useDefaultUrl: true);

        var myHub = connection.CreateHubProxy("myhub");
        connection.Start().Wait();
        myHub.Invoke(methodName, args);
    }
    catch (Exception ex)
    {
        //Some error handling
    }
}
</code>```

In hub class I have one method, called for example SayHello(), which sending message to all users.

With http its working perfectly, but when I remove 80 port from my IIS bindings, and leave only https port, it giving me error every time, when trying to Start() hub connection. I tried many things that I found by searching, but non of these works.
Does anyone else had similar problems, please help.

答:
Ok, I did something Like this

```<code> private void InvokeNotification(string methodName, params object[] args)
 {
     try
     {
         string serverIp = ConfigurationManager.AppSettings["ServerIp"];
         var connection = new HubConnection(serverIp, useDefaultUrl: true);
         var myHub = connection.CreateHubProxy("myhub");

         //This will ignore all certeficates
         //System.Net.ServicePointManager.ServerCertificateValidationCallback =
         //    ((sender, certificate, chain, sslPolicyErrors) => true);

         System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                    new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
         connection.Start().Wait();
         myHub.Invoke(methodName, args);
     }
     catch (Exception ex)
     {
         //Some error handling
     }
  }

private static bool ValidateRemoteCertificate(object sender, X509Certificate cert,
                                    X509Chain chain, SslPolicyErrors policyErrors)
{
    bool result = false;
    if (cert.Subject.ToUpper().Contains("MY_CERT_ISSUER_NAME"))
    {
        result = true;
    }
    return result;
}
</code>```

by this, I found my certificate and manually validate(actually pass through) it in a SSL conversation. I don't know how much legit is this solution, but for now it is.

UPDATE

I've changed ValidateRemoteCertificate() method:

```<code>private static bool ValidateRemoteCertificate(object sender, X509Certificate cert,
                                    X509Chain chain, SslPolicyErrors policyErrors)
{
    bool result = false;
    X509Certificate2 cert2 = (X509Certificate2)cert;
    X509Store store = new X509Store(StoreName.Root);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection cc = store.Certificates.Find(X509FindType.FindByThumbprint,
         chain.ChainElements[chain.ChainElements.Count - 1].Certificate.Thumbprint, true);
    store.Close();
    if (cc.Count > 0)
    {
        result = true;
    }
    return result;
}
</code>```

by this I'm opening certificate store, finding my item from it, by passing thumbprint parameter from certificate chain (last element).

Body:
I'm trying to Invoke my signalR hub method from server code and its giving me an error

Could not establish trust relationship for the SSL/TLS secure channel.

my server side code is something like this

private void InvokeNotification(string methodName, params object[] args)
{
    try
    {
        string serverIp = ConfigurationManager.AppSettings["ServerIp"];
        var connection = new HubConnection(serverIp, useDefaultUrl: true);

        var myHub = connection.CreateHubProxy("myhub");
        connection.Start().Wait();
        myHub.Invoke(methodName, args);
    }
    catch (Exception ex)
    {
        //Some error handling
    }
}

In hub class I have one method, called for example SayHello(), which sending message to all users.

With http its working perfectly, but when I remove 80 port from my IIS bindings, and leave only https port, it giving me error every time, when trying to Start() hub connection. I tried many things that I found by searching, but non of these works.
Does anyone else had similar problems, please help.

Body:
Ok, I did something Like this

 private void InvokeNotification(string methodName, params object[] args)
 {
     try
     {
         string serverIp = ConfigurationManager.AppSettings["ServerIp"];
         var connection = new HubConnection(serverIp, useDefaultUrl: true);
         var myHub = connection.CreateHubProxy("myhub");

         //This will ignore all certeficates
         //System.Net.ServicePointManager.ServerCertificateValidationCallback =
         //    ((sender, certificate, chain, sslPolicyErrors) => true);

         System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                    new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
         connection.Start().Wait();
         myHub.Invoke(methodName, args);
     }
     catch (Exception ex)
     {
         //Some error handling
     }
  }

private static bool ValidateRemoteCertificate(object sender, X509Certificate cert,
                                    X509Chain chain, SslPolicyErrors policyErrors)
{
    bool result = false;
    if (cert.Subject.ToUpper().Contains("MY_CERT_ISSUER_NAME"))
    {
        result = true;
    }
    return result;
}

by this, I found my certificate and manually validate(actually pass through) it in a SSL conversation. I don't know how much legit is this solution, but for now it is.

UPDATE

I've changed ValidateRemoteCertificate() method:

private static bool ValidateRemoteCertificate(object sender, X509Certificate cert,
                                    X509Chain chain, SslPolicyErrors policyErrors)
{
    bool result = false;
    X509Certificate2 cert2 = (X509Certificate2)cert;
    X509Store store = new X509Store(StoreName.Root);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection cc = store.Certificates.Find(X509FindType.FindByThumbprint,
         chain.ChainElements[chain.ChainElements.Count - 1].Certificate.Thumbprint, true);
    store.Close();
    if (cc.Count > 0)
    {
        result = true;
    }
    return result;
}

by this I'm opening certificate store, finding my item from it, by passing thumbprint parameter from certificate chain (last element).


问:
how to append the table body by ajax
I want to Append the tbody of table to already existing table how can i append the table.Actually I want to search the word from whole table .BY javascript and ajax.How can I append the table tbody in search.php page,please get me over this.
 search.php

```<code>   <div >
      <table id="table">
        <thead>
        <th>
        Email
        </th>
        <th>
        Firstname
        </th>
        <th>
        Lastname
        </th>
        <th>
        Companyname
        </th>
        <th>
        Title
        </th>
        <th>
        LinkedinURL
        </th>
        <th>
        Domain
        </th>
        <th>
        Companylocation
        </th>
        <th>
        Companysizecategory
        </th>
        <th>
       Companyfunding
        </th>
        <th>
        Companyindustry
        </th>
        <th>
        Companywebtech
        </th>
        <th>
        DateDownloaded
        </th>
        <th>
        ElucifyAccountID
        </th>
        </thead>

      </table>
      </div>
    </form>
      </div>
    </form>
      </body>
    </html>
    <script>
    $("#search").keyup(function()
    {
     var search=$(this).val();
     $.ajax({
         type:"POST",
         url:"searchajax.php",
         data:{
          ajaxsearch:search,
         },
         success:function(data){

          alert("success");
         },
         error:function(){
          alert('error');
         }

     });
    });
    </script>
</code>```

ajax.php

```<code>if (!empty($_POST['ajaxsearch']))
{
       $search=$_POST['ajaxsearch'];
$sql="SELECT * from company";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
 if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' OR ";
}

$sql="SELECT * from company ".$logicStr;
//echo "SELECT * from company ".$logicStr;
$get=mysql_query($sql);

$i=0;
while($getresult=mysql_fetch_array($get))
  {

    echo '<tbody>';
    echo'<tr>';
    echo '<td>';
     echo $getresult['Email'];
    echo '</td>';
    echo'<td>';
     echo $getresult['Firstname'];
    echo '</td>';
    echo '<td>';
     echo $getresult['Lastname'];
    echo '</td>';
    echo'<td>';
     echo $getresult['Companyname'];
     echo '</td>';
    echo'<td>';
    echo $getresult['Title'];
    echo'</td>';
    echo'<td>';
     echo $getresult['LinkedinURL'];
     echo'</td>';
    echo '<td>';
     echo $getresult['Domain'];
     echo'</td>';
    echo'<td>';
     echo $getresult['CompanyLocation'];
     echo '</td>';
    echo '<td>';
     echo $getresult['Companysizecategory'];
     echo '</td>';
    echo '<td>';
     echo $getresult['Companyfunding']
     echo'</td>';
   echo'<td>';
    echo $getresult['Companyindustry'];
    echo '</td>';
    echo '<td>';
     echo $getresult['companywebtech'];
     echo'</td>';
    echo '<td>';
    echo $getresult['Datedownloaded'];
    echo'</td>';
    echo '<td>';
     echo $getresult['ElucifyAccountID'];
     echo'</td>';
     echo'</tr>';
     echo'</tbody>';

   $i++;
   }
   }
   else
   {
    echo'<script>window.alert("enter valid Data")</script>';
   }
 ?>
</code>```

答:
In your ajax.php, you already print
. So if you want to append that ajax
 to existing search.php, please try like this:

```<code>$.ajax({
    type:"POST",
    url:"searchajax.php",
    data:{ajaxsearch:search},
    success:function(data){
        $('#table tbody').append(data);
    },
    error:function(){
        alert('error');
    }
});
</code>```

Note: if you use append, existing rows are not delete before append
  new data. This may cause duplicate rows.

If you don't need duplicate rows, you can remove or empty
 before append as shown in below.

```<code>$.ajax({
        type:"POST",
        url:"searchajax.php",
        data:{ajaxsearch:search},
        success:function(data){
            $('#table tbody').empty();
            $('#table tbody').append(data);
        },
        error:function(){
            alert('error');
        }
    });
</code>```

Title: how to append the table body by ajax

Body:
I want to Append the tbody of table to already existing table how can i append the table.Actually I want to search the word from whole table .BY javascript and ajax.How can I append the table tbody in search.php page,please get me over this.
 search.php

        Email

        Firstname

        Lastname

        Companyname

        Title

        LinkedinURL

        Domain

        Companylocation

        Companysizecategory

       Companyfunding

        Companyindustry

        Companywebtech

        DateDownloaded

        ElucifyAccountID

    </form>

    </form>

ajax.php

if (!empty($_POST['ajaxsearch']))
{
       $search=$_POST['ajaxsearch'];
$sql="SELECT * from company";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
 if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' OR ";
}

$sql="SELECT * from company ".$logicStr;
//echo "SELECT * from company ".$logicStr;
$get=mysql_query($sql);

$i=0;
while($getresult=mysql_fetch_array($get))
  {

    echo '
';
    echo'
';
    echo '';
     echo $getresult['Email'];
    echo '	';
    echo'';
     echo $getresult['Firstname'];
    echo '	';
    echo '';
     echo $getresult['Lastname'];
    echo '	';
    echo'';
     echo $getresult['Companyname'];
     echo '	';
    echo'';
    echo $getresult['Title'];
    echo'	';
    echo'';
     echo $getresult['LinkedinURL'];
     echo'	';
    echo '';
     echo $getresult['Domain'];
     echo'	';
    echo'';
     echo $getresult['CompanyLocation'];
     echo '	';
    echo '';
     echo $getresult['Companysizecategory'];
     echo '	';
    echo '';
     echo $getresult['Companyfunding']
     echo'	';
   echo'';
    echo $getresult['Companyindustry'];
    echo '	';
    echo '';
     echo $getresult['companywebtech'];
     echo'	';
    echo '';
    echo $getresult['Datedownloaded'];
    echo'	';
    echo '';
     echo $getresult['ElucifyAccountID'];
     echo'	';
     echo'
';
     echo'
';

   $i++;
   }
   }
   else
   {
    echo'';
   }
 ?>

Body:
In your ajax.php, you already print <tbody>. So if you want to append that ajax <tbody> to existing search.php, please try like this:

$.ajax({
    type:"POST",
    url:"searchajax.php",
    data:{ajaxsearch:search},
    success:function(data){
        $('#table tbody').append(data);
    },
    error:function(){
        alert('error');
    }
});

Note: if you use append, existing rows are not delete before append
  new data. This may cause duplicate rows.

If you don't need duplicate rows, you can remove or empty <tbody> before append as shown in below.

$.ajax({
        type:"POST",
        url:"searchajax.php",
        data:{ajaxsearch:search},
        success:function(data){
            $('#table tbody').empty();
            $('#table tbody').append(data);
        },
        error:function(){
            alert('error');
        }
    });


问:
jquery can't alert ajax response
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

```<code>    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }
</code>```

However, if the above code was written without

```<code>    if (response == 'false') {

    }
</code>```

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

答:
If you are sending the strings "true" or "false",  try removing extra whitespace that could be there from php file:

```<code>if (response.trim() == 'false') {
   alert(response);
}
</code>```

Title: jquery can't alert ajax response

Body:
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }

However, if the above code was written without

    if (response == 'false') {

    }

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

Body:
If you are sending the strings "true" or "false",  try removing extra whitespace that could be there from php file:

if (response.trim() == 'false') {
   alert(response);
}


问:
Conversion of oracle timestamp to postgres timestamp?
oracle timestamp example: 26-APR-17 09.40.13.243356000

Hi i have a scenario I am converting oracle timestamp to postgres timestamp but the output is not expected .

Query run in psql

```<code>migration=# SELECT TO_TIMESTAMP('26-APR-17 09.40.13.243356000','DD-MON-YY HH24.MI.SS:MS') :: timestamp without time zone;
        to_timestamp
----------------------------
   2017-04-26 09:15:55.864128                  ----- this is output
(1 row)
</code>```

The output should be: 2017-04-26 09:40:13.243356

答:
The problem is that 243356000 is taken as milliseconds, which accounts for the strange offset of about half an hour.

Trim the last three sigits and use US for microseconds:

```<code>SELECT to_timestamp(
          regexp_replace(
             '26-APR-17 09.40.13.243356000',
             '\d{3}$',
             ''
          ),
          'DD-MON-YY HH24.MI.SS.US'
       );
</code>```

Body:
oracle timestamp example: 26-APR-17 09.40.13.243356000

Hi i have a scenario I am converting oracle timestamp to postgres timestamp but the output is not expected .

Query run in psql

migration=# SELECT TO_TIMESTAMP('26-APR-17 09.40.13.243356000','DD-MON-YY HH24.MI.SS:MS') :: timestamp without time zone;
        to_timestamp
----------------------------
   2017-04-26 09:15:55.864128                  ----- this is output
(1 row)

The output should be: 2017-04-26 09:40:13.243356

Body:
The problem is that 243356000 is taken as milliseconds, which accounts for the strange offset of about half an hour.

Trim the last three sigits and use US for microseconds:

SELECT to_timestamp(
          regexp_replace(
             '26-APR-17 09.40.13.243356000',
             '\d{3}$',
             ''
          ),
          'DD-MON-YY HH24.MI.SS.US'
       );


问:
memory size of int vs integer in java
I have doubt in memory allocation for int and Integer variable in Java. For measuring memory i have used Instrumentation.getObjectSize() and it produces the same size for both the variables. Please find my code below:

ObjectSizeFetcher.java

```<code>import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}
</code>```

Test.java

```<code>public class Test {
public static void main(String[] args) throws Exception {
        int i=0;
        Integer i1 = new Integer(0);
        long value = ObjectSizeFetcher.getObjectSize(i);
        System.out.println(value);//prints 16

        long value1 = ObjectSizeFetcher.getObjectSize(i1);
        System.out.println(value1);//prints 16
}
}
</code>```

In the above case both the variable size prints the same. My doubt is, int is primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes but in this case why produces 16 bytes for both the values? If both the take same amount of memory in heap means, it leads to memory issue in java right?

答:
i gets auto-boxed to an Integer when passed to getObjectSize.

So you get the value of the size of promoted variable, not the original primitive int.

To circumvent this behaviour, build overloads of getObjectSize for the primitive cases:

```<code>public static long getObjectSize(int o) {
    return Integer.SIZE / 8;
}
</code>```

and so on.

Title: memory size of int vs integer in java

Body:
I have doubt in memory allocation for int and Integer variable in Java. For measuring memory i have used Instrumentation.getObjectSize() and it produces the same size for both the variables. Please find my code below:

ObjectSizeFetcher.java

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

Test.java

public class Test {
public static void main(String[] args) throws Exception {
        int i=0;
        Integer i1 = new Integer(0);
        long value = ObjectSizeFetcher.getObjectSize(i);
        System.out.println(value);//prints 16

        long value1 = ObjectSizeFetcher.getObjectSize(i1);
        System.out.println(value1);//prints 16
}
}

In the above case both the variable size prints the same. My doubt is, int is primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes but in this case why produces 16 bytes for both the values? If both the take same amount of memory in heap means, it leads to memory issue in java right?

Body:
i gets auto-boxed to an Integer when passed to getObjectSize.

So you get the value of the size of promoted variable, not the original primitive int.

To circumvent this behaviour, build overloads of getObjectSize for the primitive cases:

public static long getObjectSize(int o) {
    return Integer.SIZE / 8;
}

and so on.


问:
Importing views from microsoft sql server 2003 fail
I'm trying to migrate from microsoft sql server 2003 to sql server 2016.
Importing the data went well, using Microsoft SQL Management Studion 2016, but the views were not imported. And here is my request, how can I import the views?

At this point I tried:

Generate a creation script from the old database, but it seems back in 2003, this option didn't existed

Make a query in the old SQL server to list all the views, copy them and recreate them manually in the new server, but no queries worked to retrieve all the views

Copy the .MDF and.LDF file from the old server, and attach them to the new server, but I have the following error:

=

```<code>==================================

Fail to join database for serber « DESKTOP-53C6I45\SQLEXPRESS ».  (Microsoft.SqlServer.Smo)

------------------------------
To get help, click on : http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=13.0.16106.4+((SSMS_Rel_16_5).170125-2137)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attacher+la+base+de+données+Server&LinkId=20476

------------------------------
Software location :

   at Microsoft.SqlServer.Management.Smo.Server.AttachDatabase(String name, StringCollection files)
   at Microsoft.SqlServer.Management.SqlManagerUI.AttachDatabaseData.PrimaryFile.Attach()
   at Microsoft.SqlServer.Management.SqlManagerUI.AttachDatabase.SendDataToServer()

===================================

An exception was produced during the execution of batch Transact-SQL. (Microsoft.SqlServer.ConnectionInfo)

------------------------------
Location of the software :

   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(StringCollection sqlCommands, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQuery(StringCollection queries, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.Server.AttachDatabaseWorker(String name, StringCollection files, String owner, AttachOptions attachOptions)
   at Microsoft.SqlServer.Management.Smo.Server.AttachDatabase(String name, StringCollection files)

===================================

The database 'Labeint' can't be upgraded, because its non final version (539) isn't managed by this version of SQL Server. You can't open a database which is incompatible with this version of sqlservr.exe. You must rereate the database.
Impossible to open the new database 'Labeint'. Abandon of CREATE DATABASE. (.Net SqlClient Data Provider)

------------------------------
To get help, click on : http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=950&LinkId=20476

------------------------------
Server name : DESKTOP-53C6I45\SQLEXPRESS
Error number : 950
Gravity : 20
State: 1
Line number : 1

------------------------------
Location of the software :

   at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)
</code>```

The thing is the views are complex in an old project, getting data I don't know where for a project which is a black box to me, otherwise I would have recreated them manually, trying to figuring out how they were made.

答:
You can't wholsesale migrate the database files this way. You're trying to upgrade a Sql Server 2000 DB (v539) to Sql Server 2016 and there is not upgrade path for that. At a push you'd probably need to go from 2000 to 2008R2, then 2008R2 to 2016 if this is your chosen (only) path.

An alternative is to download an older version of Red-Gate Sql Compare (v11 or before) and run that in trial mode against an empty 2016 DB.

https://www.red-gate.com/products/old-versions

Body:
I'm trying to migrate from microsoft sql server 2003 to sql server 2016.
Importing the data went well, using Microsoft SQL Management Studion 2016, but the views were not imported. And here is my request, how can I import the views?

At this point I tried:

Generate a creation script from the old database, but it seems back in 2003, this option didn't existed

Make a query in the old SQL server to list all the views, copy them and recreate them manually in the new server, but no queries worked to retrieve all the views

Copy the .MDF and.LDF file from the old server, and attach them to the new server, but I have the following error:

=

==================================

Fail to join database for serber « DESKTOP-53C6I45\SQLEXPRESS ».  (Microsoft.SqlServer.Smo)

------------------------------
To get help, click on : http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=13.0.16106.4+((SSMS_Rel_16_5).170125-2137)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attacher+la+base+de+données+Server&LinkId=20476

------------------------------
Software location :

   at Microsoft.SqlServer.Management.Smo.Server.AttachDatabase(String name, StringCollection files)
   at Microsoft.SqlServer.Management.SqlManagerUI.AttachDatabaseData.PrimaryFile.Attach()
   at Microsoft.SqlServer.Management.SqlManagerUI.AttachDatabase.SendDataToServer()

===================================

An exception was produced during the execution of batch Transact-SQL. (Microsoft.SqlServer.ConnectionInfo)

------------------------------
Location of the software :

   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(StringCollection sqlCommands, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQuery(StringCollection queries, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.Server.AttachDatabaseWorker(String name, StringCollection files, String owner, AttachOptions attachOptions)
   at Microsoft.SqlServer.Management.Smo.Server.AttachDatabase(String name, StringCollection files)

===================================

The database 'Labeint' can't be upgraded, because its non final version (539) isn't managed by this version of SQL Server. You can't open a database which is incompatible with this version of sqlservr.exe. You must rereate the database.
Impossible to open the new database 'Labeint'. Abandon of CREATE DATABASE. (.Net SqlClient Data Provider)

------------------------------
To get help, click on : http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=950&LinkId=20476

------------------------------
Server name : DESKTOP-53C6I45\SQLEXPRESS
Error number : 950
Gravity : 20
State: 1
Line number : 1

------------------------------
Location of the software :

   at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)

The thing is the views are complex in an old project, getting data I don't know where for a project which is a black box to me, otherwise I would have recreated them manually, trying to figuring out how they were made.


问:
Create dynamic Component React (Native)
i get from web sevice array of object [{"id:1","title": "News",....},"id":2, "title": "History", .....}], so i want to create tab and scroll using react-native-scrollable-tab-view https://github.com/skv-headless/react-native-scrollable-tab-view, for static it work nice , but i don't know how to make dynamic because admin can add more title any time so static not work for this purpose.

In my code i do like this

```<code> constructor(props){
        super(props);
        this.state = {
            ws: []
        };
    }
</code>```

Also

```<code>componentDidMount() {
        fetch('http://localhost:8000/api/getThemeByOrganisations', {
            }).then((response) => response.json())
                .then((res) => {
                    this.setState({
                        ws : ws
                     });
                })
                .catch((error) => {
                    console.error(error);
                });
    };
</code>```

I want to make component name like that i get from web service (title) example NewsComponent

In the end i want to do like this but dynamic

```<code>var App = React.createClass({
  render() {
    return (
      <ScrollableTabView renderTabBar={() => <CustomTabBar someProp={'here'} />}>
        <ReactPage tabLabel="React" />
        <FlowPage tabLabel="Flow" />
        <JestPage tabLabel="Jest" />
      </ScrollableTabView>
    );
  }
});
</code>```

So here i want to do like for in "ws" and create dynamic Page , So anyone can help me and thanks

答:
To render components from an array of objects, you can use map. An example would be:

```<code>render() {
  return (
    <View>
      {myArray.map(item => <TargetComponent {...item}/>)}
    </View>
  )
}
</code>```

Title: Create dynamic Component React (Native)

Body:
i get from web sevice array of object [{"id:1","title": "News",....},"id":2, "title": "History", .....}], so i want to create tab and scroll using react-native-scrollable-tab-view https://github.com/skv-headless/react-native-scrollable-tab-view, for static it work nice , but i don't know how to make dynamic because admin can add more title any time so static not work for this purpose.

In my code i do like this

 constructor(props){
        super(props);
        this.state = {
            ws: []
        };
    }

Also

componentDidMount() {
        fetch('http://localhost:8000/api/getThemeByOrganisations', {
            }).then((response) => response.json())
                .then((res) => {
                    this.setState({
                        ws : ws
                     });
                })
                .catch((error) => {
                    console.error(error);
                });
    };

I want to make component name like that i get from web service (title) example NewsComponent

In the end i want to do like this but dynamic

var App = React.createClass({
  render() {
    return (
      <ScrollableTabView renderTabBar={() => <CustomTabBar someProp={'here'} />}>
        <ReactPage tabLabel="React" />
        <FlowPage tabLabel="Flow" />
        <JestPage tabLabel="Jest" />
      </ScrollableTabView>
    );
  }
});

So here i want to do like for in "ws" and create dynamic Page , So anyone can help me and thanks

Body:
To render components from an array of objects, you can use map. An example would be:

render() {
  return (
    <View>
      {myArray.map(item => <TargetComponent {...item}/>)}
    </View>
  )
}


问:
Python - List index out of range csv file
I am trying to make a dictionary that counts the number of each entry in the 13th to 17th column of a csv file. This is my code so far:

```<code>import unicodecsv

with open('hashtag.csv', 'r') as inp, open('hashtag3.csv', 'w') as out:
    writer = unicodecsv.writer(out, delimiter=';', lineterminator='\n',encoding='ISO-8859-1')
    stuff = unicodecsv.reader(inp, delimiter=';', encoding='ISO-8859-1')
    my_dict={}

    for row in stuff:
        for i in range (13,18):
            if row[i] in my_dict:
                my_dict[row[i]]+=1
            else:
                my_dict[row[i]]=1
    print my_dict
</code>```

However, it tells me this, when I try to run it.

row[i] in my_dict:
  IndexError: list index out of range

I tried taking each index on its own to figure out where it went wrong and found out, that it works with row[13], but not with any of the other integers in my range.
I thought maybe it's because in the other columns, there are some empty cells, but I can't even do an if-request in those other columns without getting the same error.

答:
It seems like, for some reason, row does not have all 13-18 columns.

Modify the for loop to

```<code>for i in range(13,min(len(row),18)):
</code>```

PS,

Instead of the (somewhat) cumbersome if row[i] in my_dict you might consider using defaultdict:

```<code>from collections import defaultdict

my_dict = defaultdict(int)  # accessing a new key returns zero
# ...
for row in stuff:
    for i in xrange(13, min(18, len(row))):
        my_dict[row[i]] += 1
</code>```

Body:
I am trying to make a dictionary that counts the number of each entry in the 13th to 17th column of a csv file. This is my code so far:

import unicodecsv

with open('hashtag.csv', 'r') as inp, open('hashtag3.csv', 'w') as out:
    writer = unicodecsv.writer(out, delimiter=';', lineterminator='\n',encoding='ISO-8859-1')
    stuff = unicodecsv.reader(inp, delimiter=';', encoding='ISO-8859-1')
    my_dict={}

    for row in stuff:
        for i in range (13,18):
            if row[i] in my_dict:
                my_dict[row[i]]+=1
            else:
                my_dict[row[i]]=1
    print my_dict

However, it tells me this, when I try to run it.

row[i] in my_dict:
  IndexError: list index out of range

I tried taking each index on its own to figure out where it went wrong and found out, that it works with row[13], but not with any of the other integers in my range.
I thought maybe it's because in the other columns, there are some empty cells, but I can't even do an if-request in those other columns without getting the same error.

Body:
It seems like, for some reason, row does not have all 13-18 columns.

Modify the for loop to

for i in range(13,min(len(row),18)):

PS,

Instead of the (somewhat) cumbersome if row[i] in my_dict you might consider using defaultdict:

from collections import defaultdict

my_dict = defaultdict(int)  # accessing a new key returns zero
# ...
for row in stuff:
    for i in xrange(13, min(18, len(row))):
        my_dict[row[i]] += 1


问:
change current menu item color
Hello i have a website with two menus, one on scroll and  another that shows when the header is at top
 i am trying to change the current menu item color when the header is at top

screenshot below

```<code>http://skyechopencil.com/home-newest/
</code>```

this is what i have tried but it only affects the menu item when on scroll not when fixed at the top

```<code>body .container .navigation ul .current-menu-item a {
color: #ff9900 !important;
text-decoration: underline;
}
</code>```

can someone help in correctin me

答:
-- language: lang-css -->

```<code>#sub-header ul li:hover{ background-color: #000;}
#sub-header ul li:hover a{ color: #fff; }
#sub-header ul li.active{ background-color: #000; }
#sub-header ul li.active a{ color: #fff; }
</code>```

 Home

 Contact Us

 About Us

```

Title: change current menu item color

Body:
Hello i have a website with two menus, one on scroll and  another that shows when the header is at top
 i am trying to change the current menu item color when the header is at top

screenshot below

http://skyechopencil.com/home-newest/

this is what i have tried but it only affects the menu item when on scroll not when fixed at the top

body .container .navigation ul .current-menu-item a {
color: #ff9900 !important;
text-decoration: underline;
}

can someone help in correctin me

Body:
-- language: lang-css -->

#sub-header ul li:hover{ background-color: #000;}
#sub-header ul li:hover a{ color: #fff; }
#sub-header ul li.active{ background-color: #000; }
#sub-header ul li.active a{ color: #fff; }

<div id="sub-header">
    <ul>
        <li> <a href="index.php">Home</a> </li>
        <li> <a href="contact.php">Contact Us</a> </li>
        <li> <a href="about.php">About Us</a> </li>
    </ul>
</div>


问:
How to pass dynamic initial values to redux-form
I'm using redux form in a table, I'm passing id as initial value to update some record.

If I pass initial value, it's taking same id to all the rows.

How can I do this ?

```<code>initialValues: { lead_id: id} //from component

Leads = reduxForm({
    form: `leads`,
    validate,
}))(Leads);
</code>```

Thank You

答:
As I understand, you are making redux-from for each row of your table component.

You have written:

```<code>Leads = reduxForm({
    form: `leads`,
    ...,
}))(Leads);
</code>```

You are passing leads as value to form prop for all redux-from. You have to give here unique value for each redux-form (corresponding to each row).

You can pass unique id while calling Leads component like this:

```<code><Leads form={'your unique id here'} />
</code>```

Body:
I'm using redux form in a table, I'm passing id as initial value to update some record.

If I pass initial value, it's taking same id to all the rows.

How can I do this ?

initialValues: { lead_id: id} //from component

Leads = reduxForm({
    form: `leads`,
    validate,
}))(Leads);

Thank You

Body:
As I understand, you are making redux-from for each row of your table component.

You have written:

Leads = reduxForm({
    form: `leads`,
    ...,
}))(Leads);

You are passing leads as value to form prop for all redux-from. You have to give here unique value for each redux-form (corresponding to each row).

You can pass unique id while calling Leads component like this:

<Leads form={'your unique id here'} />


问:
No provider for Http! - migrating from angular 2 to 4
I have included HttpModule in my import as follows

app.module.ts

```<code>import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/Http';
import { ApiService } from '../services/api.service';
@NgModule({
imports: [
        BrowserModule,
        HttpModule,
        .........
    ]
providers: [
        ApiService,
        .......
    ]
    })
</code>```

ApiService is my custom Service .

app.component.ts

```<code>import { Component, OnInit,NgZone } from '@angular/core';
import { Platform, AlertController, Events } from 'ionic-angular';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/Http';
import { StatusBar, Splashscreen, OneSignal, Network, CodePush, SyncStatus } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
import { EventsPage } from '../pages/events/events';
import { NewsPage } from '../pages/news/news';
import { RadioPage } from '../pages/radio/radio';
import { GalleryPage } from '../pages/gallery/gallery';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
    declare var navigator: any;
    declare var Connection: any;

    @Component({
        templateUrl: 'app.html'

    })
    export class MyApp {

        rootPage = TabsPage;

        constructor(public platform: Platform, public alert: AlertController,
            private events: Events,
            public radioService: RadioPage,
            private codePush: CodePush,
            private ngZone: NgZone,
            public http:Http) { }

        ngOnInit() {

            this.platform.ready().then(() => {
                // My custom code
            });
        }
    }
</code>```

答:
You should remove

```<code>providers: [Http]
</code>```

from your component annotation.

And '@angular/Http' needs to be in lowercase, '@angular/http'

Body:
I have included HttpModule in my import as follows

app.module.ts

import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/Http';
import { ApiService } from '../services/api.service';
@NgModule({
imports: [
        BrowserModule,
        HttpModule,
        .........
    ]
providers: [
        ApiService,
        .......
    ]
    })

ApiService is my custom Service .

app.component.ts

import { Component, OnInit,NgZone } from '@angular/core';
import { Platform, AlertController, Events } from 'ionic-angular';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/Http';
import { StatusBar, Splashscreen, OneSignal, Network, CodePush, SyncStatus } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
import { EventsPage } from '../pages/events/events';
import { NewsPage } from '../pages/news/news';
import { RadioPage } from '../pages/radio/radio';
import { GalleryPage } from '../pages/gallery/gallery';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
    declare var navigator: any;
    declare var Connection: any;

    @Component({
        templateUrl: 'app.html'

    })
    export class MyApp {

        rootPage = TabsPage;

        constructor(public platform: Platform, public alert: AlertController,
            private events: Events,
            public radioService: RadioPage,
            private codePush: CodePush,
            private ngZone: NgZone,
            public http:Http) { }

        ngOnInit() {

            this.platform.ready().then(() => {
                // My custom code
            });
        }
    }

Body:
You should remove

providers: [Http]

from your component annotation.

And '@angular/Http' needs to be in lowercase, '@angular/http'


问:
How to prevent the activity from loading twice on pressing the button
I am trying to prevent the activity from loading twice if I press the button twice instantly after the first click.

I have an activity which loads on click of a button, say

```<code> myButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
       //Load another activity
    }
});
</code>```

Now because the activity to be loaded has network calls, it takes a little time to load (MVC). I do show a loading view for this but if I press the button twice before that, I can see the activity being loaded twice.

Do any one know how to prevent this?

答:
Since SO doesn't allow me to comment on other answers, I have to pollute this thread with a new answer.

Common answers for the "activity opens twice" problem and my experiences with these solutions (Android 7.1.1):

Disable button that starts the activity: Works but feels a little clumsy. If you have multiple ways to start the activity in your app (e.g. a button in the action bar AND by clicking on an item in a list view), you have to keep track of the enabled/disabled state of multiple GUI elements. Plus it's not very convenient to disable clicked items in a list view, for example. So, not a very universal approach.

launchMode="singleInstance": Not working with startActivityForResult(), breaks back navigation with startActivity(), not recommended for regular applications by Android manifest documentation.

launchMode="singleTask": Not working with startActivityForResult(), not recommended for regular applications by Android manifest documentation.

FLAG_ACTIVITY_REORDER_TO_FRONT: Breaks back button.

FLAG_ACTIVITY_SINGLE_TOP: Not working, activity is still opened twice.

FLAG_ACTIVITY_CLEAR_TOP: This is the only one working for me.

EDIT: This was for starting activities with startActivity(). When using startActivityForResult() I need to set both FLAG_ACTIVITY_SINGLE_TOP and FLAG_ACTIVITY_CLEAR_TOP.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to prevent the activity from loading twice if I press the button twice instantly after the first click.

I have an activity which loads on click of a button, say

 myButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
       //Load another activity
    }
});

Now because the activity to be loaded has network calls, it takes a little time to load (MVC). I do show a loading view for this but if I press the button twice before that, I can see the activity being loaded twice.

Do any one know how to prevent this?