问:
How do I align 3 circular images?
So I have this code:

/*--- Circular images --- */
.img-circular1, .img-circular2, .img-circular3{
 width: 200px;
 height: 200px;
 background-size: cover;
 display: block;
  border-radius: 100px;
 -webkit-border-radius: 100px;
 -moz-border-radius: 100px;
 float: left;
 background: red;
}
.img-circular1{
   background-image: url('/Images/learn.jpg');
}
.img-circular2{
   background-image: url('/Images/watch.jpg');
}
.img-circular3{
   background-image: url('/Images/practice.jpg');
}
#container1
{
top: 100px;
    position: relative;
    margin-left:auto;
    margin-right:auto;
    width:70%;
    background-color: green;
    overflow: auto;
    bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container1" style="padding-bottom: 500px;">
<div class="img-circular1"></div>
<div class="img-circular2"></div>
<div class="img-circular3"></div>
<div class="img-circular1"></div>
</div></code>```

I have no managed to get 2 of them to show in a green box. But the third (which I duplicated before and after the other 2) will not show for some reason?

Also, they are not equidistant apart - how can I get them an equal spacing apart?

Please help

NOTE: Instead of images there are red circles, just for visibility reasons.

答:
Apply float: left on images themself, not on container:

/*--- Circular images --- */
.img-circular1, .img-circular2, .img-circular3{
 /*width: 200px;*/
 /*height: 200px;*/
 width: 100px;
 height: 100px;
 background-size: cover;
 display: block;
  border-radius: 100px;
 -webkit-border-radius: 100px;
 -moz-border-radius: 100px;
 float: left;
}
.img-circular1{
   background-image: url('/Imageslearn.jpg');
   background: #aaa; /*added to as an alternative to image*/
}
.img-circular2{
   background-image: url('/Images/watch.jpg');
   background: #aaa; /*added to as an alternative to image*/
}
.img-circular3{
   background-image: url('/Images/practice.jpg');
      background: #aaa; /*added to as an alternative to image*/
}
.container1{
 left: 15%;
 width: 70%;
/*  float: left;  */
 height: 300px;
 position: relative;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container1">
<div class="img-circular1"></div>
<div class="img-circular2"></div>
<div class="img-circular3"></div>
</div></code>```

To answer your second question:

wrap circles in some other div

make their width be some percentage value and float them left

set margin on circles to margin: 0 auto.

Here is prototype for you to study:

#green {
  background: green;
  padding: 10px;
  overflow: auto;
}

#blue {
  background: blue;
  width: 50%;
  float: left;
  border: 1px solid #fff;
  box-sizing: border-box; /*good for when there is border or padding*/
}

#red {
  background: red;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="green">
  <div id="blue">
    <div id="red"></div>
  </div>
  <div id="blue">
    <div id="red"></div>
  </div>
  <div id="blue">
    <div id="red"></div>
  </div>
  <div id="blue">
    <div id="red"></div>
  </div>
</div></code>```

Title: How do I align 3 circular images?

Body:
So I have this code:

/*--- Circular images --- */
.img-circular1, .img-circular2, .img-circular3{
 width: 200px;
 height: 200px;
 background-size: cover;
 display: block;
  border-radius: 100px;
 -webkit-border-radius: 100px;
 -moz-border-radius: 100px;
 float: left;
 background: red;
}
.img-circular1{
   background-image: url('/Images/learn.jpg');
}
.img-circular2{
   background-image: url('/Images/watch.jpg');
}
.img-circular3{
   background-image: url('/Images/practice.jpg');
}
#container1
{
top: 100px;
    position: relative;
    margin-left:auto;
    margin-right:auto;
    width:70%;
    background-color: green;
    overflow: auto;
    bottom: 0;
}

I have no managed to get 2 of them to show in a green box. But the third (which I duplicated before and after the other 2) will not show for some reason?

Also, they are not equidistant apart - how can I get them an equal spacing apart?

Please help

NOTE: Instead of images there are red circles, just for visibility reasons.

Body:
Apply float: left on images themself, not on container:

/*--- Circular images --- */
.img-circular1, .img-circular2, .img-circular3{
 /*width: 200px;*/
 /*height: 200px;*/
 width: 100px;
 height: 100px;
 background-size: cover;
 display: block;
  border-radius: 100px;
 -webkit-border-radius: 100px;
 -moz-border-radius: 100px;
 float: left;
}
.img-circular1{
   background-image: url('/Imageslearn.jpg');
   background: #aaa; /*added to as an alternative to image*/
}
.img-circular2{
   background-image: url('/Images/watch.jpg');
   background: #aaa; /*added to as an alternative to image*/
}
.img-circular3{
   background-image: url('/Images/practice.jpg');
      background: #aaa; /*added to as an alternative to image*/
}
.container1{
 left: 15%;
 width: 70%;
/*  float: left;  */
 height: 300px;
 position: relative;
  }

<div class="container1">
<div class="img-circular1"></div>
<div class="img-circular2"></div>
<div class="img-circular3"></div>
</div>

To answer your second question:

wrap circles in some other div

make their width be some percentage value and float them left

set margin on circles to margin: 0 auto.

Here is prototype for you to study:

#green {
  background: green;
  padding: 10px;
  overflow: auto;
}

#blue {
  background: blue;
  width: 50%;
  float: left;
  border: 1px solid #fff;
  box-sizing: border-box; /*good for when there is border or padding*/
}

#red {
  background: red;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin: 0 auto;
}

<div id="green">
  <div id="blue">
    <div id="red"></div>
  </div>
  <div id="blue">
    <div id="red"></div>
  </div>
  <div id="blue">
    <div id="red"></div>
  </div>
  <div id="blue">
    <div id="red"></div>
  </div>
</div>


来源: stackexchange

问:
When to make pointer point to a struct on the heap vs on the stack?
```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct foo {
    char* text;
    int num;
} foo;

int main(void) {

    foo* a = malloc(sizeof(foo));
    a->text = "Something";
    a->num = 4;
    printf("%s %d\n", a->text, a->num);

    foo b;
    b.text = "Something";
    b.num = 4;
    foo* c = &b;
    printf("%s %d", c->text, c->num);

    return 0;
}
</code>```

Both print the exact same thing. The only difference between foo* a and foo* c is where each one points to. Which one should be preferred? I usually see malloc() more but I don't understand why.

答:
I think you should malloc() only for bigger data. You should consider that malloc() needs more time because it must find search for a data block in the heap and reserve it. If you use the struct on stack this is not necessary. So it really depends on what you are doing.

Edit: Also you should think of the scope of the variable. If the struct is needed only within the function I would prefer the stack.

ContentLicense: CC BY-SA 3.0

Body:
#include <stdio.h>
#include <stdlib.h>

typedef struct foo {
    char* text;
    int num;
} foo;

int main(void) {

    foo* a = malloc(sizeof(foo));
    a->text = "Something";
    a->num = 4;
    printf("%s %d\n", a->text, a->num);

    foo b;
    b.text = "Something";
    b.num = 4;
    foo* c = &b;
    printf("%s %d", c->text, c->num);

    return 0;
}

Both print the exact same thing. The only difference between foo* a and foo* c is where each one points to. Which one should be preferred? I usually see malloc() more but I don't understand why.


问:
how to set time out for sql query transaction in java application
how to set time out for sql query transaction in java application which uses SpringJDBC or Hibernate.
Say in banking application we need to execute query in stipulated time (3 secs)</p>

答:
You can try</p>

```<code>JdbcTemplate template = new JdbcTemplate(dataSource);
template.setQueryTimeout(3);
</code>```

Body:
You can try

JdbcTemplate template = new JdbcTemplate(dataSource);
template.setQueryTimeout(3);


问:
Excel VBA type mismatch (error 13) for sheetname reference from a range on another sheet
I have Personal.xls VBA code/macros that are designed to reformat any file of a certain structure that the code is run on. One of the tasks is to create a series of filtered tab sheets from a primary data sheet provided in the original file. I then create a new worksheet that creates checkboxes adjacent to a sheetname reference list.

I want to hide or unhide checked the underlying sheets for checked boxes. I created a button that automatically will run a macro when pressed (after checkboxes have been selected) that loops through the sheetnames and sets them visible or not. Being that I'm such a dummy...

I cannot get past syntax for objects and get the loop to perform without an error 13 type mismatch error. Here is the code I'm running and an attached picture of the active sheet that the code is referencing.

NB: D is the column where I'm storing the linked cell data for range A1 to "the number of sheets in the workbook".

```<code>Public Sub Button_Click()
 Dim I As Integer
 For I = 1 To Sheets.Count
 If Range("AZ" & I).Value = False Or Range("AZ" & I) = Empty Then
 Sheets(Range("A" & I)).Visible = False
 Else:
 Sheets(Range("A" & I)).Visible = True
 End If
 Next
 End Sub
</code>```

答:
Try this:

```<code>Public Sub Button_Click()
 Dim I As Integer
 Dim SheetName as String

 For I = 1 To Sheets.Count
 SheetName = Range("A" & I).Value
 If Range("AZ" & I).Value = False Or Range("AZ" & I) = Empty Then
 Sheets(SheetName).Visible = False
 Else:
 Sheets(SheetName).Visible = True
 End If
 Next
 End Sub
</code>```

I think the type mismatch is coming from the Sheets(Range("A" & I)).Visible line. The Sheets object requires a string that contains the name of a valid sheet in the workbook. In your case, you are pointing to a range value, not a string. Since the Range value you pointed to contains the name of the sheet, I simply made the SheetName variable for the Sheets object to point to. Since SheetName is a string, it should not throw any 'type mismatch' errors. I hope this helps.

Body:
I have Personal.xls VBA code/macros that are designed to reformat any file of a certain structure that the code is run on. One of the tasks is to create a series of filtered tab sheets from a primary data sheet provided in the original file. I then create a new worksheet that creates checkboxes adjacent to a sheetname reference list.

I want to hide or unhide checked the underlying sheets for checked boxes. I created a button that automatically will run a macro when pressed (after checkboxes have been selected) that loops through the sheetnames and sets them visible or not. Being that I'm such a dummy...

I cannot get past syntax for objects and get the loop to perform without an error 13 type mismatch error. Here is the code I'm running and an attached picture of the active sheet that the code is referencing.

NB: D is the column where I'm storing the linked cell data for range A1 to "the number of sheets in the workbook".

Public Sub Button_Click()
 Dim I As Integer
 For I = 1 To Sheets.Count
 If Range("AZ" & I).Value = False Or Range("AZ" & I) = Empty Then
 Sheets(Range("A" & I)).Visible = False
 Else:
 Sheets(Range("A" & I)).Visible = True
 End If
 Next
 End Sub

Body:
Try this:

Public Sub Button_Click()
 Dim I As Integer
 Dim SheetName as String

 For I = 1 To Sheets.Count
 SheetName = Range("A" & I).Value
 If Range("AZ" & I).Value = False Or Range("AZ" & I) = Empty Then
 Sheets(SheetName).Visible = False
 Else:
 Sheets(SheetName).Visible = True
 End If
 Next
 End Sub

I think the type mismatch is coming from the Sheets(Range("A" & I)).Visible line. The Sheets object requires a string that contains the name of a valid sheet in the workbook. In your case, you are pointing to a range value, not a string. Since the Range value you pointed to contains the name of the sheet, I simply made the SheetName variable for the Sheets object to point to. Since SheetName is a string, it should not throw any 'type mismatch' errors. I hope this helps.


问:
Clion "Cannot load CMake project: CMake executable is incorrect" issue
I ran into a problem while trying to use Clion.
I imported a project, yet all off the headers and .cpp files are greyed out. The error shown is as in the title: "Cannot load CMake project: CMake executable is incorrect".Here is a screenshot of it.
It's worth noting that I'm working with kubuntu and have downloaded all of the following: gcc, g++, make, cmake, gdb.
I would love some help with solving this problem so I could start working with Clion.
Thanks in advance.</p>

答:
I just ran into this. Deleting the project's .idea directory and having clion recreate it fixed the issue for me.

Clion also reported that Bundled Cmake does not work in this enviroment

And when setting the actual path to the cmake binary it said it wasn't there when it was.


问:
How do I set up udev rules for debugging a physical android device with Android Studio?
In the past I've never had to set this up, but I updated Android Studio to version 2.3.1 today and got this error when clicking debug:

```<code>05/03 17:19:19: Launching app
$ adb push app-debug.apk {path on my computer}
com.android.ddmlib.AdbCommandRejectedException: insufficient permissions for device: verify udev rules.
See [http://developer.android.com/tools/device.html] for more information.
Error while Installing APK
</code>```

I went to the page they specified, where they told me to make the file /etc/udev/rules.d/51-android.rules

So I did, adding this line:

SUBSYSTEM=="usb", ATTR{idVendor}=="12d1", MODE="0666", GROUP="plugdev"

For my (Huawei) Nexus 6P.

I also added the debug section to build.grade, as they specified.

However, I still get the same error. I tried substituting my own linux user group in place of plugdev, but that didn't fix the issue either. Any suggestions?

答:
You probably did not add the proper ATTR{idVendor} attribute. To do that, do the following:

```<code>$ sudo adb devices
List of devices attached
adb server is out of date.  killing...
* daemon started successfully *
XXXXyyyy    device
</code>```

After running adb devices you'll see the output above.

Copy the first 4 bytes of the device output (so, XXXX). Replace those with ATTR{idVendor}=="XXXX" in /etc/udev/rules.d/51-android.rules and restart udev.

As the comment below indicated, the above method may not work; another option is to use lsusb or tail dmesg.

Body:
In the past I've never had to set this up, but I updated Android Studio to version 2.3.1 today and got this error when clicking debug:

05/03 17:19:19: Launching app
$ adb push app-debug.apk {path on my computer}
com.android.ddmlib.AdbCommandRejectedException: insufficient permissions for device: verify udev rules.
See [http://developer.android.com/tools/device.html] for more information.
Error while Installing APK

I went to the page they specified, where they told me to make the file /etc/udev/rules.d/51-android.rules

So I did, adding this line:

SUBSYSTEM=="usb", ATTR{idVendor}=="12d1", MODE="0666", GROUP="plugdev"

For my (Huawei) Nexus 6P.

I also added the debug section to build.grade, as they specified.

However, I still get the same error. I tried substituting my own linux user group in place of plugdev, but that didn't fix the issue either. Any suggestions?

Body:
You probably did not add the proper ATTR{idVendor} attribute. To do that, do the following:

$ sudo adb devices
List of devices attached
adb server is out of date.  killing...
* daemon started successfully *
XXXXyyyy    device

After running adb devices you'll see the output above.

Copy the first 4 bytes of the device output (so, XXXX). Replace those with ATTR{idVendor}=="XXXX" in /etc/udev/rules.d/51-android.rules and restart udev.

As the comment below indicated, the above method may not work; another option is to use lsusb or tail dmesg.

ContentLicense: CC BY-SA 4.0


问:
Wordpress - I can reach by url normal php files but no uploaded ones
I'm working on a Wordpress project, and I'm trying to create a product via woocommerce rest API, I made it work in local, but when I upload the files to the server, I just can't reach via URL my file, for example,
If I write:

```<code>    $.get('http://example.com/wp-includes/option.php')
    .done(function() {
        alert('Correct');
    }).fail(function() {
        alert('Nope');
})
</code>```

An alert with Correct appears, but, if I write:

```<code>    $.get('http://example.com/wp-includes/createProduct.php')
    .done(function() {
        alert('Correct');
    }).fail(function() {
        alert('Nope');
})
</code>```

An alert with Nope will be shown, so I don't get why it reaches all its 'native' files and not that one I uploaded. Files like .js in the js folder are being read correctly, but this .php just can't be reached. And I need it for an AJAX :c

Hope someone can help me and thanks.

答:
Check your directory/file permissions.

On linux try running ll -h inside the wp-includes directory to compare the user and read/write permissions of the files being created.

For instance, you may be user ubuntu, ec2-user, something like that, but your files are being created and owned by root.

EDIT:

Upload your files through cpanel's file manager.

Whether I upload the file using winscp or cpanel file manager, it doesn't affect the read/write permissions, it's always 0644, which should work.  BUT uploading through cpanel's file manager, the ownership for the file is the same where as using winscp to upload the user is different.

Body:
I'm working on a Wordpress project, and I'm trying to create a product via woocommerce rest API, I made it work in local, but when I upload the files to the server, I just can't reach via URL my file, for example,
If I write:

    $.get('http://example.com/wp-includes/option.php')
    .done(function() {
        alert('Correct');
    }).fail(function() {
        alert('Nope');
})

An alert with Correct appears, but, if I write:

    $.get('http://example.com/wp-includes/createProduct.php')
    .done(function() {
        alert('Correct');
    }).fail(function() {
        alert('Nope');
})

An alert with Nope will be shown, so I don't get why it reaches all its 'native' files and not that one I uploaded. Files like .js in the js folder are being read correctly, but this .php just can't be reached. And I need it for an AJAX :c

Hope someone can help me and thanks.


问:
How to close/hide app main window?
I have an app that has a main window and secondary windows.

In certain situations, I would like to only display a secondary window when the user launches the app.

The problem is that the app's main window is automatically launched, so I after programamtically opening the secondary window I am left with both the main and secondary windows.

Is there any way I can hide the main window?  (Ie, emulate the user pressing the "close button" in the top right corner of the main window?)

答: Why closing/hiding the main window? You could show the content of the secondary window in the main window (that is created when app's launched) and if user wants to show the main window you could show its content in secondary window.</p>

Title: How to close/hide app main window?


问:
Instagram API with Laravel 5.4
I am using an Instagram package vinkla to get the user data to my app.

Here is the code that I use in order to get the results:

```<code>public function instagram()
{
   $insta = new Instagram();

   $getUser = $insta->get('gopro');

   dd($getUser);
}
</code>```

When I diedump the results I get this array on return:

```<code>array:20 [▼
  0 => {#205 ▼
    +"id": "1552323772757218591_28902942"
    +"code": "BWK9j8rlpUf"
    +"user": {#208 ▶}
    +"images": {#202 ▼
      +"thumbnail": {#203 ▶}
      +"low_resolution": {#214 ▶}
      +"standard_resolution": {#204 ▼
        +"width": 640
        +"height": 640
        +"url": "https://scontent-frt3-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19624693_104174916895493_9107740182827761664_n.jpg"
      }
    }
    +"created_time": "1499271435"
    +"caption": {#207 ▶}
    +"likes": {#215 ▶}
    +"comments": {#222 ▶}
    +"can_view_comments": true
    +"can_delete_comments": false
    +"type": "image"
    +"link": "https://www.instagram.com/p/BWK9j8rlpUf/"
    +"location": {#223 ▶}
    +"alt_media_url": null
  }
  1 => {#224 ▶}
  2 => {#251 ▶}
  3 => {#278 ▶}

]
</code>```

Now the thing that I am trying to approach:
I want to integrate some images on my laravel app. Basically I want to get the image url from each array  images->standard_resolution->url.

I have tried to iterate the array with double foreach no luck so far.

Any suggestion on how to achieve that ?

答:
Hi you may be getting the results in array you can convert the array to collection there is nice helper in laravel

```<code>   $yourCollection =  collect(yourArray);
</code>```

then you can apply queries on Collection same as Eloquent and also apply the foreach loop.

Edit 2

You can do this also by

```<code> $yourArray = json_decode($getUser,true);
</code>```

you can do apply a loop on it.

```<code>@foreach($yourArray as $arr){
    //do what ever you want to do with
   $arr['standard_resolution']['url'];
  }
</code>```

I hope this helps.

Title: Instagram API with Laravel 5.4

Body:
I am using an Instagram package vinkla to get the user data to my app.

Here is the code that I use in order to get the results:

public function instagram()
{
   $insta = new Instagram();

   $getUser = $insta->get('gopro');

   dd($getUser);
}

When I diedump the results I get this array on return:

array:20 [▼
  0 => {#205 ▼
    +"id": "1552323772757218591_28902942"
    +"code": "BWK9j8rlpUf"
    +"user": {#208 ▶}
    +"images": {#202 ▼
      +"thumbnail": {#203 ▶}
      +"low_resolution": {#214 ▶}
      +"standard_resolution": {#204 ▼
        +"width": 640
        +"height": 640
        +"url": "https://scontent-frt3-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19624693_104174916895493_9107740182827761664_n.jpg"
      }
    }
    +"created_time": "1499271435"
    +"caption": {#207 ▶}
    +"likes": {#215 ▶}
    +"comments": {#222 ▶}
    +"can_view_comments": true
    +"can_delete_comments": false
    +"type": "image"
    +"link": "https://www.instagram.com/p/BWK9j8rlpUf/"
    +"location": {#223 ▶}
    +"alt_media_url": null
  }
  1 => {#224 ▶}
  2 => {#251 ▶}
  3 => {#278 ▶}

]

Now the thing that I am trying to approach:
I want to integrate some images on my laravel app. Basically I want to get the image url from each array  images->standard_resolution->url.

I have tried to iterate the array with double foreach no luck so far.

Any suggestion on how to achieve that ?

Body:
Hi you may be getting the results in array you can convert the array to collection there is nice helper in laravel

   $yourCollection =  collect(yourArray);

then you can apply queries on Collection same as Eloquent and also apply the foreach loop.

Edit 2

You can do this also by

 $yourArray = json_decode($getUser,true);

you can do apply a loop on it.

@foreach($yourArray as $arr){
    //do what ever you want to do with
   $arr['standard_resolution']['url'];
  }

I hope this helps.


问:
a simple person class in objective c
I'm starting to learn objective c, I made a simple person class, i get 6 errors,
expected specifier-qualifier-list before '-' token

just wondering if someone can explain to me what I'm doing wrong,

thanks

```<code>#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;

    -(void) setFName:(NSString *) theFirstName;
    -(void) setLName:(NSString *) theLastName;
    -(void) printName;
}
@end

@implementation Person
{

    -(void) setFName:(NSString *) theFirstName
    {
        firstName = [[NSString alloc]initWithString: theFirstName];
    }

    -(void) setLName:(NSString *) theLastName
    {
        lastName = [[NSString alloc]initWithString: theLastName];
    }

    -(void) printName
    {
        NSLog(@"The person's full name is",firstName,lastName);
    }

}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Person *person = [[Person alloc] init];

    [person setFName:@"Amir"];
    [person setLName:@"Karimian"];
    [person printName];

    [person release];
    [pool drain];
    return 0;
}
</code>```

答:
Also, apart from taskinoor's answer, it's good practice to implement a -(void)dealloc method in your class:

```<code>-(void)dealloc {
    [firstName release]; //since they have been alloced.
    [lastName release];
    [super dealloc];
}
</code>```

Note that if you wanted to use properties, like Dave DeLong, you should be careful about choosing @property(assign), @property(copy) or @property(retain) and managing whether you release the NSStrings or not.

ContentLicense: CC BY-SA 2.5

Title: a simple person class in objective c

Body:
I'm starting to learn objective c, I made a simple person class, i get 6 errors,
expected specifier-qualifier-list before '-' token

just wondering if someone can explain to me what I'm doing wrong,

thanks

#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;

    -(void) setFName:(NSString *) theFirstName;
    -(void) setLName:(NSString *) theLastName;
    -(void) printName;
}
@end

@implementation Person
{

    -(void) setFName:(NSString *) theFirstName
    {
        firstName = [[NSString alloc]initWithString: theFirstName];
    }

    -(void) setLName:(NSString *) theLastName
    {
        lastName = [[NSString alloc]initWithString: theLastName];
    }

    -(void) printName
    {
        NSLog(@"The person's full name is",firstName,lastName);
    }

}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Person *person = [[Person alloc] init];

    [person setFName:@"Amir"];
    [person setLName:@"Karimian"];
    [person printName];

    [person release];
    [pool drain];
    return 0;
}

Body:
Also, apart from taskinoor's answer, it's good practice to implement a -(void)dealloc method in your class:

-(void)dealloc {
    [firstName release]; //since they have been alloced.
    [lastName release];
    [super dealloc];
}

Note that if you wanted to use properties, like Dave DeLong, you should be careful about choosing @property(assign), @property(copy) or @property(retain) and managing whether you release the NSStrings or not.


问:
In a Unity3D - Android project .. how to get memory warnings?
How to be alerted of memory warnings?  Unity3D, building to Android.

Cheers.

答:
You can subscribe to Application.lowMemory Documentation

For example, in some monoBehaviour starting your game:

```<code>private void Start()
{
    Application.lowMemory += ReportSystemLowMemory;
}

private void ReportSystemLowMemory()
{
    Debug.LogWarning("Warning: Low memory");
}
</code>```

Be sure to don't subscribe ReportSystemLowMemory more than once.

Also unsubscribing it would be a good practice, ie Application.lowMemory -= ReportSystemLowMemory when you are close your app/game.

Body:
You can subscribe to Application.lowMemory Documentation

For example, in some monoBehaviour starting your game:

private void Start()
{
    Application.lowMemory += ReportSystemLowMemory;
}

private void ReportSystemLowMemory()
{
    Debug.LogWarning("Warning: Low memory");
}

Be sure to don't subscribe ReportSystemLowMemory more than once.

Also unsubscribing it would be a good practice, ie Application.lowMemory -= ReportSystemLowMemory when you are close your app/game.


问:
Client Mongoose C app to query LAN DNS?
I'm experimenting with Cesanta's Mongoose server/"client" networking library in C. This is in Windows 7 x64 using Pelle's C. I'm trying to make a LAN-capable text messaging app on port 90 as two dialog-as-main executables (server and client) to support 20 connections to the server. FWIW, I'm using a fast timer to call mg_mgr_poll(&mgr, 0) which retains UI responsiveness and uses very little CPU.

Cesanta gives good examples of server communication setup and that works flawlessly.  I can also get a client to connect to the server, but the server's IP address must be used in mg_connect().

Since the server's hostname is public to the LAN, I was hoping to ask the LAN for this host's IP. I had this working in VB awhile ago:

```<code>Dim host As New IPHostEntry
host = Dns.GetHostEntry(hostName)
Return host.AddressList.GetValue(0)
</code>```

However as the VB project got bigger, VB got stranger and much more difficult, so I migrated to good old C. (Perhaps it was falling back to a NetBIOS name query, dunno.) No, I'd rather not migrate again to C# or C++/VS.

The Cesanta documentation on DNS resolution is quite vague. Code like mg_connect(&mgr, "MyServerPC:90", ev_handler); simply crashes, despite mg_connect stating it will try and resolve hostnames.

Can Mongoose resolve a local (LAN) hostname, and how? Or is this futile, and should everything be done manually in Winsock?

答:
i have the same issue as you.

First i think that the mg_connect should not crashes, only if you try to do something with the returned connection which is null.

Second, mongoose try to resolve the address using DNS from specific location at the registry and it's take the first address he can find.

The location is :SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces
,check here in each of the interfaces.
i think there is a bug here (i am going to open an issues for it and also try to fix it and created a pull request).

Little update:

i have opend an issue and create a pull request about this issue.
https://github.com/cesanta/mongoose/issues/832

https://github.com/cesanta/mongoose/pull/833

Mongoose check each interface for the Value of NameServer and DhcpNameServer ,and return the first one (which is not empty) it can find but if it found an empty value for NameServer it doesn't check DhcpNameServer(and therefore miss the correct address) which will cause an error and direct the name resolving to a default server(i think it's google DNS -8.8.8.8).

You can fix this by going to the registry and adding the value of your DNS address to the registry key-NameServer

this is a comment from mongoose code:

```<code>    /*
     * See https://github.com/cesanta/mongoose/issues/176
     * The value taken from the registry can be empty, a single
     * IP address, or multiple IP addresses separated by comma.
     * If it's empty, check the next interface.
     * If it's multiple IP addresses, take the first one.
     */
</code>```

Title: Client Mongoose C app to query LAN DNS?

Body:
I'm experimenting with Cesanta's Mongoose server/"client" networking library in C. This is in Windows 7 x64 using Pelle's C. I'm trying to make a LAN-capable text messaging app on port 90 as two dialog-as-main executables (server and client) to support 20 connections to the server. FWIW, I'm using a fast timer to call mg_mgr_poll(&mgr, 0) which retains UI responsiveness and uses very little CPU.

Cesanta gives good examples of server communication setup and that works flawlessly.  I can also get a client to connect to the server, but the server's IP address must be used in mg_connect().

Since the server's hostname is public to the LAN, I was hoping to ask the LAN for this host's IP. I had this working in VB awhile ago:

Dim host As New IPHostEntry
host = Dns.GetHostEntry(hostName)
Return host.AddressList.GetValue(0)

However as the VB project got bigger, VB got stranger and much more difficult, so I migrated to good old C. (Perhaps it was falling back to a NetBIOS name query, dunno.) No, I'd rather not migrate again to C# or C++/VS.

The Cesanta documentation on DNS resolution is quite vague. Code like mg_connect(&mgr, "MyServerPC:90", ev_handler); simply crashes, despite mg_connect stating it will try and resolve hostnames.

Can Mongoose resolve a local (LAN) hostname, and how? Or is this futile, and should everything be done manually in Winsock?

Body:
i have the same issue as you.

First i think that the mg_connect should not crashes, only if you try to do something with the returned connection which is null.

Second, mongoose try to resolve the address using DNS from specific location at the registry and it's take the first address he can find.

The location is :SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces
,check here in each of the interfaces.
i think there is a bug here (i am going to open an issues for it and also try to fix it and created a pull request).

Little update:

i have opend an issue and create a pull request about this issue.
https://github.com/cesanta/mongoose/issues/832

https://github.com/cesanta/mongoose/pull/833

Mongoose check each interface for the Value of NameServer and DhcpNameServer ,and return the first one (which is not empty) it can find but if it found an empty value for NameServer it doesn't check DhcpNameServer(and therefore miss the correct address) which will cause an error and direct the name resolving to a default server(i think it's google DNS -8.8.8.8).

You can fix this by going to the registry and adding the value of your DNS address to the registry key-NameServer

this is a comment from mongoose code:

    /*
     * See https://github.com/cesanta/mongoose/issues/176
     * The value taken from the registry can be empty, a single
     * IP address, or multiple IP addresses separated by comma.
     * If it's empty, check the next interface.
     * If it's multiple IP addresses, take the first one.
     */


问:
Using wildcards in HAVING
Im trying to get a list of all the countries that have atleast 2 customers with yahoo email.

So far I came up with this:

```<code>SELECT Country
FROM Customer
GROUP BY Country
HAVING COUNT(Email LIKE '%yahoo%')>= 2
</code>```

This doesnt work though. Probably because I cant use LIKE in HAVING clause. I tried to use it in where clause, but I cant use aggregate functions there. Do you know how to make this work? Assume standard sql. Thx

答:
Use a CTE to build your aggregated list of filtered countries.

SETUP TEST DATA

```<code>IF OBJECT_ID('tempdb.dbo.#td', 'U') IS NOT NULL
  DROP TABLE #td;

CREATE TABLE #td ( country varchar(10), email varchar(20) ) ;

INSERT INTO #td ( country, email )
VALUES
       ('US','bob@builder.com')
     , ('GB','bob@yahoo.com')
     , ('US','bill@yahoo.com')
     , ('US','ted@yahoo.com')
     , ('FR','joe@friday.com')
     , ('GR','jim@gmail.com')
     , ('NZ','mrmaori@yahoo.com')
     , ('NZ','kiwi@yahoo.com')
     , ('US','rufus@yahoo.com')
;
</code>```

QUERY

```<code>WITH CTE AS(
   SELECT country, count(*) AS countryCount
   FROM #td
   WHERE email LIKE '%yahoo%'
   GROUP BY country
)
SELECT CTE.country
FROM CTE
WHERE CTE.countryCount >= 2
;
</code>```

This will give you NZ and US as the only 2 countries. US has 3 yahoo and 1 non-yahoo. NZ has 2 yahoo. GB has only 1 yahoo and is excluded.

Title: Using wildcards in HAVING

Body:
Im trying to get a list of all the countries that have atleast 2 customers with yahoo email.

So far I came up with this:

SELECT Country
FROM Customer
GROUP BY Country
HAVING COUNT(Email LIKE '%yahoo%')>= 2

This doesnt work though. Probably because I cant use LIKE in HAVING clause. I tried to use it in where clause, but I cant use aggregate functions there. Do you know how to make this work? Assume standard sql. Thx

Body:
Use a CTE to build your aggregated list of filtered countries.

SETUP TEST DATA

IF OBJECT_ID('tempdb.dbo.#td', 'U') IS NOT NULL
  DROP TABLE #td;

CREATE TABLE #td ( country varchar(10), email varchar(20) ) ;

INSERT INTO #td ( country, email )
VALUES
       ('US','bob@builder.com')
     , ('GB','bob@yahoo.com')
     , ('US','bill@yahoo.com')
     , ('US','ted@yahoo.com')
     , ('FR','joe@friday.com')
     , ('GR','jim@gmail.com')
     , ('NZ','mrmaori@yahoo.com')
     , ('NZ','kiwi@yahoo.com')
     , ('US','rufus@yahoo.com')
;

QUERY

WITH CTE AS(
   SELECT country, count(*) AS countryCount
   FROM #td
   WHERE email LIKE '%yahoo%'
   GROUP BY country
)
SELECT CTE.country
FROM CTE
WHERE CTE.countryCount >= 2
;

This will give you NZ and US as the only 2 countries. US has 3 yahoo and 1 non-yahoo. NZ has 2 yahoo. GB has only 1 yahoo and is excluded.


问:
Accurate timing in iOS
I am looking at the 'Metronome' sample code from the iOS SDK (http://developer.apple.com/library/ios/#samplecode/Metronome/Introduction/Intro.html). I am running the metronome at 60 BPM, which means a tick every second. When I look at an external watch (the PC's watch), I see the metronome is running too slow - it misses about one beat each minute, which is app. 15msec of consistent error. The relevant code piece is:

```<code>- (void)startDriverTimer:(id)info {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Give the sound thread high priority to keep the timing steady.
    [NSThread setThreadPriority:1.0];
    BOOL continuePlaying = YES;

    while (continuePlaying) {  // Loop until cancelled.
        // An autorelease pool to prevent the build-up of temporary objects.
        NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
        [self playSound];

        [self performSelectorOnMainThread:@selector(animateArmToOppositeExtreme) withObject:nil waitUntilDone:NO];
        NSDate *curtainTime = [[NSDate alloc] initWithTimeIntervalSinceNow:self.duration];
        NSDate *currentTime = [[NSDate alloc] init];
        // Wake up periodically to see if we've been cancelled.
        while (continuePlaying && ([currentTime compare:curtainTime] != NSOrderedDescending)) {
            if ([soundPlayerThread isCancelled] == YES) {
                continuePlaying = NO;
            }
            [NSThread sleepForTimeInterval:0.01];
            [currentTime release];
            currentTime = [[NSDate alloc] init];
        }

        [curtainTime release];
        [currentTime release];
        [loopPool drain];
    }
    [pool drain];
}
</code>```

Where

self.duration

is 1.0 second in the case of 60 BPM. I wonder where this error comes from, and how can I make a more accurate timer/interval counter.

EDIT: The problem exists as well when I change the sleep time to smaller values, e.g .001.

EDIT2 (update): The problem exists as well when I use the CFAbsoluteTimeGetCurrent() method for timing. When I use the same method to measure timing between a button tap events, the timing seems accurate - I tap once a second (while watching a watch), and the measured rate is 60 BPM (on average). So I guess it must be some issue with the NSThread (?). Another thing is that on the device (iPod) the problem seems more severe then on the simulator.

答:
Ok, I have some answers after doing some more tests, so I am sharing it with anyone who is interested.

I've placed a variable to measure time intervals between ticks, inside the play method (the method that actually sends the play message to the AVAudioPlayer object), and as my simple compare-to-external-watch experiment showed, the 60 BPM was too slow - I got these time intervals (in seconds):

```<code>1.004915
1.009982
1.010014
1.010013
1.010028
1.010105
1.010095
1.010105
</code>```

My conclusion was that some overhead time elapses after each 1-second-interval is counted, and that extra time (about 10msec) is accumulated to a noticeable amount after a few tens of seconds --- quite bad for a metronome. So instead of measuring the interval between calls, I decided to measure the total interval from the first call, so that the error won't be accumulated. In other words I've replaced this condition:

```<code>while (continuePlaying && ((currentTime0 + [duration doubleValue]) >= currentTime1)
</code>```

with this condition:

```<code>while (continuePlaying && ((_currentTime0 + _cnt * [duration doubleValue]) >= currentTime1 ))
</code>```

where now _currentTime0 and _cnt are class members (sorry if it's a c++ jargon, I am quite new to Obj-C), the former holds the time stamp of the first call to the method, and the latter is an int counting number of ticks (==function calls). This resulted in the following measured time intervals:

```<code>1.003942
0.999754
0.999959
1.000213
0.999974
0.999451
1.000581
0.999470
1.000370
0.999723
1.000244
1.000222
0.999869
</code>```

and it is evident even without calculating the average, that these values fluctuate around 1.0 second (and the average is close to 1.0 with at least a millisecond of accuracy).

I will be happy to hear more insights regarding what causes the extra time to elapse - 10msec sounds as eternity for a modern CPU - though I am not familiar with the specs of the iPod CPU (it's iPod 4G, and Wikipedia says the CUP is PowerVR SGX GPU 535 @ 200 MHz)

Title: Accurate timing in iOS

Body:
I am looking at the 'Metronome' sample code from the iOS SDK (http://developer.apple.com/library/ios/#samplecode/Metronome/Introduction/Intro.html). I am running the metronome at 60 BPM, which means a tick every second. When I look at an external watch (the PC's watch), I see the metronome is running too slow - it misses about one beat each minute, which is app. 15msec of consistent error. The relevant code piece is:

- (void)startDriverTimer:(id)info {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Give the sound thread high priority to keep the timing steady.
    [NSThread setThreadPriority:1.0];
    BOOL continuePlaying = YES;

    while (continuePlaying) {  // Loop until cancelled.
        // An autorelease pool to prevent the build-up of temporary objects.
        NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
        [self playSound];

        [self performSelectorOnMainThread:@selector(animateArmToOppositeExtreme) withObject:nil waitUntilDone:NO];
        NSDate *curtainTime = [[NSDate alloc] initWithTimeIntervalSinceNow:self.duration];
        NSDate *currentTime = [[NSDate alloc] init];
        // Wake up periodically to see if we've been cancelled.
        while (continuePlaying && ([currentTime compare:curtainTime] != NSOrderedDescending)) {
            if ([soundPlayerThread isCancelled] == YES) {
                continuePlaying = NO;
            }
            [NSThread sleepForTimeInterval:0.01];
            [currentTime release];
            currentTime = [[NSDate alloc] init];
        }

        [curtainTime release];
        [currentTime release];
        [loopPool drain];
    }
    [pool drain];
}

Where

self.duration

is 1.0 second in the case of 60 BPM. I wonder where this error comes from, and how can I make a more accurate timer/interval counter.

EDIT: The problem exists as well when I change the sleep time to smaller values, e.g .001.

EDIT2 (update): The problem exists as well when I use the CFAbsoluteTimeGetCurrent() method for timing. When I use the same method to measure timing between a button tap events, the timing seems accurate - I tap once a second (while watching a watch), and the measured rate is 60 BPM (on average). So I guess it must be some issue with the NSThread (?). Another thing is that on the device (iPod) the problem seems more severe then on the simulator.

Body:
Ok, I have some answers after doing some more tests, so I am sharing it with anyone who is interested.

I've placed a variable to measure time intervals between ticks, inside the play method (the method that actually sends the play message to the AVAudioPlayer object), and as my simple compare-to-external-watch experiment showed, the 60 BPM was too slow - I got these time intervals (in seconds):

1.004915
1.009982
1.010014
1.010013
1.010028
1.010105
1.010095
1.010105

My conclusion was that some overhead time elapses after each 1-second-interval is counted, and that extra time (about 10msec) is accumulated to a noticeable amount after a few tens of seconds --- quite bad for a metronome. So instead of measuring the interval between calls, I decided to measure the total interval from the first call, so that the error won't be accumulated. In other words I've replaced this condition:

while (continuePlaying && ((currentTime0 + [duration doubleValue]) >= currentTime1)

with this condition:

while (continuePlaying && ((_currentTime0 + _cnt * [duration doubleValue]) >= currentTime1 ))

where now _currentTime0 and _cnt are class members (sorry if it's a c++ jargon, I am quite new to Obj-C), the former holds the time stamp of the first call to the method, and the latter is an int counting number of ticks (==function calls). This resulted in the following measured time intervals:

1.003942
0.999754
0.999959
1.000213
0.999974
0.999451
1.000581
0.999470
1.000370
0.999723
1.000244
1.000222
0.999869

and it is evident even without calculating the average, that these values fluctuate around 1.0 second (and the average is close to 1.0 with at least a millisecond of accuracy).

I will be happy to hear more insights regarding what causes the extra time to elapse - 10msec sounds as eternity for a modern CPU - though I am not familiar with the specs of the iPod CPU (it's iPod 4G, and Wikipedia says the CUP is PowerVR SGX GPU 535 @ 200 MHz)


问:
Handling success and failure API JSON responses when json format is different for each
How do I handle a failure when my method only returns a single return type?

```<code> public async Task<User> GetUser(int userId)
{
    User user = null;
    HttpResponseMessage response = await client.GetAsync("/User/...");
    if (response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        user = JsonConvert.DeserializeObject<User>(result);
    }
    else
    {
        // ????
    }

    return user;
}
</code>```

Success:

```<code>{
    "a": 1,
    "b": 2,
    "c": 3
}
</code>```

Failure

```<code>{
    "error": "something has gone wrong..."
}
</code>```

In the failure case currently I am just returning null, but I want to return the error message.

The API I am using doesn't return the same JSON for both failure and success, so I'm not sure how to best handle the failure case.

答:
@Crowcoder's comment is the proper route. However, in case you ever had a successful response with a dynamic object structure this information could be useful. You can test a property on a returned object to see if it is undefined. In your case, and don't do this because you should use the status codes, you could do something like this:

```<code>if(result.error){
    //this is an error state
} else {
    //this was successful
}
</code>```

Body:
How do I handle a failure when my method only returns a single return type?

 public async Task<User> GetUser(int userId)
{
    User user = null;
    HttpResponseMessage response = await client.GetAsync("/User/...");
    if (response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        user = JsonConvert.DeserializeObject<User>(result);
    }
    else
    {
        // ????
    }

    return user;
}

Success:

{
    "a": 1,
    "b": 2,
    "c": 3
}

Failure

{
    "error": "something has gone wrong..."
}

In the failure case currently I am just returning null, but I want to return the error message.

The API I am using doesn't return the same JSON for both failure and success, so I'm not sure how to best handle the failure case.

Body:
@Crowcoder's comment is the proper route. However, in case you ever had a successful response with a dynamic object structure this information could be useful. You can test a property on a returned object to see if it is undefined. In your case, and don't do this because you should use the status codes, you could do something like this:

if(result.error){
    //this is an error state
} else {
    //this was successful
}


问:
Linux use interface for raw socket only
I'm having a OpenWrt Linux distribution for my embedded system. The device has 3 network interfaces: eth0, eth1 and wlan0.

One of the network interface (eth0) should be used for raw socket programming only. I'm able to create a socket with the parameters AF_PACKET, SOCK_RAW, ETH_P_ALL. The socket receives all network traffic, I can send packets and everything is OK.

But my problem is, that the OS is also using the interface for sending an reciving (e. g. ARP and ICMP requests/responses).

Is there any option that the interface is only used by my program and not by the OS itself?

答:
This is not possible to achieve with a vanilla kernel. But this can come close:

First, ignore all arp requests on that interface:

```<code>echo 8 > /proc/sys/net/ipv4/conf/eth0/arp_ignore
</code>```

Then, disable IPv6:

```<code>echo 1 > /proc/sys/net/ipv6/conf/eth0/disable_ipv6
</code>```

Finally, filter all IPv4 packets coming on that interface

```<code>iptables -I INPUT -i eth0 -j DROP
</code>```

And do not set an IP-address or routes on that interface. This is of course not perfect, certain packets will still be processed by the kernel, but I don't think there is a much better solution.

Title: Linux use interface for raw socket only

Body:
This is not possible to achieve with a vanilla kernel. But this can come close:

First, ignore all arp requests on that interface:

echo 8 > /proc/sys/net/ipv4/conf/eth0/arp_ignore

Then, disable IPv6:

echo 1 > /proc/sys/net/ipv6/conf/eth0/disable_ipv6

Finally, filter all IPv4 packets coming on that interface

iptables -I INPUT -i eth0 -j DROP

And do not set an IP-address or routes on that interface. This is of course not perfect, certain packets will still be processed by the kernel, but I don't think there is a much better solution.


问:
Why position of div is affected by margin-top of its child?
Here is my markup

CSS

```<code>body{
    background-color:#353535;
}
#parent{
    background-color:#eee;
}
#child{
    background-color:#1b1b1b;
    margin:60px auto 10px;
    width:100px;
}
</code>```

HTML

```<code><div id="parent">
    <div id="child">child</div>
</div>
</code>```

Result: http://jsfiddle.net/W74TZ/

答: It's part of the CSS spec. You can read up more on this by Googling "margin collapsing", e.g. http://www.howtocreate.co.uk/tutorials/css/margincollapsing</p>

Body:
Here is my markup

CSS

body{
    background-color:#353535;
}
#parent{
    background-color:#eee;
}
#child{
    background-color:#1b1b1b;
    margin:60px auto 10px;
    width:100px;
}

HTML

child

Result: http://jsfiddle.net/W74TZ/


问:
Getting text from XPath but want elements?
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

```<code><node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>
</code>```

I wish to copy the content of node 2 including the tags, which is:

```<code><node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>
</code>```

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

答:
Correct XPath query to fetch div inner text </p>

<p>Use the text() function: </p>

```<code>//node1/node2/text()
</code>```

Body:
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

<node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>

I wish to copy the content of node 2 including the tags, which is:

<node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

Body:
Correct XPath query to fetch div inner text

Use the text() function:

//node1/node2/text()


问:
Find row where values for column is maximal in a pandas DataFrame
How can I find the row for which the value of a specific column is maximal?

df.max() will give me the maximal value for each column, I don't know how to get the corresponding row.

答:
The idmax of the DataFrame returns the label index of the row with the maximum value and the behavior of argmax depends on version of pandas (right now it returns a warning). If you want to use the positional index, you can do the following:

```<code>max_row = df['A'].values.argmax()
</code>```

or

```<code>import numpy as np
max_row = np.argmax(df['A'].values)
</code>```

Note that if you use np.argmax(df['A']) behaves the same as df['A'].argmax().

Body:
The idmax of the DataFrame returns the label index of the row with the maximum value and the behavior of argmax depends on version of pandas (right now it returns a warning). If you want to use the positional index, you can do the following:

max_row = df['A'].values.argmax()

or

import numpy as np
max_row = np.argmax(df['A'].values)

Note that if you use np.argmax(df['A']) behaves the same as df['A'].argmax().


问:
When to make pointer point to a struct on the heap vs on the stack?
```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct foo {
    char* text;
    int num;
} foo;

int main(void) {

    foo* a = malloc(sizeof(foo));
    a->text = "Something";
    a->num = 4;
    printf("%s %d\n", a->text, a->num);

    foo b;
    b.text = "Something";
    b.num = 4;
    foo* c = &b;
    printf("%s %d", c->text, c->num);

    return 0;
}
</code>```

Both print the exact same thing. The only difference between foo* a and foo* c is where each one points to. Which one should be preferred? I usually see malloc() more but I don't understand why.

答: Heap-allocated data is easier to share with others (i.e. across function boundaries), especially when the function that creates an object needs to have it usable when that function has exited. This is not possible with non-heap data (except when using static but that creates problems too), which can be rather limiting.

Body:
#include <stdio.h>
#include <stdlib.h>

typedef struct foo {
    char* text;
    int num;
} foo;

int main(void) {

    foo* a = malloc(sizeof(foo));
    a->text = "Something";
    a->num = 4;
    printf("%s %d\n", a->text, a->num);

    foo b;
    b.text = "Something";
    b.num = 4;
    foo* c = &b;
    printf("%s %d", c->text, c->num);

    return 0;
}

Both print the exact same thing. The only difference between foo* a and foo* c is where each one points to. Which one should be preferred? I usually see malloc() more but I don't understand why.


问:
Updating records in a loop with Laravel giving me a 500 server error
Obviously I'm running out of memory and I realise this is the wrong way to update thousands of records, but what is the right way?

I have an assosiative array which I'm looping through to update record values:

$array = ['red' => '1', 'blue' => '1', 'green' => '3']

(obviously this array is a lot larger, around 1000 records.)

Loop through and update like this:

```<code>  foreach ($array as $key => $value) {
    Colour::where('name', '=', $key)->update(['cost' => $value]);
  }
</code>```

what's the right way to do this?

答:
Instead of querying the model, and update it - try to update it without fetching:

```<code>foreach ($array as $key => $value) {
    DB::table('colors')
        ->where('name', $key)
        ->update(['cost' => $value]);
}
</code>```

For more info, see Laravel's documentation

Body:
Obviously I'm running out of memory and I realise this is the wrong way to update thousands of records, but what is the right way?

I have an assosiative array which I'm looping through to update record values:

$array = ['red' => '1', 'blue' => '1', 'green' => '3']

(obviously this array is a lot larger, around 1000 records.)

Loop through and update like this:

  foreach ($array as $key => $value) {
    Colour::where('name', '=', $key)->update(['cost' => $value]);
  }

what's the right way to do this?

Body:
Instead of querying the model, and update it - try to update it without fetching:

foreach ($array as $key => $value) {
    DB::table('colors')
        ->where('name', $key)
        ->update(['cost' => $value]);
}

For more info, see Laravel's documentation


问:
sticky navigation jumps with css and jquery
I am trying to build sticky navigation but the problem is that when the scrollTop reaches 300px my navigation is jumping too fast and I want to scroll it smoothly and I am not sure where the problem is ( why the navigation is jumping out(bouncing) ).

https://jsfiddle.net/7mgLkk53/1/

```<code>jsfiddle
</code>```

答:
You can use css3 transition property to make it smoother on class .main-head-scrolled

Fiddle link

Body:
I am trying to build sticky navigation but the problem is that when the scrollTop reaches 300px my navigation is jumping too fast and I want to scroll it smoothly and I am not sure where the problem is ( why the navigation is jumping out(bouncing) ).

https://jsfiddle.net/7mgLkk53/1/

jsfiddle


问:
No green squiggly line under obsolete properties, no warnings during build either ... VS2017
When I will be removing/changing a property I usually mark it obsolete so VisualStudio will show a green squiggly line under the propertyname wherever it's shown in code. It also generates a warning during compilation.

I've noticed that in VS2017 this doesn't happen, does anyone know how I can get this behaviour back to how it was (and should be in my opinion) ?

thanks,
Jurjen.

答:
It would seem that when you override a property and mark it as obsolete,

```<code>[Obsolete("...")]
public override int SomeId {get;set;}
</code>```

Then no green squiggly or compiler warning, seems to have to do with the override as in the base class it's not obsolete

```<code>[Obsolete("...")]
public new int SomeId {get {return base.SomeId;} set {base.SomeId=value;} }
</code>```

using 'new' does the trick, green squiggly's and compiler warnings.

Body:
It would seem that when you override a property and mark it as obsolete,

[Obsolete("...")]
public override int SomeId {get;set;}

Then no green squiggly or compiler warning, seems to have to do with the override as in the base class it's not obsolete

[Obsolete("...")]
public new int SomeId {get {return base.SomeId;} set {base.SomeId=value;} }

using 'new' does the trick, green squiggly's and compiler warnings.


问:
Developing gems and testing
I am new to developing Ruby gems, but I thought I'd give it a try.

Recently checking out the latest episode on Railscasts (http://railscasts.com/episodes/245-new-gem-with-bundler) I'm using Bundler to create my gem.

However I'm kind of clueless on how to test my gem.

Sure I could run rake install and then require it from irb, but this seems like a kind of slow workflow for me.

What I'd like to do is create a dummy Rails app and require the gem by referencing to it's source code. Is this possible? I'm sure I've read about it somewhere…

Thanks!

答:
You can reference the gem locally, but if you don't want to run bundle update each time you change the gem, you can just require the files using their full path, or by moving (or symlinking) your gem into /vendor.

But to be honest, it sounds like you need to write some tests! ;) Manually testing each change you make is going to get tiresome and error-prone. If you're new to writing gems, have a look at the source of other popular gems and see how they're tested.

Title: Developing gems and testing


问:
Undefined behavior sanitizer suppression file: failed to parse suppressions
After compiling an application with clang 3.6 using -fsanitize=undefined,
I'm trying to start the instrumented program while using a suppression file to ignore some of the errors:

```<code>UBSAN_OPTIONS="suppressions=ubsan.supp" ./app.exe
</code>```

The suppression file ubsan.supp contains:

```<code>signed-integer-overflow:example.c
</code>```

This leads to an error message:

```<code>UndefinedBehaviorSanitizer: failed to parse suppressions
</code>```

The same occurs with a gcc 4.9 build.
The only documentation I can find is http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html, which is for clang 3.9, while I use 3.6 (which doesn't have documentation for ubsan included).

Can anyone provide working examples for ubsan suppression files, that work in clang 3.6?

Edit: By browsing the source code of ubsan, I found that the only valid suppression type might be "vptr_check" - dunno which version I was looking at though.
Can anyone confirm that in clang 3.9 more suppression types are available?

答:
I'd tried it by creating three files, compile.sh, main.cpp and suppressions.supp as shown below.  The unsigned-integer-overflow is not a part of undefined that's why it needs to be included specifically.  This works on my machine with clang-3.9.

So, I'd guess more suppression types are valid in clang-3.9.

```<code># compile.sh
set -x
UBSAN_OPTIONS=suppressions=suppressions.supp:print_stacktrace=1 #:help=1
export UBSAN_OPTIONS
clang++-3.9 -g -std=c++11 -fsanitize=undefined -fno-omit-frame-pointer -fsanitize=unsigned-integer-overflow main.cpp
./a.out

// main.cpp
#include <bits/stdc++.h>
#include <bits/stl_tree.h>
using namespace std;
int main(int argc, char **argv) {
  unsigned int k = UINT_MAX;
  k += 1;
  return 0;
}

# suppressions.supp
unsigned-integer-overflow:main.cpp
</code>```

Body:
After compiling an application with clang 3.6 using -fsanitize=undefined,
I'm trying to start the instrumented program while using a suppression file to ignore some of the errors:

UBSAN_OPTIONS="suppressions=ubsan.supp" ./app.exe

The suppression file ubsan.supp contains:

signed-integer-overflow:example.c

This leads to an error message:

UndefinedBehaviorSanitizer: failed to parse suppressions

The same occurs with a gcc 4.9 build.
The only documentation I can find is http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html, which is for clang 3.9, while I use 3.6 (which doesn't have documentation for ubsan included).

Can anyone provide working examples for ubsan suppression files, that work in clang 3.6?

Edit: By browsing the source code of ubsan, I found that the only valid suppression type might be "vptr_check" - dunno which version I was looking at though.
Can anyone confirm that in clang 3.9 more suppression types are available?

Body:
I'd tried it by creating three files, compile.sh, main.cpp and suppressions.supp as shown below.  The unsigned-integer-overflow is not a part of undefined that's why it needs to be included specifically.  This works on my machine with clang-3.9.

So, I'd guess more suppression types are valid in clang-3.9.

# compile.sh
set -x
UBSAN_OPTIONS=suppressions=suppressions.supp:print_stacktrace=1 #:help=1
export UBSAN_OPTIONS
clang++-3.9 -g -std=c++11 -fsanitize=undefined -fno-omit-frame-pointer -fsanitize=unsigned-integer-overflow main.cpp
./a.out

// main.cpp
#include <bits/stdc++.h>
#include <bits/stl_tree.h>
using namespace std;
int main(int argc, char **argv) {
  unsigned int k = UINT_MAX;
  k += 1;
  return 0;
}

# suppressions.supp
unsigned-integer-overflow:main.cpp


问:
Square layout on GridLayoutManager for RecyclerView
I try to make a grid-layout with square images. I thought that it must be possible to manipulate the GridLayoutManager by manipulating onMeasure to do a

```<code>super.onMeasure(recycler, state, widthSpec, widthSpec);
</code>```

instead of

```<code>super.onMeasure(recycler, state, widthSpec, heightSpec);
</code>```

but unfortunately, that didn't work.

Any ideas?

答:
I don't like chosen answer so let me provide mine: Instead of wrapping entire item layout in SomeDammyLayoutWithFixedAspectRatio you can hack GridLayoutManager and rewrite code inside measureChild. I've replaced these lines:

```<code>if (mOrientation == VERTICAL) {
        wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                horizontalInsets, lp.width, false);
        hSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getHeightMode(),
                verticalInsets, lp.height, true);
    } else {
        hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                verticalInsets, lp.height, false);
        wSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getWidthMode(),
                horizontalInsets, lp.width, true);
    }
</code>```

to:

```<code>if (mOrientation == VERTICAL) {
        wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                horizontalInsets, lp.width, false);
        hSpec = wSpec;
    } else {
        hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                verticalInsets, lp.height, false);
        wSpec = hSpec;
    }
</code>```

It seems to work fine.

Don't get me wrong, this is quite messy too, but at least this solution doesn't hurt app performance by extending view hierarchy

Body:
I try to make a grid-layout with square images. I thought that it must be possible to manipulate the GridLayoutManager by manipulating onMeasure to do a

super.onMeasure(recycler, state, widthSpec, widthSpec);

instead of

super.onMeasure(recycler, state, widthSpec, heightSpec);

but unfortunately, that didn't work.

Any ideas?

Body:
I don't like chosen answer so let me provide mine: Instead of wrapping entire item layout in SomeDammyLayoutWithFixedAspectRatio you can hack GridLayoutManager and rewrite code inside measureChild. I've replaced these lines:

if (mOrientation == VERTICAL) {
        wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                horizontalInsets, lp.width, false);
        hSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getHeightMode(),
                verticalInsets, lp.height, true);
    } else {
        hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                verticalInsets, lp.height, false);
        wSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getWidthMode(),
                horizontalInsets, lp.width, true);
    }

to:

if (mOrientation == VERTICAL) {
        wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                horizontalInsets, lp.width, false);
        hSpec = wSpec;
    } else {
        hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
                verticalInsets, lp.height, false);
        wSpec = hSpec;
    }

It seems to work fine.

Don't get me wrong, this is quite messy too, but at least this solution doesn't hurt app performance by extending view hierarchy


问:
In AWS Codepipeline, how do I assign a proper role name to allow a stack deployment via CloudFormation?
So, I am creating a pipeline and when I go to add a deploy stage to create a stack with CloudFormation, I get this error when I try to attach a role name:

"The role name is invalid. Check that the specified role exists and can be assumed by AWS CloudFormation."

The role exists, and I have gone into "Trust Relationship" and made CodePipeline a trusted entity. I am using the ARN as the role name. Any help would be much appreciated. Thanks!

答: In the "Trust Relationship" it is actually CloudFormation that needs to be the trusted entity, not CodePipeline.</p>


问:
Running a linux subprocess in python script
I need to show coloured diff of two text files on linux from my python script, for which I am using vimdiff. I am able to run vimdiff using subprocess but I cant get control back to python script. It stays in the vimdiff mode forever until I do Ctrl+Z.
What i want to do is that open vimdiff and get back to python script after receiving some kind of input from the keyboard. I tried signal module too but couldnt solve the problem.

I am a beginner in python so far what I tried is here:

```<code>import subprocess
p = subprocess.Popen(["vimdiff","test1.txt", "test2.txt"])
try:
 p.wait()
except KeyboardInterrupt:
 p.kill()
</code>```

Any help will be appreciated

答:
vim is a full screen text mode program that does tricks with screen. Avoid piping its input/output. Better run

```<code>subprocess.call(["vimdiff", "test1.txt", "test2.txt"])
</code>```

or simply

```<code>os.system("vimdiff test1.txt test2.txt")
</code>```

Body:
I need to show coloured diff of two text files on linux from my python script, for which I am using vimdiff. I am able to run vimdiff using subprocess but I cant get control back to python script. It stays in the vimdiff mode forever until I do Ctrl+Z.
What i want to do is that open vimdiff and get back to python script after receiving some kind of input from the keyboard. I tried signal module too but couldnt solve the problem.

I am a beginner in python so far what I tried is here:

import subprocess
p = subprocess.Popen(["vimdiff","test1.txt", "test2.txt"])
try:
 p.wait()
except KeyboardInterrupt:
 p.kill()

Any help will be appreciated

Body:
vim is a full screen text mode program that does tricks with screen. Avoid piping its input/output. Better run

subprocess.call(["vimdiff", "test1.txt", "test2.txt"])

or simply

os.system("vimdiff test1.txt test2.txt")


问:
Instagram API with Laravel 5.4
I am using an Instagram package vinkla to get the user data to my app.

Here is the code that I use in order to get the results:

```<code>public function instagram()
{
   $insta = new Instagram();

   $getUser = $insta->get('gopro');

   dd($getUser);
}
</code>```

When I diedump the results I get this array on return:

```<code>array:20 [▼
  0 => {#205 ▼
    +"id": "1552323772757218591_28902942"
    +"code": "BWK9j8rlpUf"
    +"user": {#208 ▶}
    +"images": {#202 ▼
      +"thumbnail": {#203 ▶}
      +"low_resolution": {#214 ▶}
      +"standard_resolution": {#204 ▼
        +"width": 640
        +"height": 640
        +"url": "https://scontent-frt3-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19624693_104174916895493_9107740182827761664_n.jpg"
      }
    }
    +"created_time": "1499271435"
    +"caption": {#207 ▶}
    +"likes": {#215 ▶}
    +"comments": {#222 ▶}
    +"can_view_comments": true
    +"can_delete_comments": false
    +"type": "image"
    +"link": "https://www.instagram.com/p/BWK9j8rlpUf/"
    +"location": {#223 ▶}
    +"alt_media_url": null
  }
  1 => {#224 ▶}
  2 => {#251 ▶}
  3 => {#278 ▶}

]
</code>```

Now the thing that I am trying to approach:
I want to integrate some images on my laravel app. Basically I want to get the image url from each array  images->standard_resolution->url.

I have tried to iterate the array with double foreach no luck so far.

Any suggestion on how to achieve that ?

答:
use map from laravel collection will simply get the urls

```<code>$data = collect($getUser)->map(function($v) {
    return $v->images->standard_resolution->url;
});
</code>```

And you also can use foreach

```<code>$urls = [];
foreach ($getUser as $row) {
    array_push($urls, $row->images->standard_resolution->url);
}

dd($urls);
</code>```

Title: Instagram API with Laravel 5.4

Body:
I am using an Instagram package vinkla to get the user data to my app.

Here is the code that I use in order to get the results:

public function instagram()
{
   $insta = new Instagram();

   $getUser = $insta->get('gopro');

   dd($getUser);
}

When I diedump the results I get this array on return:

array:20 [▼
  0 => {#205 ▼
    +"id": "1552323772757218591_28902942"
    +"code": "BWK9j8rlpUf"
    +"user": {#208 ▶}
    +"images": {#202 ▼
      +"thumbnail": {#203 ▶}
      +"low_resolution": {#214 ▶}
      +"standard_resolution": {#204 ▼
        +"width": 640
        +"height": 640
        +"url": "https://scontent-frt3-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19624693_104174916895493_9107740182827761664_n.jpg"
      }
    }
    +"created_time": "1499271435"
    +"caption": {#207 ▶}
    +"likes": {#215 ▶}
    +"comments": {#222 ▶}
    +"can_view_comments": true
    +"can_delete_comments": false
    +"type": "image"
    +"link": "https://www.instagram.com/p/BWK9j8rlpUf/"
    +"location": {#223 ▶}
    +"alt_media_url": null
  }
  1 => {#224 ▶}
  2 => {#251 ▶}
  3 => {#278 ▶}

]

Now the thing that I am trying to approach:
I want to integrate some images on my laravel app. Basically I want to get the image url from each array  images->standard_resolution->url.

I have tried to iterate the array with double foreach no luck so far.

Any suggestion on how to achieve that ?

Body:
use map from laravel collection will simply get the urls

$data = collect($getUser)->map(function($v) {
    return $v->images->standard_resolution->url;
});

And you also can use foreach

$urls = [];
foreach ($getUser as $row) {
    array_push($urls, $row->images->standard_resolution->url);
}

dd($urls);


问:
Encode CSV file for Sendgrid's Email API
I am attempting to build a client reporting engine using R/Python, and Sendgrid's Email API.  I can send emails, but the last thing that I need to do is attach a client's CSV report.

I have attempted a number of approaches, including base64 encoding the file and writing the string to disk from R to python, but not luck.  That said, it seems like I am getting stuck on this error:

TypeError: Object of type 'bytes' is not JSON serializable

My code to get there is:

```<code>with open('raw/test-report.csv', 'rb') as fd:
     b64data = base64.b64encode(fd.read())
attachment = Attachment()
attachment.content = b64data
attachment.filename = "your-lead-report.csv"
mail.add_attachment(attachment)
</code>```

What is confusing is that if I simply replace b64data with the line

```<code>attachment.content = 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12'
</code>```

an email is sent with an attachment.

For reference, I have been using:

https://github.com/sendgrid/sendgrid-python

and

kitchen sink tutorial

and haven't had any issues until this final step in my project.

Any help will be greatly appreciated.  It's worth noting that my strength is in R, but I usually can hack things together in python with the help of the internets.

答:
You need to convert b64data to a regular string before assigning it to attachment.content. Sendgrid builds a JSON payload which it sends in the requests so it doesn't know how to serialize the value assigned to attachment.content which in this case is a bytestring.

```<code>str(b64data,'utf-8')
</code>```

References:

https://github.com/sendgrid/sendgrid-python/blob/master/USAGE.md#post-mailsend

Body:
I am attempting to build a client reporting engine using R/Python, and Sendgrid's Email API.  I can send emails, but the last thing that I need to do is attach a client's CSV report.

I have attempted a number of approaches, including base64 encoding the file and writing the string to disk from R to python, but not luck.  That said, it seems like I am getting stuck on this error:

TypeError: Object of type 'bytes' is not JSON serializable

My code to get there is:

with open('raw/test-report.csv', 'rb') as fd:
     b64data = base64.b64encode(fd.read())
attachment = Attachment()
attachment.content = b64data
attachment.filename = "your-lead-report.csv"
mail.add_attachment(attachment)

What is confusing is that if I simply replace b64data with the line

attachment.content = 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12'

an email is sent with an attachment.

For reference, I have been using:

https://github.com/sendgrid/sendgrid-python

and

kitchen sink tutorial

and haven't had any issues until this final step in my project.

Any help will be greatly appreciated.  It's worth noting that my strength is in R, but I usually can hack things together in python with the help of the internets.

Body:
You need to convert b64data to a regular string before assigning it to attachment.content. Sendgrid builds a JSON payload which it sends in the requests so it doesn't know how to serialize the value assigned to attachment.content which in this case is a bytestring.

str(b64data,'utf-8')

References:

https://github.com/sendgrid/sendgrid-python/blob/master/USAGE.md#post-mailsend


问:
Segmentation Fault when trying to increment letters
```<code>#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <crypt.h>

int main(int argc, string argv[])
{
    if(argc > 2){ printf("too many arguments\n"); return 51; }
    if(argc < 2){ printf("too few arguments\n"); return 50; }
    if(strlen(argv[1]) > 4){ printf("Password is greater than 4 characters\n"); return 52; }

    if(argc == 2) //make sure there are enough args
    {
        string hash_guess = "A";

        while(crypt(hash_guess, "50") != argv[1]) //while answer not correct
        {
            while(hash_guess[0] <= 'Z' && hash_guess[0] >= 'A')
            {
                hash_guess[0] = hash_guess[0] + 1;
                printf("%s", hash_guess);
            }
        }

    }

}
</code>```

I am trying to increment letter by letter through a word, so it would go a then b then c until z then it will go aa, ab, ac, ad.... then ba bb bc bd... then za... zz... zzz. I'm starting with one letter, but I get error "segmentation fault"

答:
Ok the reason for the segfault, just for information, is that you are using compiler's read only memory as temporary storage.

```<code>typedef string char*;

string hash_guess = "A";
</code>```

The compiler generates a 2 entry constant memory array of 'A' and '\0'.  You cannot write to this memory.  It is Undefined Behavior.  (UB)

```<code>        while(hash_guess[0] <= 'Z' && hash_guess[0] >= 'A')
        {
            hash_guess[0] = hash_guess[0] + 1;
</code>```

...

Is illegal.  You need a temp char array to hold your guess for this to be legal.

```<code>char my_guess[5];  // You specify a max length of 4.  Make a constant soon please.
strcpy(my_guess, hash_guess);  // Real code never uses this function for safety reasons.

// Beware that later when going to multi-letter check, you will
// need to re- NUL terminate the string...

        while(my_guess[0] <= 'Z' && my_guess[0] >= 'A')
        {
            my_guess[0] = my_guess[0] + 1;
// ...
</code>```

my_guessis on the stack and safely usable.

Body:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <crypt.h>

int main(int argc, string argv[])
{
    if(argc > 2){ printf("too many arguments\n"); return 51; }
    if(argc < 2){ printf("too few arguments\n"); return 50; }
    if(strlen(argv[1]) > 4){ printf("Password is greater than 4 characters\n"); return 52; }

    if(argc == 2) //make sure there are enough args
    {
        string hash_guess = "A";

        while(crypt(hash_guess, "50") != argv[1]) //while answer not correct
        {
            while(hash_guess[0] <= 'Z' && hash_guess[0] >= 'A')
            {
                hash_guess[0] = hash_guess[0] + 1;
                printf("%s", hash_guess);
            }
        }

    }

}

I am trying to increment letter by letter through a word, so it would go a then b then c until z then it will go aa, ab, ac, ad.... then ba bb bc bd... then za... zz... zzz. I'm starting with one letter, but I get error "segmentation fault"

Body:
Ok the reason for the segfault, just for information, is that you are using compiler's read only memory as temporary storage.

typedef string char*;

string hash_guess = "A";

The compiler generates a 2 entry constant memory array of 'A' and '\0'.  You cannot write to this memory.  It is Undefined Behavior.  (UB)

        while(hash_guess[0] <= 'Z' && hash_guess[0] >= 'A')
        {
            hash_guess[0] = hash_guess[0] + 1;

...

Is illegal.  You need a temp char array to hold your guess for this to be legal.

char my_guess[5];  // You specify a max length of 4.  Make a constant soon please.
strcpy(my_guess, hash_guess);  // Real code never uses this function for safety reasons.

// Beware that later when going to multi-letter check, you will
// need to re- NUL terminate the string...

        while(my_guess[0] <= 'Z' && my_guess[0] >= 'A')
        {
            my_guess[0] = my_guess[0] + 1;
// ...

my_guessis on the stack and safely usable.


问:
Real-Time Database Updating
I have ~300 Identical Excel Spreadsheets (.xlsx) that all have ten different cells I would like to project to an Access database. Some are single cells, a few ranges-- all of them are named in each individual workbook. The database should hold all values from the same worksheet on the same line, and all numbers should update in real time.

My goal is to use access to keep a running record on the contents of these cells. I have attempted to link the workbooks to the Master Access database using: External Data->Import and Link->Excel->Link to the data source by creating a linked table-> and here I would select one of the named ranges and click 'Finish', but I can only do this once per spreadsheet. This makes repeating this process for all spreadsheets unfeasible.

Is there a way to use Access VBA to create a linked Excel Table for each Workbook in the folder?

I am sort of teaching myself Access, and am still relatively new at it so any insight will help.

Cheers.

答:
Luckily, I had just that lying around somewhere. This links all excel files in the same folder as the database.

Note that this just uses the file name as the tablename, and links everything using default settings. Change the DoCmd.TransferSpreadsheet line to customize it. Originally I have this linked to a form so I can choose what to import, and how it is handled.

```<code>Public Sub ImportExcel()
    Dim objFSO As Object 'FileSystemObject
    Dim databasefolderlocation As String
    Dim objFolder As Object 'Folder
    Dim objFile As Variant
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    databasefolderlocation = Application.CurrentProject.Path 'This sets the folder, you can change it for another folder
    Set objFolder = objFSO.GetFolder(databasefolderlocation)
    For Each objFile In objFolder.Files
        If objFile.Name Like "*.xls" Or objFile.Name Like "*.xlsx" Then
            DoCmd.TransferSpreadsheet acLink, , objFile.Name, objFile.Path
        End If
    Next objFile
End Sub
</code>```

Title: Real-Time Database Updating

Body:
Luckily, I had just that lying around somewhere. This links all excel files in the same folder as the database.

Note that this just uses the file name as the tablename, and links everything using default settings. Change the DoCmd.TransferSpreadsheet line to customize it. Originally I have this linked to a form so I can choose what to import, and how it is handled.

Public Sub ImportExcel()
    Dim objFSO As Object 'FileSystemObject
    Dim databasefolderlocation As String
    Dim objFolder As Object 'Folder
    Dim objFile As Variant
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    databasefolderlocation = Application.CurrentProject.Path 'This sets the folder, you can change it for another folder
    Set objFolder = objFSO.GetFolder(databasefolderlocation)
    For Each objFile In objFolder.Files
        If objFile.Name Like "*.xls" Or objFile.Name Like "*.xlsx" Then
            DoCmd.TransferSpreadsheet acLink, , objFile.Name, objFile.Path
        End If
    Next objFile
End Sub


问:
bulma: horizontal form controls not expanded correctly
I have one text input and 2 selects that I want to put them horizontally. based on bulma css framework, that what I'm supposed to do:

```<code><div class="field is-horizontal">
  <div class="field-body">
     <div class="field">
        <p class="control is-expanded has-icons-left">
           <input class="input" type="text" placeholder="Search" name="id" id="id">
           <span class="icon is-small is-left"><i class="fa fa-search"></i></span>
        </p>
     </div>
     <div class="field">
        <p class="control">
           <span class="select">
              <select name="status" id="status">
                 <option value="">Status:</option>
                 <option value="active">active</option>
                 <option value="pause">pause</option>
              </select>
           </span>
        </p>
     </div>
     <div class="field">
        <p class="control">
           <span class="select">
              <select name="limit" id="limit">
                 <option value="">Limits:</option>
                 <option value="10">10</option>
                 <option value="20">20</option>
              </select>
           </span>
        </p>
     </div>
  </div>
</code>```

normally the last 2 selects should take their real width and the first input should expand until it takes the available space, but this is what i'm getting:

答:
Add is-narrow to the fields you want to be narrow:

```<code><div class="field is-narrow">
</code>```

Working example: https://jsfiddle.net/wostex/ut4nedq2/

Body:
I have one text input and 2 selects that I want to put them horizontally. based on bulma css framework, that what I'm supposed to do:

           <input class="input" type="text" placeholder="Search" name="id" id="id">

              <select name="status" id="status">
                 <option value="">Status:</option>
                 <option value="active">active</option>
                 <option value="pause">pause</option>
              </select>

              <select name="limit" id="limit">
                 <option value="">Limits:</option>
                 <option value="10">10</option>
                 <option value="20">20</option>
              </select>

normally the last 2 selects should take their real width and the first input should expand until it takes the available space, but this is what i'm getting:

Body:
Add is-narrow to the fields you want to be narrow:

<div class="field is-narrow">

Working example: https://jsfiddle.net/wostex/ut4nedq2/


问:
ADFS Sign-In Pages Customization
I am working on  a iOS application.

The login page which is showing from ADFS on a UIWebview is not looking good, so I want to customise it.

Is this possible from the client side?

I have tried to get user inputs in a custom login field and autofill the web view form and submit so that user can't see the ugly login screen which is coming from ADFS itself, but I am not getting the desired result. I am totally stuck.

答:
The ADFS login-page is served out of ADFS.

You cannot customise it client side.

To customise on the server side, refer ADFS : Continuing the Login and Home Realm Discovery (HRD) and Change Password customisation adventure .

Title: ADFS Sign-In Pages Customization


问:
Stylecop tells me to add this keyword, but it's redundant - any performance implications?
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?

Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.

Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.

Thanks

答:
In C# this is a reference to the current instance of the class (it's me in VB.NET). It's used generally to fully qualify a class member. For example, consider this C# class:

```<code>public class MyClass
{
    int rate;

    private void testMethod()
    {
        int x;

        x = this.rate;
    }
}
</code>```

this isn't required in the code above, but adds instant clarity when reading the code that rate belongs to the class rather than the method (search SO, you'll find lots of opinions about the use of this). It's semantic behavior is the same in VB--and its use doesn't impose a performance penalty.

OwnerDisplayName: GSS

Body:
In C# this is a reference to the current instance of the class (it's me in VB.NET). It's used generally to fully qualify a class member. For example, consider this C# class:

public class MyClass
{
    int rate;

    private void testMethod()
    {
        int x;

        x = this.rate;
    }
}

this isn't required in the code above, but adds instant clarity when reading the code that rate belongs to the class rather than the method (search SO, you'll find lots of opinions about the use of this). It's semantic behavior is the same in VB--and its use doesn't impose a performance penalty.

OwnerDisplayName: rp


问:
IEnumerable parser class design
I'm creating a class that can read from a dicom file. This is basically a binary file filled with a lot of objects. I want to create a solid class that can do this. So I've designed the following.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Medicom
{
    public class DDocument : IEnumerable<DDataElement>
    {
        /// <summary>
        /// Creates a new DDocument from a file.
        /// </summary>
        /// <param name="path">The path of the file to load </param>
        /// <returns>An DDocument that contains the Dicom information from the file</returns>
        public static DDocument Load(string path)
        {
            return DDocument.Load(new FileStream(path, FileMode.Open));
        }

        /// <summary>
        /// Creates a new XDocument instance by using the specified stream.
        /// </summary>
        /// <param name="stream">The stream that contains the Dicom information.</param>
        /// <returns>An DDocument that contains the Dicom information from the stream.</returns>
        public static DDocument Load(Stream stream)
        {
            //Logic here to read the whole stream and List<DDataElement> Data with all the data
        }

        /// <summary>
        /// Gets or sets a list with MetaInformation containing DDataElements
        /// </summary>
        public List<DDataElement> Data
        {
            get;
            set;
        }

        /// <summary>
        /// Returns an enumerator that can be used to iterate through the DDocument
        /// </summary>
        /// <returns>An IEnumerator that can be used to iterate through the DDocument</returns>
        public IEnumerator<DDataElement> GetEnumerator()
        {
            foreach (DDataElement dataElement in Data)
            {
                yield return dataElement;
            }
        }
    }
}
</code>```

I wanted to know what you think of it. Are there any changes you would make in this class?

答:
Two things:

First, you should close the FileStream when you're done with it:

```<code>public static DDocument Load(string path)
{
    using(FileStream fs = new FileStream(path, FileMode.Open)) {
        return DDocument.Load(fs);
    }
}
</code>```

Second, the List already has a perfectly good IEnumerable! You should use it!

```<code>public IEnumerator<DDataElement> GetEnumerator()
{
    return (IEnumerator<DDataElement>)Data.GetEnumerator();
}
</code>```

Title: IEnumerable parser class design

Body:
I'm creating a class that can read from a dicom file. This is basically a binary file filled with a lot of objects. I want to create a solid class that can do this. So I've designed the following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Medicom
{
    public class DDocument : IEnumerable<DDataElement>
    {
        ///
        /// Creates a new DDocument from a file.
        ///
        /// <param name="path">The path of the file to load </param>
        /// <returns>An DDocument that contains the Dicom information from the file</returns>
        public static DDocument Load(string path)
        {
            return DDocument.Load(new FileStream(path, FileMode.Open));
        }

        ///
        /// Creates a new XDocument instance by using the specified stream.
        ///
        /// <param name="stream">The stream that contains the Dicom information.</param>
        /// <returns>An DDocument that contains the Dicom information from the stream.</returns>
        public static DDocument Load(Stream stream)
        {
            //Logic here to read the whole stream and List<DDataElement> Data with all the data
        }

        ///
        /// Gets or sets a list with MetaInformation containing DDataElements
        ///
        public List<DDataElement> Data
        {
            get;
            set;
        }

        ///
        /// Returns an enumerator that can be used to iterate through the DDocument
        ///
        /// <returns>An IEnumerator that can be used to iterate through the DDocument</returns>
        public IEnumerator<DDataElement> GetEnumerator()
        {
            foreach (DDataElement dataElement in Data)
            {
                yield return dataElement;
            }
        }
    }
}

I wanted to know what you think of it. Are there any changes you would make in this class?

Body:
Two things:

First, you should close the FileStream when you're done with it:

public static DDocument Load(string path)
{
    using(FileStream fs = new FileStream(path, FileMode.Open)) {
        return DDocument.Load(fs);
    }
}

Second, the List already has a perfectly good IEnumerable! You should use it!

public IEnumerator<DDataElement> GetEnumerator()
{
    return (IEnumerator<DDataElement>)Data.GetEnumerator();
}


问:
How to debug prepare statement with PHP?
I am trying to insert value in my database using below code.But it does not enter value.I want to debug & print any error message i tried $stmt->error or $stmt->errorInfo() but nothing worked for me.

```<code>$stmt = $this->conn->prepare("INSERT INTO users(name) values(?)");
$stmt->bind_param("s", "dhieaj");

$result = $stmt->execute();
echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
    // User successfully inserted
    return USER_CREATED_SUCCESSFULLY;
}
</code>```

答:
I tried to run the same code on my Local AppEngine Server and these where my findings:

Original Code:

```<code>$stmt = $this->conn->prepare("INSERT INTO users(name) values(?)");
$stmt->bind_param("s", "dhieaj");

$result = $stmt->execute();
echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
// User successfully inserted
    return USER_CREATED_SUCCESSFULLY;
}
</code>```

Experiments:

```<code>$stmt->bind_param("s", "dhieaj");
// failed with error ( <b>Fatal error</b>:  Cannot pass parameter 2 by reference in <b>C:\...)
</code>```

so I modified the line to:

```<code>$param="dhieaj";
$stmt->bind_param("s", $param);
</code>```

Next error I got was for:
    echo $stmt->errorInfo();  //(Call to undefined method mysqli_stmt::errorInfo())
so I commented the line out.

Then I modified your return statement to echo since mine is just a fragment as posted by you.

I also noticed your conn lacked the '$' declaration key. ($conn).

Final Code:

```<code>$stmt = $conn->prepare("INSERT INTO users(firstname) values(?)");
$p="dhieaj";
$stmt->bind_param("s", $p);

$result = $stmt->execute();
// echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
    // User successfully inserted
    echo "USER_CREATED_SUCCESSFULLY";
}
</code>```

Body:
I am trying to insert value in my database using below code.But it does not enter value.I want to debug & print any error message i tried $stmt->error or $stmt->errorInfo() but nothing worked for me.

$stmt = $this->conn->prepare("INSERT INTO users(name) values(?)");
$stmt->bind_param("s", "dhieaj");

$result = $stmt->execute();
echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
    // User successfully inserted
    return USER_CREATED_SUCCESSFULLY;
}

Body:
I tried to run the same code on my Local AppEngine Server and these where my findings:

Original Code:

$stmt = $this->conn->prepare("INSERT INTO users(name) values(?)");
$stmt->bind_param("s", "dhieaj");

$result = $stmt->execute();
echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
// User successfully inserted
    return USER_CREATED_SUCCESSFULLY;
}

Experiments:

$stmt->bind_param("s", "dhieaj");
// failed with error ( <b>Fatal error</b>:  Cannot pass parameter 2 by reference in <b>C:\...)

so I modified the line to:

$param="dhieaj";
$stmt->bind_param("s", $param);

Next error I got was for:
    echo $stmt->errorInfo();  //(Call to undefined method mysqli_stmt::errorInfo())
so I commented the line out.

Then I modified your return statement to echo since mine is just a fragment as posted by you.

I also noticed your conn lacked the '$' declaration key. ($conn).

Final Code:

$stmt = $conn->prepare("INSERT INTO users(firstname) values(?)");
$p="dhieaj";
$stmt->bind_param("s", $p);

$result = $stmt->execute();
// echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
    // User successfully inserted
    echo "USER_CREATED_SUCCESSFULLY";
}


问:
Android : NDK vs CMAKE optimizations
I recently switched my Android/Application mk file to a CMakeLists.txt file.

A good portion of the code is native in c/c++ (hence why cmake's debugging ability is required).

Now though, I am comparing the two builds, and the one built with ndk is much faster ...

I have added in the "-Os" flag to the

```<code>externalNativeBuild {
    cmake {
        arguments "-Os"
    }
}
</code>```

block inside the build.gradle file.

My question is what is the differences of compilation here ?? What about ndk-build and cmake is different that would cause this ??

I feel as if this is a dumb question with a quick answer

答:
Answering my own question here :

Since we're using cmake and not ndk-build ... Build Variant actually matters for compiling native code. Building with Release fixes the performance issue.

Note : -O2 flag is included by the android.toolchain.cmake file

Title: Android : NDK vs CMAKE optimizations

Body:
I recently switched my Android/Application mk file to a CMakeLists.txt file.

A good portion of the code is native in c/c++ (hence why cmake's debugging ability is required).

Now though, I am comparing the two builds, and the one built with ndk is much faster ...

I have added in the "-Os" flag to the

externalNativeBuild {
    cmake {
        arguments "-Os"
    }
}

block inside the build.gradle file.

My question is what is the differences of compilation here ?? What about ndk-build and cmake is different that would cause this ??

I feel as if this is a dumb question with a quick answer