问:
ImageView rounded corners
I wanted image to have rounded corners. I implement this xml code and use this in my image view. but image overlap the shape. I am downloading the image through async task.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle" >
 <corners android:radius="20dip" />
</shape>

<ImageView
    android:id="@+id/trVouchersImage"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="8dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/ash_arrow"
 />
</code>```

答:
I use extend ImageView:</p>

```<code>public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

    public RadiusCornerImageView(Context context) {
        super(context);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);
         } else {
            throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
        }
        clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}
</code>```

Title: ImageView rounded corners

Body:
I wanted image to have rounded corners. I implement this xml code and use this in my image view. but image overlap the shape. I am downloading the image through async task.

<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle" >
 <corners android:radius="20dip" />
</shape>

<ImageView
    android:id="@+id/trVouchersImage"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="8dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/ash_arrow"
 />

Body:
I use extend ImageView:

public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
    private int cornerRadiusDP = 0; // dp
    private int corner_radius_position;

    public RadiusCornerImageView(Context context) {
        super(context);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
        try {
            cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
            corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
        } finally {
            typeArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
        Path clipPath = new Path();
        RectF rect = null;
        if (corner_radius_position == 0) { // all
            // round corners on all 4 angles
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        } else if (corner_radius_position == 1) {
            // round corners only on top left and top right
            rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);
         } else {
            throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
        }
        clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
        canvas.clipPath(clipPath);
        super.onDraw(canvas);
    }
}


来源: stackexchange

问:
Calculating the average difference in purchase dates by customer id
Was wondering how I would use R to calculate the below.

Assuming a CSV with the following purchase data:

```<code>| Customer ID  | Purchase Date |
| 1            | 01/01/2017    |
| 2            | 01/01/2017    |
| 3            | 01/01/2017    |
| 4            | 01/01/2017    |
| 1            | 02/01/2017    |
| 2            | 03/01/2017    |
| 2            | 07/01/2017    |
</code>```

I want to figure out the average time between repurchases by customer.

The math would  be like the one below:

```<code>| Customer ID  | AVG repurchase |
| 1            | 30 days        | = (02/01 - 01/01 / 1 order
| 2            | 90 days        | = ( (03/01 - 01/01) + (07 - 3/1) ) /2 orders
| 3            | n/a            |
| 4            | n/a            |
</code>```

The output would be the total average across customers -- so: 60 days = (30 avg for customer1 + 90 avg for customer2) / 2 customers.

答:
I've assumed you have read your CSV into a dataframe named df and I've renamed your variables using snake case, since having variables with a space in the name can be inconvenient, leading many to use either snake case or camel case variable naming conventions.

Here is a base R solution:

```<code>mean(sapply(by(df$purchase_date, df$customer_id, diff), mean), na.rm=TRUE)

[1] 60.75
</code>```

You may notice that we get 60.75 rather than 60 as you expected. This is because there are 31 days between customer 1's purchases (31 days in January until February 1), and similarly for customer 2's purchases -- there are not always 30 days in a month.

Explanation

```<code>by(df$purchase_date, df$customer_id, diff)
</code>```

The by() function applies another function to data by groupings. Here, we are applying diff() to df$purchase_date by the unique values of df$customer_id. By itself, this would result in the following output:

```<code>df$customer_id: 1
Time difference of 31 days
-----------------------------------------------------------
df$customer_id: 2
Time differences in days
[1]  59 122
</code>```

We then use

```<code>sapply(by(df$purchase_date, df$customer_id, diff), mean)
</code>```

to apply mean() to the elements of the previous result. This gives us each customer's average time to repurchase:

```<code>   1    2    3    4
31.0 90.5  NaN  NaN
</code>```

(we see customers 3 and 4 never repurchased). Finally, we need to average these average repurchase times, which means we need to also deal with those NaN values, so we use:

```<code>mean(sapply(by(df$purchase_date, df$customer_id, diff), mean), na.rm=TRUE)
</code>```

which will average the previous results, ignoring missing values (which, in R include NaN values).

ContentLicense: CC BY-SA 3.0

Body:
Was wondering how I would use R to calculate the below.

Assuming a CSV with the following purchase data:

| Customer ID  | Purchase Date |
| 1            | 01/01/2017    |
| 2            | 01/01/2017    |
| 3            | 01/01/2017    |
| 4            | 01/01/2017    |
| 1            | 02/01/2017    |
| 2            | 03/01/2017    |
| 2            | 07/01/2017    |

I want to figure out the average time between repurchases by customer.

The math would  be like the one below:

| Customer ID  | AVG repurchase |
| 1            | 30 days        | = (02/01 - 01/01 / 1 order
| 2            | 90 days        | = ( (03/01 - 01/01) + (07 - 3/1) ) /2 orders
| 3            | n/a            |
| 4            | n/a            |

The output would be the total average across customers -- so: 60 days = (30 avg for customer1 + 90 avg for customer2) / 2 customers.

Body:
I've assumed you have read your CSV into a dataframe named df and I've renamed your variables using snake case, since having variables with a space in the name can be inconvenient, leading many to use either snake case or camel case variable naming conventions.

Here is a base R solution:

mean(sapply(by(df$purchase_date, df$customer_id, diff), mean), na.rm=TRUE)

[1] 60.75

You may notice that we get 60.75 rather than 60 as you expected. This is because there are 31 days between customer 1's purchases (31 days in January until February 1), and similarly for customer 2's purchases -- there are not always 30 days in a month.

Explanation

by(df$purchase_date, df$customer_id, diff)

The by() function applies another function to data by groupings. Here, we are applying diff() to df$purchase_date by the unique values of df$customer_id. By itself, this would result in the following output:

df$customer_id: 1
Time difference of 31 days
-----------------------------------------------------------
df$customer_id: 2
Time differences in days
[1]  59 122

We then use

sapply(by(df$purchase_date, df$customer_id, diff), mean)

to apply mean() to the elements of the previous result. This gives us each customer's average time to repurchase:

   1    2    3    4
31.0 90.5  NaN  NaN

(we see customers 3 and 4 never repurchased). Finally, we need to average these average repurchase times, which means we need to also deal with those NaN values, so we use:

mean(sapply(by(df$purchase_date, df$customer_id, diff), mean), na.rm=TRUE)

which will average the previous results, ignoring missing values (which, in R include NaN values).


问:
How to implement master detail view of firebase list with AngularDart
I want to implement detail master view with the click function on list item of firebase database, When I am defining the detail view component in notes_component with the following code it binds the data and populates, but with the separate detail view component the code doesn't work and while debugging it gives the result

```<code><div *ngIf="selectedNote != null">
    <h2>{{selectedNote.title}}</h2>
    <h4>{{selectedNote.subject}}</h4>
    <p>{{selectedNote.text}}</p>
</div>
</code>```

result image

https://webdev.dartlang.org/angular/tutorial/toh-pt2

notes_component.html

```<code><div id="notes" class="mdl-grid">
    <div *ngFor="let note of notes"
         class="mdl-card mdl-cell mdl-cell--4-col section--center mdl-shadow--2dp"
         (click)="onSelect(note)"
         [class.selected]="note === selectedNote">
        <div class="mdl-card__supporting-text note-text">
            <img *ngIf="note.imageUrl != null" [src]="note.imageUrl">
            <h4 class="note-subject">{{note.subject}}</h4>
            <p class="note-title" *ngIf="note.title?.isNotEmpty">{{note.title}}</p>
        </div>

        <div *ngIf="service.user != null" style="visibility: hidden" class="mdl-card__actions note-actions">
            <a (click)="service.removeItem(note.key)" title="Remove note" class="note-remove">
                <i class="material-icons">delete</i>
            </a>
        </div>
    </div>
</div>
<note-detail [note]="selectedNote"></note-detail>
</code>```

notes_component.dart

```<code>import 'package:angular/angular.dart';

import '../../firebase_service.dart';
import '../../model/note.dart';

@Component(
    selector: 'notes',
    templateUrl: 'notes_component.html',
    directives: const [CORE_DIRECTIVES, NgIf, NgFor,])
class NotesComponent implements OnInit {
  final FirebaseService service;
  List<Note> notes = [];
  Note selectedNote;

  NotesComponent(this.service);

  void onSelect(Note note) => selectedNote = note;
  @override
  ngOnInit() {
    notes = service.notes;
  }
}
</code>```

note.dart
library tr_app.item;

```<code>const String jsonTagText = "text";
const String jsonTagSubject = "subject";
const String jsonTagTitle = "title";
const String jsonTagImgUrl = "img_url";

class Note {
  int id;
  String key;
  String text;
  String title;
  String subject;
  String imageUrl;

  Note([this.text, this.title, this.subject, this.imageUrl, this.key]);

  static Map toMap(Note item) {
    Map jsonMap = {
      jsonTagText: item.text,
      jsonTagSubject: item.subject,
      jsonTagTitle: item.title,
      jsonTagImgUrl: item.imageUrl
    };
    return jsonMap;
  }
}
</code>```

firebase_service.dart

```<code>import 'dart:html';
import 'package:angular/angular.dart';
import 'package:firebase/firebase.dart' as fb;

import '../src/model/note.dart';

@Injectable()
class FirebaseService {
  final fb.Auth auth;
  final fb.DatabaseReference databaseRef;
  final fb.StorageReference storageRef;
  final List<Note> notes = [];
  fb.User user;
  bool loading = true;

  FirebaseService()
      : auth = fb.auth(),
        databaseRef = fb.database().ref("notes"),
        storageRef = fb.storage().ref("notes");

  init() {
    databaseRef.onChildAdded.listen((e) {
      // Snapshot of the data.
      fb.DataSnapshot data = e.snapshot;

      // Value of data from snapshot.
      var val = data.val();
      // Creates a new Note item. It is possible to retrieve a key from data.
      var item = new Note(
          val[jsonTagText], val[jsonTagTitle], val[jsonTagImgUrl], data.key);
      notes.insert(0, item);
    });

    // Setups listening on the child_removed event on the database ref.
    databaseRef.onChildRemoved.listen((e) {
      fb.DataSnapshot data = e.snapshot;
      var val = data.val();

      // Removes also the image from storage.
      var imageUrl = val[jsonTagImgUrl];
      if (imageUrl != null) {
        removeItemImage(imageUrl);
      }
      notes.removeWhere((n) => n.key == data.key);
    });

    // Sets loading to true when path changes
    databaseRef.onValue.listen((e) {
      loading = false;
    });

    // Sets user when auth state changes
    auth.onIdTokenChanged.listen((e) {
      user = e;
    });
  }

  // Pushes a new item as a Map to database.
  postItem(Note item) async {
    try {
      await databaseRef.push(Note.toMap(item)).future;
    } catch (e) {
      print("Error in writing to database: $e");
    }
  }

  // Removes item with a key from database.
  removeItem(String key) async {
    try {
      await databaseRef.child(key).remove();
    } catch (e) {
      print("Error in deleting $key: $e");
    }
  }

  // Puts image into a storage.
  postItemImage(File file) async {
    try {
      var task = storageRef.child(file.name).put(file);
      task.onStateChanged
          .listen((_) => loading = true, onDone: () => loading = false);

      var snapshot = await task.future;
      return snapshot.downloadURL;
    } catch (e) {
      print("Error in uploading to storage: $e");
    }
  }

  // Removes image with an imageUrl from the storage.
  removeItemImage(String imageUrl) async {
    try {
      var imageRef = fb.storage().refFromURL(imageUrl);
      await imageRef.delete();
    } catch (e) {
      print("Error in deleting $imageUrl: $e");
    }
  }

  // Signs in with the Google auth provider.
  signInWithGoogle() async {
    var provider = new fb.GoogleAuthProvider();
    try {
      await auth.signInWithPopup(provider);
    } catch (e) {
      print("Error in sign in with Google: $e");
    }
  }

  signOut() async {
    await auth.signOut();
  }
}
</code>```

note_detail_component.html

```<code><div *ngIf="note != null">
    <h2>{{note.title}}</h2>
    <h4>{{note.subject}}</h4>
    <img *ngIf="note.imageUrl != null" [src]="note.imageUrl">
    <p>{{note.text}}</p>
</div>
</code>```

note_detail_component.dart

```<code>import 'package:angular/angular.dart';
import 'package:tr_app/src/firebase_service.dart';
import 'package:tr_app/src/model/note.dart';

@Component(
    selector: 'note-detail',
    templateUrl: 'note_detail_component.html',
    styleUrls: const ['note_detail_component.css'],
    directives: const [
      CORE_DIRECTIVES,
      NgIf,
      NgFor,
    ])
class NoteDetailComponent {

  final FirebaseService service;
  Note note;

  NoteDetailComponent(this.service);

}
</code>```

答: You need to write "ngIf", not "ngif", in the template.</p>

Body:
I want to implement detail master view with the click function on list item of firebase database, When I am defining the detail view component in notes_component with the following code it binds the data and populates, but with the separate detail view component the code doesn't work and while debugging it gives the result

{{selectedNote.title}}

{{selectedNote.subject}}

{{selectedNote.text}}

result image

https://webdev.dartlang.org/angular/tutorial/toh-pt2

notes_component.html

{{note.subject}}

{{note.title}}

                delete

<note-detail [note]="selectedNote"></note-detail>

notes_component.dart

import 'package:angular/angular.dart';

import '../../firebase_service.dart';
import '../../model/note.dart';

@Component(
    selector: 'notes',
    templateUrl: 'notes_component.html',
    directives: const [CORE_DIRECTIVES, NgIf, NgFor,])
class NotesComponent implements OnInit {
  final FirebaseService service;
  List<Note> notes = [];
  Note selectedNote;

  NotesComponent(this.service);

  void onSelect(Note note) => selectedNote = note;
  @override
  ngOnInit() {
    notes = service.notes;
  }
}

note.dart
library tr_app.item;

const String jsonTagText = "text";
const String jsonTagSubject = "subject";
const String jsonTagTitle = "title";
const String jsonTagImgUrl = "img_url";

class Note {
  int id;
  String key;
  String text;
  String title;
  String subject;
  String imageUrl;

  Note([this.text, this.title, this.subject, this.imageUrl, this.key]);

  static Map toMap(Note item) {
    Map jsonMap = {
      jsonTagText: item.text,
      jsonTagSubject: item.subject,
      jsonTagTitle: item.title,
      jsonTagImgUrl: item.imageUrl
    };
    return jsonMap;
  }
}

firebase_service.dart

import 'dart:html';
import 'package:angular/angular.dart';
import 'package:firebase/firebase.dart' as fb;

import '../src/model/note.dart';

@Injectable()
class FirebaseService {
  final fb.Auth auth;
  final fb.DatabaseReference databaseRef;
  final fb.StorageReference storageRef;
  final List<Note> notes = [];
  fb.User user;
  bool loading = true;

  FirebaseService()
      : auth = fb.auth(),
        databaseRef = fb.database().ref("notes"),
        storageRef = fb.storage().ref("notes");

  init() {
    databaseRef.onChildAdded.listen((e) {
      // Snapshot of the data.
      fb.DataSnapshot data = e.snapshot;

      // Value of data from snapshot.
      var val = data.val();
      // Creates a new Note item. It is possible to retrieve a key from data.
      var item = new Note(
          val[jsonTagText], val[jsonTagTitle], val[jsonTagImgUrl], data.key);
      notes.insert(0, item);
    });

    // Setups listening on the child_removed event on the database ref.
    databaseRef.onChildRemoved.listen((e) {
      fb.DataSnapshot data = e.snapshot;
      var val = data.val();

      // Removes also the image from storage.
      var imageUrl = val[jsonTagImgUrl];
      if (imageUrl != null) {
        removeItemImage(imageUrl);
      }
      notes.removeWhere((n) => n.key == data.key);
    });

    // Sets loading to true when path changes
    databaseRef.onValue.listen((e) {
      loading = false;
    });

    // Sets user when auth state changes
    auth.onIdTokenChanged.listen((e) {
      user = e;
    });
  }

  // Pushes a new item as a Map to database.
  postItem(Note item) async {
    try {
      await databaseRef.push(Note.toMap(item)).future;
    } catch (e) {
      print("Error in writing to database: $e");
    }
  }

  // Removes item with a key from database.
  removeItem(String key) async {
    try {
      await databaseRef.child(key).remove();
    } catch (e) {
      print("Error in deleting $key: $e");
    }
  }

  // Puts image into a storage.
  postItemImage(File file) async {
    try {
      var task = storageRef.child(file.name).put(file);
      task.onStateChanged
          .listen((_) => loading = true, onDone: () => loading = false);

      var snapshot = await task.future;
      return snapshot.downloadURL;
    } catch (e) {
      print("Error in uploading to storage: $e");
    }
  }

  // Removes image with an imageUrl from the storage.
  removeItemImage(String imageUrl) async {
    try {
      var imageRef = fb.storage().refFromURL(imageUrl);
      await imageRef.delete();
    } catch (e) {
      print("Error in deleting $imageUrl: $e");
    }
  }

  // Signs in with the Google auth provider.
  signInWithGoogle() async {
    var provider = new fb.GoogleAuthProvider();
    try {
      await auth.signInWithPopup(provider);
    } catch (e) {
      print("Error in sign in with Google: $e");
    }
  }

  signOut() async {
    await auth.signOut();
  }
}

note_detail_component.html

{{note.title}}

{{note.subject}}

{{note.text}}

note_detail_component.dart

import 'package:angular/angular.dart';
import 'package:tr_app/src/firebase_service.dart';
import 'package:tr_app/src/model/note.dart';

@Component(
    selector: 'note-detail',
    templateUrl: 'note_detail_component.html',
    styleUrls: const ['note_detail_component.css'],
    directives: const [
      CORE_DIRECTIVES,
      NgIf,
      NgFor,
    ])
class NoteDetailComponent {

  final FirebaseService service;
  Note note;

  NoteDetailComponent(this.service);

}


问:
how to track from where visitor come to my site php
I want to track the site URL from where user reached my site.

From where he came i.el, Google, GMail, Facebook, etc.

I tried $_SERVER['HTTP_REFERER'] but it does not contain anything when user click on my site link from any external site but resides the value when I visit among my site pages and this is also not trusted.

So, What I can do from here?

Is there any other way to track the external URL through PHP?

Any idea?

EDIT: Now HTTP_REFERER is able to get the url from most of sites but not able to get the url if user came through Gmail and AOL. What could be the causes?

答:
Visitors coming from google can be tracked using google analytics, it gives you the search query terms used before.

This solution also track a lot of other things from your visitors. I undertand it's not PHP based, but it's the only other kind of solution I know if HTTP_REFERRER is not enough to you, and as you quoted google...

ContentLicense: CC BY-SA 2.5


问:
Wordpress questionnaire and open ended answer
I'm looking for a wordpress plugin that simply lets me ask the user a question and have a text box that lets them enter an answer as they please. I've looked at many questionnaire plugins but they all seem to have just the option to answer the question from a selection of sample answers. i.e checkboxes with answer a, b or c etc.</p>

答:
You can use any form builder plugin. Not only questionnaire plugins. Unless there is a reason that you cannot and we cannot understand without more content on your question.

Ninja forms

Gravity Forms

Formidable Forms

Are only some of them. Create a new Form. Add a paragraph element for your Question and a textarea for the answer.

Then you can use a shortcode to load it on the page and check the answers on the submitted entries on the backend.


问:
Send ajax GET request to ASP .NET Web API
I use the following ajax script.

```<code>$.ajax({
            dataType: 'json',
            url: url,
            data:  tuDispId,
            type: "GET",
            success: function (data) {
                bindData(data);
                $("#alert-placeholder").empty();
                $('#alert-placeholder').removeClass('alert alert-danger');
            },
            error: function (xhr, textStatus, errorThrown) {
                $('#alert-placeholder').addClass('alert alert-danger');
                $('#alert-placeholder').html(errorThrown);
            }
        });
</code>```

The attribute Route in Web API before method.

```<code>[Route("api/tudisp/Edit/{tuDispId}")]
        public IHttpActionResult Edit(int tuDispId)
{
}
</code>```

The genarated request from ajax.

```<code>http://localhost:xxxxx/api/tudisp/Edit/?179
</code>```

How to force ajax to not generate sign '?' by id parameter.

答:
The simplest way to do it is to change the url property of the Ajax options...

```<code>$.ajax({
    dataType: 'json',
    url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
    type: "GET",
    success: function (data) {
        bindData(data);
        $("#alert-placeholder").empty();
        $('#alert-placeholder').removeClass('alert alert-danger');
    },
    error: function (xhr, textStatus, errorThrown) {
        $('#alert-placeholder').addClass('alert alert-danger');
        $('#alert-placeholder').html(errorThrown);
    }
});
</code>```

GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.

However, if you wanted to modify existing Ajax requests you can use prefiltering.  This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...

```<code>$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    options.data = ""; // this removes the querystring
    for (key in originalOptions.data) {
        options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
    }
});

$.ajax({
    url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
    data: {
        "tuDispId": 179
    }
});
</code>```

If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.

Body:
I use the following ajax script.

$.ajax({
            dataType: 'json',
            url: url,
            data:  tuDispId,
            type: "GET",
            success: function (data) {
                bindData(data);
                $("#alert-placeholder").empty();
                $('#alert-placeholder').removeClass('alert alert-danger');
            },
            error: function (xhr, textStatus, errorThrown) {
                $('#alert-placeholder').addClass('alert alert-danger');
                $('#alert-placeholder').html(errorThrown);
            }
        });

The attribute Route in Web API before method.

[Route("api/tudisp/Edit/{tuDispId}")]
        public IHttpActionResult Edit(int tuDispId)
{
}

The genarated request from ajax.

http://localhost:xxxxx/api/tudisp/Edit/?179

How to force ajax to not generate sign '?' by id parameter.

Body:
The simplest way to do it is to change the url property of the Ajax options...

$.ajax({
    dataType: 'json',
    url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
    type: "GET",
    success: function (data) {
        bindData(data);
        $("#alert-placeholder").empty();
        $('#alert-placeholder').removeClass('alert alert-danger');
    },
    error: function (xhr, textStatus, errorThrown) {
        $('#alert-placeholder').addClass('alert alert-danger');
        $('#alert-placeholder').html(errorThrown);
    }
});

GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.

However, if you wanted to modify existing Ajax requests you can use prefiltering.  This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    options.data = ""; // this removes the querystring
    for (key in originalOptions.data) {
        options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
    }
});

$.ajax({
    url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
    data: {
        "tuDispId": 179
    }
});

If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.


问:
Can multiword abbreviations in TEI be combined with <w> and <ex> elements?
I'm developing a TEI P5 XML text edition that requires that abbreviations include <am> elements to signal abbreviation markers and <ex> elements to indicate the expanded matter of these abbreviations within their respective  and <expan> environments. Now I am investigating the feasibility of encoding <w> word elements as well, thus:

```<code><w>
 <choice>
  <abbr>þa<am>&combmacr;</am></abbr>
  <expan>þa<ex>m</ex></expan>
 </choice>
</w>
</code>```

The syntax is straightforward as long as the <choice> environment encodes one word and one word only. However, I'm worried multiword abbreviations cannot straightforwardly be combined with word elements, as whichever of <w> or <ex> comes last needs to be closed before the former is. Thus the <expan> line in the following won't validate:

```<code><choice>
 <abbr><w>L<am>&baracr;</am></w></abbr>
 <expan><w>L<ex>EOFAN</w> <w>MEN</w></ex></expan>
</choice>
</code>```

I cannot contain the full <ex> element within a single <w> or both <w> elements within <ex> because the first letter of the first word (in this example) is in the manuscript and thus does not count as an editorial expansion. Is there any way around this?

NB My reason for wanting to encode words is not to lemmatize but to be able to encode manuscript word spacing alongside lexical word spacing: by having my XSL strip or preserve space in <w> elements, I can choose to display word spacing either by modern standards or as presented in the manuscript by way of a parameter. This is also why it would be undesirable to enclose the entire <choice> environment in a single <w> tag, unless perhaps in any multiword expansions I add in word spacing using a special character to be translated into a regular space by the XSL styhesleet (a non-breaking space perhaps?). Is that what I should be looking at? (Using XSLT 2.0.)

答:
Yes, I think too that <w> inside of <choice> makes sense here. As you demonstrated, one abbreviation can unfold in more than one word. Consequently, it would be right to have multiple <ex> as well. Why not encode it like this:

```<code><expan><w>L<ex>EOFAN</ex></w> <w><ex>MEN</ex></w></expan>
</code>```

However, I was thinking of another issue. You said that you need <w> only to "encode manuscript word spacing alongside lexical word spacing". As <expan> is definitively not on manuscript level, but only on interpretative level, why would you need to separate <w> here at all? In the end, would it be sufficient to give the expansion simply within one <w>? The space between LEOFAN and MEN is editorial anyway. So why not try this as well:

```<code><expan><w>L<ex>EOFAN MEN</ex></w></expan>
</code>```

Body:
I'm developing a TEI P5 XML text edition that requires that abbreviations include <am> elements to signal abbreviation markers and <ex> elements to indicate the expanded matter of these abbreviations within their respective  and <expan> environments. Now I am investigating the feasibility of encoding <w> word elements as well, thus:

<w>
 <choice>
  þa<am>&combmacr;</am>
  <expan>þa<ex>m</ex></expan>
 </choice>
</w>

The syntax is straightforward as long as the <choice> environment encodes one word and one word only. However, I'm worried multiword abbreviations cannot straightforwardly be combined with word elements, as whichever of <w> or <ex> comes last needs to be closed before the former is. Thus the <expan> line in the following won't validate:

<choice>
 <w>L<am>&baracr;</am></w>
 <expan><w>L<ex>EOFAN</w> <w>MEN</w></ex></expan>
</choice>

I cannot contain the full <ex> element within a single <w> or both <w> elements within <ex> because the first letter of the first word (in this example) is in the manuscript and thus does not count as an editorial expansion. Is there any way around this?

NB My reason for wanting to encode words is not to lemmatize but to be able to encode manuscript word spacing alongside lexical word spacing: by having my XSL strip or preserve space in <w> elements, I can choose to display word spacing either by modern standards or as presented in the manuscript by way of a parameter. This is also why it would be undesirable to enclose the entire <choice> environment in a single <w> tag, unless perhaps in any multiword expansions I add in word spacing using a special character to be translated into a regular space by the XSL styhesleet (a non-breaking space perhaps?). Is that what I should be looking at? (Using XSLT 2.0.)

Body:
Yes, I think too that <w> inside of <choice> makes sense here. As you demonstrated, one abbreviation can unfold in more than one word. Consequently, it would be right to have multiple <ex> as well. Why not encode it like this:

<expan><w>L<ex>EOFAN</ex></w> <w><ex>MEN</ex></w></expan>

However, I was thinking of another issue. You said that you need <w> only to "encode manuscript word spacing alongside lexical word spacing". As <expan> is definitively not on manuscript level, but only on interpretative level, why would you need to separate <w> here at all? In the end, would it be sufficient to give the expansion simply within one <w>? The space between LEOFAN and MEN is editorial anyway. So why not try this as well:

<expan><w>L<ex>EOFAN MEN</ex></w></expan>


问:
How to make variable values carry over outside of if statement
So, I've made a rock paper scissors program, and it works like a charm.  The only gripe I have with it is that the scores in the output do not carry over afterwards.  This is written in Python- and forgive me if the code in the box below is formatted wrong, I'm new to stack overflow.

ties = ties + 1, for example, will print properly, but then when the program is run again, if I get another tie, it won't say ties = 2, it'll keep saying Ties:  1.  Or if I get a tie and a loss, it'll say Ties:  1 Loses:  0 and then it'll print Ties:  0 Loses:  1

```<code>import random
def main():

    playRPS = str.lower(input("Play a game or rock paper scissors?  Yes or no.  "))
    if(playRPS == "no"):
        print("Well, why did you run the program them?")
    while(playRPS == "yes"):
        human = int(input("Welcome to rock paper scissors!  Type 1 for rock, 2 for paper, or 3 for scissors"))
        cpu = random.randint(1,3)
        ties = 0
        wins = 0
        loses = 0
        if(human == cpu):
            print("It's a tie!")
            ties = ties + 1
            playRPS = input("Play again?")
        elif(human == 1 and cpu == 2):
            print("The computer picked paper, you picked rock, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 1 and cpu == 3):
            print("The computer picked scissors, you picked rock, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        elif(human == 2 and cpu == 1):
            print("You picked paper, the computer picked rock, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        elif(human == 2 and cpu == 3):
            print("You picked paper, the computer picked scissors, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 3 and cpu == 1):
            print("You picked scissors, the computer picked rock, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 3 and cpu == 2):
            print("You picked scissors, the computer picked paper, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        else:
            print("An error occured, maybe you typed 4, or 5, or maybe you made a typo.")
        playRPS = str.lower(input("Another game?  Yes or no."))
        print("Wins:  " + str(wins))
        print("Ties:  " + str(ties))
        print("Loses  " + str(loses))
</code>```

main()

答: As your code is written, each time the while loop runs, it resets ties, wins, and losses back to zero. Move those expressions outside the while loop, and the values won't be reset with each new game.

Body:
So, I've made a rock paper scissors program, and it works like a charm.  The only gripe I have with it is that the scores in the output do not carry over afterwards.  This is written in Python- and forgive me if the code in the box below is formatted wrong, I'm new to stack overflow.

ties = ties + 1, for example, will print properly, but then when the program is run again, if I get another tie, it won't say ties = 2, it'll keep saying Ties:  1.  Or if I get a tie and a loss, it'll say Ties:  1 Loses:  0 and then it'll print Ties:  0 Loses:  1

import random
def main():

    playRPS = str.lower(input("Play a game or rock paper scissors?  Yes or no.  "))
    if(playRPS == "no"):
        print("Well, why did you run the program them?")
    while(playRPS == "yes"):
        human = int(input("Welcome to rock paper scissors!  Type 1 for rock, 2 for paper, or 3 for scissors"))
        cpu = random.randint(1,3)
        ties = 0
        wins = 0
        loses = 0
        if(human == cpu):
            print("It's a tie!")
            ties = ties + 1
            playRPS = input("Play again?")
        elif(human == 1 and cpu == 2):
            print("The computer picked paper, you picked rock, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 1 and cpu == 3):
            print("The computer picked scissors, you picked rock, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        elif(human == 2 and cpu == 1):
            print("You picked paper, the computer picked rock, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        elif(human == 2 and cpu == 3):
            print("You picked paper, the computer picked scissors, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 3 and cpu == 1):
            print("You picked scissors, the computer picked rock, CPU wins!")
            loses = loses + 1
            playRPS = input("Play again?")
        elif(human == 3 and cpu == 2):
            print("You picked scissors, the computer picked paper, You win!")
            wins = wins + 1
            playRPS = input("Play again?")
        else:
            print("An error occured, maybe you typed 4, or 5, or maybe you made a typo.")
        playRPS = str.lower(input("Another game?  Yes or no."))
        print("Wins:  " + str(wins))
        print("Ties:  " + str(ties))
        print("Loses  " + str(loses))

main()


问:
How to remove notification action
I have a method that creates/updates a notification:

```<code>private void createNotification(Boolean removeAction) {
        getButtonPendingIntent().cancel();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("My App")
                .setOngoing(true)
                .setPriority(NotificationCompat.PRIORITY_MAX);

        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle("My App");

        if (removeAction) {
            String msg = "Some message";
            bigTextStyle.bigText(msg);
            builder.setContentText(msg);
            // this will remove button but leaves an empty space where the button existed
            builder.addAction(0, null, null);
        } else {
            String msg = "You are logged in. Slide down to logout.";
            bigTextStyle.bigText(msg);
            builder.setContentText(msg);
            builder.addAction(R.drawable.some_icon, "My Button", getButtonPendingIntent());
        }

        builder.setStyle(bigTextStyle);

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, ResultActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(ResultActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(100, builder.build());
    }
</code>```

Sometimes I need to remove the action that I created with the notification.  If I just create a new build and notify of a new event that does not have the action, the action button still remains.

I add in this code:

```<code>builder.addAction(0, null, null);
</code>```

And that removes the action button, however still leaves a blank space in the notification screen where the button used to be.  Is there a 'right' way to remove an action from a notification, and the space it used?

答:
Just clear the actions from notifications and notify it.</p>

```<code>notificationBuilder.mActions.clear();
notificationManager.notify(id, notificationBuilder.build());
</code>```

Title: How to remove notification action

Body:
I have a method that creates/updates a notification:

private void createNotification(Boolean removeAction) {
        getButtonPendingIntent().cancel();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("My App")
                .setOngoing(true)
                .setPriority(NotificationCompat.PRIORITY_MAX);

        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle("My App");

        if (removeAction) {
            String msg = "Some message";
            bigTextStyle.bigText(msg);
            builder.setContentText(msg);
            // this will remove button but leaves an empty space where the button existed
            builder.addAction(0, null, null);
        } else {
            String msg = "You are logged in. Slide down to logout.";
            bigTextStyle.bigText(msg);
            builder.setContentText(msg);
            builder.addAction(R.drawable.some_icon, "My Button", getButtonPendingIntent());
        }

        builder.setStyle(bigTextStyle);

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, ResultActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(ResultActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(100, builder.build());
    }

Sometimes I need to remove the action that I created with the notification.  If I just create a new build and notify of a new event that does not have the action, the action button still remains.

I add in this code:

builder.addAction(0, null, null);

And that removes the action button, however still leaves a blank space in the notification screen where the button used to be.  Is there a 'right' way to remove an action from a notification, and the space it used?

Body:
Just clear the actions from notifications and notify it.

notificationBuilder.mActions.clear();
notificationManager.notify(id, notificationBuilder.build());


问:
Get all values of some fields in MongoDB
I have objects like this:

```<code>{
    model:"Samsung Galaxy Note 8",
    cpu : "Snapdragon 835 Exynos 8895",
    storage: "64/128/256 GB",
    removable:"256GB microSDXC",
    ram: "6 GB",
    os: "Android 7.1.1 'Nougat'",
    size:{
        l:162.5,
        h:74.8,
        w:8.6
    },
    weight:195,
    battery:"3300 mAh Li-Ion, non-removable battery",
    display:"6.3', 2960x1440",
    camera:{
        rear:12,
        front:8
    },
    image:"https://image.com"
}
</code>```

I want for example all the distinct values of cpus and rams. If I use distinct() mongodb function, i can get only all the values of one field, but if I want multiple fields?

答:
You can use aggregation. Like below and it will give you all the different combinations of cpu and ram:

```<code>db.datastorevalues.aggregate(
    [

        {
            $group: {
                _id:{
                     "cpu ":"$cpu ",
                     "ram":"$cpu "
                }
            }
        }
    ]

);
</code>```

edit

If you want all the distinct values for the cpus and all the distinct values for the rams in the database

```<code>db.datastorevalues.aggregate(
    [

        {
            $group: {
                _id: null,
                cpus: {$addToSet: "$cpu"},
                rams: {$addToSet: "$ram"},

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

Body:
I have objects like this:

{
    model:"Samsung Galaxy Note 8",
    cpu : "Snapdragon 835 Exynos 8895",
    storage: "64/128/256 GB",
    removable:"256GB microSDXC",
    ram: "6 GB",
    os: "Android 7.1.1 'Nougat'",
    size:{
        l:162.5,
        h:74.8,
        w:8.6
    },
    weight:195,
    battery:"3300 mAh Li-Ion, non-removable battery",
    display:"6.3', 2960x1440",
    camera:{
        rear:12,
        front:8
    },
    image:"https://image.com"
}

I want for example all the distinct values of cpus and rams. If I use distinct() mongodb function, i can get only all the values of one field, but if I want multiple fields?

Body:
You can use aggregation. Like below and it will give you all the different combinations of cpu and ram:

db.datastorevalues.aggregate(
    [

        {
            $group: {
                _id:{
                     "cpu ":"$cpu ",
                     "ram":"$cpu "
                }
            }
        }
    ]

);

edit

If you want all the distinct values for the cpus and all the distinct values for the rams in the database

db.datastorevalues.aggregate(
    [

        {
            $group: {
                _id: null,
                cpus: {$addToSet: "$cpu"},
                rams: {$addToSet: "$ram"},

            }
        }
    ]
);


问:
Web Project vs. class library
Is there any performance difference between the two?
I have a web project that only has some classes, but not UI specific items like aspx pages or ascx controls. Should I consider to move those in a Class Library rather thank keep them as a web project ?

Thanks.

答:
Just to clarify, you have phrased you question as if you have a web project without any ASPX or ASCX files.
I assume that what you mean that you have a web project with ASPX files, but also some classes that have no dependency to the ASPX files, and you are wondering if you should extract those classes to a new class library project.

As to the question, should you divide the project up, then that depends.

There is no run-time performance benefit the code in a single project. There might be a minor delay when starting the application, but once the assemblies are loaded, then the performance will be identical.

There might be a small development penalty however. I am of the impression that it takes longer to compile a system, if it is split up into many smaller projects, rather than one big one. But I have no data to back this up.

But I would not use that as a determining factor. The important question is, how is your code best structured.

Is it a larger application, I would split it up to have domain logic in one assembly and the presentation logic (web application) in another. Is it just a tiny application I would not.
Except perhaps if you want to run unit tests on the domain logic, in which case I would split it up, so I have one test assembly that tests the functionality of the domain logic assembly.

Title: Web Project vs. class library


问:
Unable to insert data into mysql database using AJAX
I'm making a timeline like project which allows to write comments on the posts. But I'm unable to insert the data. Comments are getting displayed as expected. The form values does not seem to pass on to the save_comments.php page.

Below's the codes

config.php

```<code><?php

   $con=new PDO("mysql:host=localhost;dbname=posts&comments","root","");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>
</code>```

index.php

```<code><?php
    include 'config.php';
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<?php

$sql=$con->prepare("SELECT * FROM posts");
$sql->execute();
$results=$sql->fetchAll(PDO::FETCH_ASSOC);
echo "<hr>";
foreach($results as $post){
    echo "<h2>".$post['post_title']."</h2><br>";
    echo $post['post_content']."<br>";
    ?>
<br><b>Comments</b>
<form id=comment_form_<?php echo $post['post_id']; ?> action="">
    <input type=hidden name=pid value=<?php echo $post['post_id']; ?> >
    <p><input type=text name=cbody id="comment_body_<?php echo $post['post_id']; ?>" placeholder="Write comment" ></p>
    <p><input type=text name= cauth id="comment_author_<?php echo $post['post_id']; ?>" placeholder="Your Name" ></p>
    <p><button class="submit_comment" post_id="<?php echo $post['post_id']; ?>" >Submit</button> </p>

</form>
<p><button class="show_comments" post_id="<?php echo $post['post_id']; ?>">Show comments</button></p>
<div id="comments_<?php echo $post['post_id']; ?>">

</div>
    <?php
   echo "<hr>";
}
?>
<script>
    $(document).ready(function() {
       $(".show_comments").click(function() {
            var post_id=$(this).attr('post_id');
            $("#comments_"+post_id).load("comments.php", {
                post_id:post_id
            });
    });
        $(".submit_comment").on("click",function() {
            var post_id=$(this).attr('post_id');
            $.ajax({
                data:$('#comment_form_'+post_id).serialize(),
                url:'save_comments.php',
                async : true,
                success: function(){
                    $("#comments_"+post_id).load("comments.php", {
                        post_id:post_id
                     });
                }
            })
        });
    });

</script>
</code>```

comments.php

```<code><?php

include 'config.php';
$post_id=$_POST['post_id'];
$pid=$post_id;
$sql1=$con->prepare("SELECT * FROM comments where post_id=:pid");
$sql1->bindParam(':pid',$pid);
$sql1->execute();
$results1=$sql1->fetchAll(PDO::FETCH_ASSOC);
foreach($results1 as $comment){
echo "<br><b><cite>".$comment['comment_author']."</cite></b><br>";
echo $comment['comment_body']."<br>";
}
</code>```

?>

save_comments.php

```<code>    <?php

include 'config.php';

$comment_body=$_POST['cbody'];
$comment_author=$_POST['cauth'];
$post_id=$_POST['pid'];
$sql2=$con->prepare("INSERT INTO comments Values(NULL,:pid,:cauth,:cbody)");
$sql2->bindParam(':pid',$post_id);
$sql2->bindParam(':cauth',$comment_author);
$sql2->bindParam(':cbody',$comment_body);
$sql2->execute();
?>
</code>```

PS: I'm still a beginner at AJAX & jquery

答:
You are not defining the ajax request as a POSTand therefor no POST variables are sent.

```<code>$.ajax({
  data:$('#comment_form_'+post_id).serialize(),
  url:'save_comments.php',
  async : true,
  method: 'POST', <---- ADD THIS
  success: function(){
      $("#comments_"+post_id).load("comments.php", {
          post_id:post_id
       });
  }
})
</code>```

Body:
I'm making a timeline like project which allows to write comments on the posts. But I'm unable to insert the data. Comments are getting displayed as expected. The form values does not seem to pass on to the save_comments.php page.

Below's the codes

config.php

<?php

   $con=new PDO("mysql:host=localhost;dbname=posts&comments","root","");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

index.php

<?php
    include 'config.php';
?>

<?php

$sql=$con->prepare("SELECT * FROM posts");
$sql->execute();
$results=$sql->fetchAll(PDO::FETCH_ASSOC);
echo "
";
foreach($results as $post){
    echo "
".$post['post_title']."

";
    echo $post['post_content']."
";
    ?>

Comments
<form id=comment_form_<?php echo $post['post_id']; ?> action="">
    <input type=hidden name=pid value=<?php echo $post['post_id']; ?> >

<input type=text name=cbody id="comment_body_<?php echo $post['post_id']; ?>" placeholder="Write comment" >

<input type=text name= cauth id="comment_author_<?php echo $post['post_id']; ?>" placeholder="Your Name" >

<button class="submit_comment" post_id="<?php echo $post['post_id']; ?>" >Submit</button>

</form>

<button class="show_comments" post_id="<?php echo $post['post_id']; ?>">Show comments</button>

<div id="comments_<?php echo $post['post_id']; ?>">

    <?php
   echo "
";
}
?>

comments.php

<?php

include 'config.php';
$post_id=$_POST['post_id'];
$pid=$post_id;
$sql1=$con->prepare("SELECT * FROM comments where post_id=:pid");
$sql1->bindParam(':pid',$pid);
$sql1->execute();
$results1=$sql1->fetchAll(PDO::FETCH_ASSOC);
foreach($results1 as $comment){
echo "
".$comment['comment_author']."
";
echo $comment['comment_body']."
";
}

?>

save_comments.php

    <?php

include 'config.php';

$comment_body=$_POST['cbody'];
$comment_author=$_POST['cauth'];
$post_id=$_POST['pid'];
$sql2=$con->prepare("INSERT INTO comments Values(NULL,:pid,:cauth,:cbody)");
$sql2->bindParam(':pid',$post_id);
$sql2->bindParam(':cauth',$comment_author);
$sql2->bindParam(':cbody',$comment_body);
$sql2->execute();
?>

PS: I'm still a beginner at AJAX & jquery

Body:
You are not defining the ajax request as a POSTand therefor no POST variables are sent.

$.ajax({
  data:$('#comment_form_'+post_id).serialize(),
  url:'save_comments.php',
  async : true,
  method: 'POST', <---- ADD THIS
  success: function(){
      $("#comments_"+post_id).load("comments.php", {
          post_id:post_id
       });
  }
})


问:
How to convert an IPv6 address to a binary string?
How to convert an IPv6 address to a binary string?

Example:

```<code>IPv6:    2001:0db8:85a3:0000:0000:8a2e:0370:7334
Binary:  0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100
</code>```

I want to do this in Java. Here is my failed attempt (I do not ask for a solution related to this attempt whatsoever):

Implemented in C++, where I am more familiar:

```<code>#include <iostream>
#include <string>

#define _BSD_SOURCE
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

std::string toBinary(unsigned long int decimalIpV6)
{
    std::string r;
    while(decimalIpV6!=0) {r=(decimalIpV6%2==0 ?"0":"1")+r; decimalIpV6/=2;}
    return r;
}

unsigned long int ipV6toDecimal(std::string binaryString) {
    struct sockaddr_in antelope;
    inet_aton(binaryString.c_str(), &antelope.sin_addr); // store IP in antelope
    // and this call is the same as the inet_aton() call, above:
    antelope.sin_addr.s_addr = inet_addr(binaryString.c_str());
    return antelope.sin_addr.s_addr;
}

int main() {
    std::string ipv6 = "192.168.0.0";
    unsigned long int ipv6decimal= ipV6toDecimal(ipv6);
    std::cout << toBinary(ipv6decimal) << std::endl;
    return 0;
}
</code>```

which is buggy and produces a wrong result ("1010100011000000").

PS: There is an IPv6 to Binary calculator online, which might help you when testing.

答:
You can also do it this way:

```<code>String ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String result = "";
for (String s : ipv6.split(":")) {
    int value = Integer.parseInt(s, 16);
    result += String.format("%16s", Integer.toBinaryString(value)).replace(' ', '0') + " ";
}

System.out.println(result);
</code>```

Output:

```<code>0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100
</code>```

EDIT

The previous solution won't work when the given IPv6 address is compressed. For example 3210:0000:0000:0000:0000:0000:0000:0000 can be shortened to 3210:: and is worth to mention that in those cases the solutions proposed so far won't work if we don't handle this first. To solve that issue you can do this:

```<code>String ipv6CompressedAddress = "3210::";
Inet6Address ipv6Address = (Inet6Address) Inet6Address.getByName(ipv6CompressedAddress);
String ipv6 = ipv6Address.getCanonicalHostName(); // 3210:0:0:0:0:0:0:0
</code>```

Here I'm using Java's IPv6 representation class Inet6Address to get a less compressed ip address. Then we can use the methods shown earlier to convert it to binary.

Body:
How to convert an IPv6 address to a binary string?

Example:

IPv6:    2001:0db8:85a3:0000:0000:8a2e:0370:7334
Binary:  0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100

I want to do this in Java. Here is my failed attempt (I do not ask for a solution related to this attempt whatsoever):

Implemented in C++, where I am more familiar:

#include <iostream>
#include <string>

#define _BSD_SOURCE
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

std::string toBinary(unsigned long int decimalIpV6)
{
    std::string r;
    while(decimalIpV6!=0) {r=(decimalIpV6%2==0 ?"0":"1")+r; decimalIpV6/=2;}
    return r;
}

unsigned long int ipV6toDecimal(std::string binaryString) {
    struct sockaddr_in antelope;
    inet_aton(binaryString.c_str(), &antelope.sin_addr); // store IP in antelope
    // and this call is the same as the inet_aton() call, above:
    antelope.sin_addr.s_addr = inet_addr(binaryString.c_str());
    return antelope.sin_addr.s_addr;
}

int main() {
    std::string ipv6 = "192.168.0.0";
    unsigned long int ipv6decimal= ipV6toDecimal(ipv6);
    std::cout << toBinary(ipv6decimal) << std::endl;
    return 0;
}

which is buggy and produces a wrong result ("1010100011000000").

PS: There is an IPv6 to Binary calculator online, which might help you when testing.

Body:
You can also do it this way:

String ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String result = "";
for (String s : ipv6.split(":")) {
    int value = Integer.parseInt(s, 16);
    result += String.format("%16s", Integer.toBinaryString(value)).replace(' ', '0') + " ";
}

System.out.println(result);

Output:

0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100

EDIT

The previous solution won't work when the given IPv6 address is compressed. For example 3210:0000:0000:0000:0000:0000:0000:0000 can be shortened to 3210:: and is worth to mention that in those cases the solutions proposed so far won't work if we don't handle this first. To solve that issue you can do this:

String ipv6CompressedAddress = "3210::";
Inet6Address ipv6Address = (Inet6Address) Inet6Address.getByName(ipv6CompressedAddress);
String ipv6 = ipv6Address.getCanonicalHostName(); // 3210:0:0:0:0:0:0:0

Here I'm using Java's IPv6 representation class Inet6Address to get a less compressed ip address. Then we can use the methods shown earlier to convert it to binary.


问:
Ansible nested loop tries to iterate over "all", "ungrouped" values only
I try to create an Ansible role which adds four lines to two files. I want to add line A, B, C and D to files /etc/pam.d/sshd and login.

I created a role:

```<code>---
  - name: Add a line
    lineinfile:
      path: "/etc/pam.d/{{ item.0.name }}"
      insertafter: #some line
      line: "{{ item.1 }}"
    with_nested:
      - "{{ paths }}"
      - "{{ groups }}"
</code>```

In vars folder I have a main.yml file with:

```<code>---
paths:
  - name: sshd
  - name: login

groups:
  - "line A"
  - "line B"
</code>```

etc.

paths works fine, line was added to proper files but Ansible doesn't add line A and line B. In this files after Ansible I have line all, ungrouped.

Where is the problem?

答:
groups is a magic variable, you can't override it in your playbooks:

groups is a list of all the groups (and hosts) in the inventory.

Rename your list to mygroups or something.

Body:
I try to create an Ansible role which adds four lines to two files. I want to add line A, B, C and D to files /etc/pam.d/sshd and login.

I created a role:

---
  - name: Add a line
    lineinfile:
      path: "/etc/pam.d/{{ item.0.name }}"
      insertafter: #some line
      line: "{{ item.1 }}"
    with_nested:
      - "{{ paths }}"
      - "{{ groups }}"

In vars folder I have a main.yml file with:

---
paths:
  - name: sshd
  - name: login

groups:
  - "line A"
  - "line B"

etc.

paths works fine, line was added to proper files but Ansible doesn't add line A and line B. In this files after Ansible I have line all, ungrouped.

Where is the problem?


问:
how to call python module with package name
I want to make a distributable python module, so I want to make users call functions inside of my module via just calling package name.

e.g.

/my_package/

/my_package/__init__.py

/my_package/src/

/my_package/src/__init__.py

/my_package/src/my_module.py

and, the contents of mymodule.py:

def test(): print('hello!')

in this case, I want to let users use my module like:

>>> import mypackage as mp

>>> mp.test()

hello!

just like tensorflow, numpy, etc. !!!

How should I configure __init__.py file and path info??

答:
I assume that you don't just want to expose test function but a lot of other functions. So, you can separately maintain a __all__ list in your my_package/__init__.py that exposes any external methods to be used by others.

So, your my_package/__init__.py would look like

```<code>from src.my_module import test

__all__ = [test, ]
</code>```

You can read about __all__ here: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package

ContentLicense: CC BY-SA 4.0

Body:
I assume that you don't just want to expose test function but a lot of other functions. So, you can separately maintain a __all__ list in your my_package/__init__.py that exposes any external methods to be used by others.

So, your my_package/__init__.py would look like

from src.my_module import test

__all__ = [test, ]

You can read about __all__ here: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package


问:
ActiveXObject(Excel) leaves EXCEL.EXE *32 in Procces <Javascript>
```<code>var Excel = new ActiveXObject('Excel.Application');

Excel.Visible = false;
var Excel_file = Excel.Workbooks.Open(Worksheet);
}

if(x == 2)
{
Excel_file.close(false);
Excel.Quit();
Excel.Application.Quit();
Excel = null;
Excel_file = null;

window.setTimeout(CollectGarbage, 10);
//Excel.DisplayAlerts = false;
}
</code>```

Windows Task Manager Display

I use ActiveXObject to open the excel application behind the scenes, perform my function (defined and called elsewhere) and then close it out. The problem is that through task manager, each time I run the program, it creates a new instance of EXCEL.EXE *32 in the process section.

This script is on a webpage and it will be run very often throughout the day. It is not feasible to create a different instance of it each time the program runs.

I tried to use the undocumented "CollectGarbage" as other people had recommended but it still doesn't fix the problem.

Any ideas?
Thank you.

答:
You can kill the task in task manager using the same activex object. Try the below

```<code>var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("taskkill /F /IM EXCEL.exe");
</code>```

TASKKILL

End one or more processes (by process id or image name).

Syntax
      TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

Options
    /S   system           The remote system to connect to.

```<code>/U   [domain\]user    The user context under which
                      the command should execute.

/P   [password]       The password. Prompts for input if omitted.

/F                    Forcefully terminate the process(es).

/FI  filter           Display a set of tasks that match a
                      given criteria specified by the filter.

/PID process id       The PID of the process to be terminated.

/IM  image name       The image name of the process to be terminated.
                      Wildcard '*' can be used to specify all image names.

/T                     Tree kill: terminates the specified process
                       and any child processes which were started by it.
</code>```

Filters    Apply one of the Filters below:

```<code>         Imagename   eq, ne                  String
         PID         eq, ne, gt, lt, ge, le  Positive integer.
         Session     eq, ne, gt, lt, ge, le  Any valid session number.
         Status      eq, ne                  RUNNING | NOT RESPONDING
         CPUTime     eq, ne, gt, lt, ge, le  Time hh:mm:ss
         MemUsage    eq, ne, gt, lt, ge, le  Any valid integer.
         Username    eq, ne                  User name ([Domain\]User).
         Services    eq, ne                  String The service name
         Windowtitle eq, ne                  String
         Modules     eq, ne                  String The DLL name
</code>```

Body:
var Excel = new ActiveXObject('Excel.Application');

Excel.Visible = false;
var Excel_file = Excel.Workbooks.Open(Worksheet);
}

if(x == 2)
{
Excel_file.close(false);
Excel.Quit();
Excel.Application.Quit();
Excel = null;
Excel_file = null;

window.setTimeout(CollectGarbage, 10);
//Excel.DisplayAlerts = false;
}

Windows Task Manager Display

I use ActiveXObject to open the excel application behind the scenes, perform my function (defined and called elsewhere) and then close it out. The problem is that through task manager, each time I run the program, it creates a new instance of EXCEL.EXE *32 in the process section.

This script is on a webpage and it will be run very often throughout the day. It is not feasible to create a different instance of it each time the program runs.

I tried to use the undocumented "CollectGarbage" as other people had recommended but it still doesn't fix the problem.

Any ideas?
Thank you.

Body:
You can kill the task in task manager using the same activex object. Try the below

var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("taskkill /F /IM EXCEL.exe");

TASKKILL

End one or more processes (by process id or image name).

Syntax
      TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

Options
    /S   system           The remote system to connect to.

/U   [domain\]user    The user context under which
                      the command should execute.

/P   [password]       The password. Prompts for input if omitted.

/F                    Forcefully terminate the process(es).

/FI  filter           Display a set of tasks that match a
                      given criteria specified by the filter.

/PID process id       The PID of the process to be terminated.

/IM  image name       The image name of the process to be terminated.
                      Wildcard '*' can be used to specify all image names.

/T                     Tree kill: terminates the specified process
                       and any child processes which were started by it.

Filters    Apply one of the Filters below:

         Imagename   eq, ne                  String
         PID         eq, ne, gt, lt, ge, le  Positive integer.
         Session     eq, ne, gt, lt, ge, le  Any valid session number.
         Status      eq, ne                  RUNNING | NOT RESPONDING
         CPUTime     eq, ne, gt, lt, ge, le  Time hh:mm:ss
         MemUsage    eq, ne, gt, lt, ge, le  Any valid integer.
         Username    eq, ne                  User name ([Domain\]User).
         Services    eq, ne                  String The service name
         Windowtitle eq, ne                  String
         Modules     eq, ne                  String The DLL name


答:
You can use $aggregate. Aggregation pipeline has a lot of useful methods.

Aggregate query to group and find distinct values on cpus and ram is

```<code>db.so.aggregate([{$group:{_id:{ram:"$ram", cpu:"$cpu"}}}])
</code>```

Title: Get all values of some fields in MongoDB

Body:
You can use $aggregate. Aggregation pipeline has a lot of useful methods.

Aggregate query to group and find distinct values on cpus and ram is

db.so.aggregate([{$group:{_id:{ram:"$ram", cpu:"$cpu"}}}])


问:
Carthage update is failing with error 'could not posix spawn 35'

I have an application which was developed in Xcode 7.3 and Swift 2. Now I am trying to convert it to Swift 3.0.2, as the dependency manager I am using is Carthage. Now I am updating my Carthage so that all the frameworks should support swift 3.0.2. For this, first I have used the following command:

```<code>"carthage update --platform iOS"
</code>```

It now fetches all the dependencies and check out all the dependencies but then after checkout it starts to build the dependencies and while building the dependency it just fails with an error.

Here is a attached screenshot of the error. I am totally blank on what I am missing in this case:

答:
When I faced the problem , this is how I resolved it:

I deleted everything that was checked out and got all new fetches and builds

Ran carthage update --no-build && carthage bootstrap

This problem mainly occurs in Xcode 7.3 beta2 (7D129n) toolchain. Carthage version0.12 will build the cartfile successfully if you set xcselect to 7.2.1.

Version v0.11 didn't have this problem. The problem occurs during the build, maybe because all the versions of Carthage dependencies don't match too. I also read a few posts which asked me to supply with sudo carthage update --platform iOS --no-use-binaries.

And you're using a really old version of Xcode. I'll suggest you to upgrade.

Body:
I have an application which was developed in Xcode 7.3 and Swift 2. Now I am trying to convert it to Swift 3.0.2, as the dependency manager I am using is Carthage. Now I am updating my Carthage so that all the frameworks should support swift 3.0.2. For this, first I have used the following command:

"carthage update --platform iOS"

It now fetches all the dependencies and check out all the dependencies but then after checkout it starts to build the dependencies and while building the dependency it just fails with an error.

Here is a attached screenshot of the error. I am totally blank on what I am missing in this case:


问:
Looping jquery function load() using php mysql doesn't work it loop first row only
I need to show the posts count depend on topic id using auto load jquery load() after looping the result using php but unfortunately it shows the first row and uses that first row to show another count and change again
Any Help please!

index.php

```<code>    <?php
    foreach($t_all_rows as $row){
            ?>
         <tr>
             <td class="text-center hidden-xs hidden-sm">
                 <a class="font-w600" href="javascript:void(0)">
                    <script type="text/javascript">
                                    var auto_refresh = setInterval(
                                    function ()
                                    {
            $('#load_posts').load('get_posts.php?t_id=<?php echo $row['t_id']; ?>').fadeIn("slow");
                                    }, 1000); // refresh every 5000 milliseconds
                                    </script>

                                   <span id="load_posts"></span>
                </a>
          </td>
       </tr>
       <?php } ?>
</code>```

get_posts.php

```<code>    include('connection.php');
    $db=new DB();
    $conn=$db->db_connect();
    $my_t_id=$_GET['t_id'];
    $post_query = mysqli_query($conn,'SELECT * FROM post WHERE t_id = "'.$my_t_id.'"');
    $record_count=mysqli_num_rows($post_query);
    //Display count.........
    echo $record_count;
</code>```

答:
Thanks for the help i finally realize i shoud use class instead of id</p>

```<code><script type="text/javascript">
                                var auto_refresh = setInterval(
                                function ()
                                {
        $('.load_posts<?php echo $index; ?>').load('get_posts.php?t_id=<?php echo $row['t_id']; ?>').fadeIn("slow");
                                }, 1000); // refresh every 5000 milliseconds
                                </script>

                               <span class="load_posts<?php echo $index; ?>"></span>
</code>```

Body:
I need to show the posts count depend on topic id using auto load jquery load() after looping the result using php but unfortunately it shows the first row and uses that first row to show another count and change again
Any Help please!

index.php

    <?php
    foreach($t_all_rows as $row){
            ?>

       <?php } ?>

get_posts.php

    include('connection.php');
    $db=new DB();
    $conn=$db->db_connect();
    $my_t_id=$_GET['t_id'];
    $post_query = mysqli_query($conn,'SELECT * FROM post WHERE t_id = "'.$my_t_id.'"');
    $record_count=mysqli_num_rows($post_query);
    //Display count.........
    echo $record_count;

Body:
Thanks for the help i finally realize i shoud use class instead of id

<script type="text/javascript">
                                var auto_refresh = setInterval(
                                function ()
                                {
        $('.load_posts<?php echo $index; ?>').load('get_posts.php?t_id=<?php echo $row['t_id']; ?>').fadeIn("slow");
                                }, 1000); // refresh every 5000 milliseconds
                                </script>

                               <span class="load_posts<?php echo $index; ?>"></span>


问:
How to generate excel file using node.js?
Hi I am go for the generate excel file form the array but I am not getting successes. I am work using node.js and I am use npm package for generate excel file but I am not getting any data in excel file. excel is generate but not getting any type of data in my file. so any one know where is my mistake then please let me know how can fix it.

This is my array and query =>

```<code>            var XLSX = require('xlsx');
                   var Array = [];
                    Array.push({
                        username: 'Carakc',
                        fullName: 'Crack',
                        followingCount: 2655,
                        followerCount: 466,
                        biography: 'I am new man'
                    },
                  {
                      username: 'mahi',
                      fullName: 'Fit',
                      followingCount: 3011,
                      followerCount: 385,
                      biography: 'hello everyone!'
                  })

app.get(prefix + '/GetFollowersInExcel', function (req, res, next) {
                    var ws = XLSX.utils.json_to_sheet(Array);
                    var wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "Followres");
                    var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
                    res.end(wbout, 'binary');
                }
            });
        }
    });
})
</code>```

This is my service code =>

```<code>GetFollowersInExcel: function (InstaId) {
        return $http({
            method: "GET",
            url: ONURL + "GetFollowersInExcel",
            responseType: "arraybuffer",
            headers: {
                'Content-type': 'application/json',
                'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }
        }).then(function (data, status, xhr) {
            debugger;
            if (data.data.byteLength > 0) {
                var file = new Blob([data.data], { type: 'application/binary' });
                var fileURL = URL.createObjectURL(file);
                $('#getexcel').show();
                var link = document.createElement('a');
                link.href = fileURL;
                link.download = "myfile.xlsx";
                link.click();
                URL.revokeObjectURL(file);
            }
        }, function (error) {
            return error;
        })
    },
</code>```

using this wave I am getting like this data in excel =>

I want like this data in excel file =>

答:
I've tried your first code and I've found no errors, the resulting xlsx is perfect.

Peheraps I've found the problem: var Array is declared outside the app.get callback... Are you sure that your var Array can be correctly reached by XLSX.utils.json_to_sheet? it's in the same scope? or it's declared somewhere inaccessible?

try to declare it inside the callback and probably all will work well, and, if this is the case, you can use a class or a method to retrieve the var from outside ("how" depends on your code)

P.s. change the name of the var, is not a good habit overwrite the Array object ;)

Body:
Hi I am go for the generate excel file form the array but I am not getting successes. I am work using node.js and I am use npm package for generate excel file but I am not getting any data in excel file. excel is generate but not getting any type of data in my file. so any one know where is my mistake then please let me know how can fix it.

This is my array and query =>

            var XLSX = require('xlsx');
                   var Array = [];
                    Array.push({
                        username: 'Carakc',
                        fullName: 'Crack',
                        followingCount: 2655,
                        followerCount: 466,
                        biography: 'I am new man'
                    },
                  {
                      username: 'mahi',
                      fullName: 'Fit',
                      followingCount: 3011,
                      followerCount: 385,
                      biography: 'hello everyone!'
                  })

app.get(prefix + '/GetFollowersInExcel', function (req, res, next) {
                    var ws = XLSX.utils.json_to_sheet(Array);
                    var wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "Followres");
                    var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
                    res.end(wbout, 'binary');
                }
            });
        }
    });
})

This is my service code =>

GetFollowersInExcel: function (InstaId) {
        return $http({
            method: "GET",
            url: ONURL + "GetFollowersInExcel",
            responseType: "arraybuffer",
            headers: {
                'Content-type': 'application/json',
                'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }
        }).then(function (data, status, xhr) {
            debugger;
            if (data.data.byteLength > 0) {
                var file = new Blob([data.data], { type: 'application/binary' });
                var fileURL = URL.createObjectURL(file);
                $('#getexcel').show();
                var link = document.createElement('a');
                link.href = fileURL;
                link.download = "myfile.xlsx";
                link.click();
                URL.revokeObjectURL(file);
            }
        }, function (error) {
            return error;
        })
    },

using this wave I am getting like this data in excel =>

I want like this data in excel file =>


问:
pg_restore fails with missing tablespace eventhough --no-tablespaces is given
I'm trying to import a database into postgres with the following command:

"C:\Program Files\PostgreSQL\9.5\bin\pg_restore.exe" --dbname=postgres --clean --create --format=d --jobs=16 --no-tablespaces --host=localhost --username=postgres "S:\Directory-Dump_Inn"
```
<p>The fine manual says:</p>
<blockquote>
<p>--no-tablespaces</p>
<p>Do not output commands to select tablespaces. With this option, all objects will be created in whichever tablespace is the default during restore.</p>
</blockquote>
<p>I thought this means I wouldn't have to create the tablespace, from which the dump orgins. As the import fails with</p>
<pre class="lang-none prettyprint-override"><code>ERROR: tablespace "ts_inn" does not exist
</code>```

I guess, this assumption is wrong. So what does the explanation from the manual mean then?
The import works fine if I create the tablespace beforehand.

Edit: Version of importing server is 9.5.4, version of exporting server is 9.6.3. Probably the export command is important, too:

```<code>"C:\Program Files\PostgreSQL\9.6\bin\pg_dump.exe" --host localhost --port 5432 --username "postgres" --no-password  --format directory --section pre-data --section data --section post-data --compress 0 --jobs 4 --verbose --file "F:\Postgres-Backup\Directory-Dump_Inn" "inn" 2>> %logfile%
</code>```

Is the culprit that the export omits --no-tablespaces? If it is and if I added --no-tablespaces as an argument to pg_dump, then why would I use --no-tablespaces during import? Obviously then there wouldn't be any CREATE TABLESPACE xxx in the dump file.

答:
A problem quite like yours was fixed in this commit in Sep 2016 to fix bug #14315, so make sure that you have PostgreSQL 9.5 or later with the latest patches.

But even with these patches your example will fail, because you didn't add --no-tablespaces to the invocation of pg_dump.

It is kind of surprising, but to suppress the TABLESPACE clause of CREATE DATABASE in the dump, it is not enough to call pg_restore --no-tablespaces. The dump has to be created with that option.

Body:
I'm trying to import a database into postgres with the following command:

"C:\Program Files\PostgreSQL\9.5\bin\pg_restore.exe" --dbname=postgres --clean --create --format=d --jobs=16 --no-tablespaces --host=localhost --username=postgres "S:\Directory-Dump_Inn"

The fine manual says:

--no-tablespaces

Do not output commands to select tablespaces. With this option, all objects will be created in whichever tablespace is the default during restore.

I thought this means I wouldn't have to create the tablespace, from which the dump orgins. As the import fails with

ERROR: tablespace "ts_inn" does not exist

I guess, this assumption is wrong. So what does the explanation from the manual mean then?
The import works fine if I create the tablespace beforehand.

Edit: Version of importing server is 9.5.4, version of exporting server is 9.6.3. Probably the export command is important, too:

"C:\Program Files\PostgreSQL\9.6\bin\pg_dump.exe" --host localhost --port 5432 --username "postgres" --no-password  --format directory --section pre-data --section data --section post-data --compress 0 --jobs 4 --verbose --file "F:\Postgres-Backup\Directory-Dump_Inn" "inn" 2>> %logfile%

Is the culprit that the export omits --no-tablespaces? If it is and if I added --no-tablespaces as an argument to pg_dump, then why would I use --no-tablespaces during import? Obviously then there wouldn't be any CREATE TABLESPACE xxx in the dump file.


问:
Editext setError icon disappear on Android 4.4.2 and 4.3 when length of my edittext is 0 and I press delete one more time
I'm using the setError on my Edittext.
It's working when I need to show the message but on Android 4.4.2 and 4.3 when my Edittext has length = 0 and I press delete one more time, the icon and message error gone.

On Android 6.0 and 6.0.1 this isn't happenning.

Here is my code

```<code>private void enableBtnSend() {
    if (isDatesSelected() && etDetails.getText().toString().length() > 0) {
        btnCreateEnalbled = true;
        etDetails.setError(null);
        invalidateOptionsMenu();
    } else {
        if(etDetails.getText().toString().length() <= 0) {
            etDetails.setError(getString(R.string.empty_description_field));
        } else {
            etDetails.setError(null);
        }
        btnCreateEnalbled = false;
        invalidateOptionsMenu();
    }
}

private TextWatcher onEtAnswerChanged() {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.i("beforeTextChanged","beforeTextChanged");
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.i("onTextChanged","onTextChanged");
        }

        @Override
        public void afterTextChanged(Editable editable) {
            enableBtnSend();
        }
    };
}
</code>```

答:
```<code>private void enableBtnSend() {
    if (isDatesSelected() && etDetails.getText().toString().length() > 0) {
        btnCreateEnalbled = true;
        etDetails.setError(null);
        invalidateOptionsMenu();
    } else {
        if(etDetails.getText().toString().length() <= 0) {

        etDetails.setError(getString(R.string.empty_description_field));
    etDetails.requestFocus(); //add this
            } else {
                etDetails.setError(null);
    etDetails.requestFocus(); //add this
            }
            btnCreateEnalbled = false;
            invalidateOptionsMenu();
        }
    }
</code>```

It will work.

Body:
I'm using the setError on my Edittext.
It's working when I need to show the message but on Android 4.4.2 and 4.3 when my Edittext has length = 0 and I press delete one more time, the icon and message error gone.

On Android 6.0 and 6.0.1 this isn't happenning.

Here is my code

private void enableBtnSend() {
    if (isDatesSelected() && etDetails.getText().toString().length() > 0) {
        btnCreateEnalbled = true;
        etDetails.setError(null);
        invalidateOptionsMenu();
    } else {
        if(etDetails.getText().toString().length() <= 0) {
            etDetails.setError(getString(R.string.empty_description_field));
        } else {
            etDetails.setError(null);
        }
        btnCreateEnalbled = false;
        invalidateOptionsMenu();
    }
}

private TextWatcher onEtAnswerChanged() {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.i("beforeTextChanged","beforeTextChanged");
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Log.i("onTextChanged","onTextChanged");
        }

        @Override
        public void afterTextChanged(Editable editable) {
            enableBtnSend();
        }
    };
}

Body:
private void enableBtnSend() {
    if (isDatesSelected() && etDetails.getText().toString().length() > 0) {
        btnCreateEnalbled = true;
        etDetails.setError(null);
        invalidateOptionsMenu();
    } else {
        if(etDetails.getText().toString().length() <= 0) {

        etDetails.setError(getString(R.string.empty_description_field));
    etDetails.requestFocus(); //add this
            } else {
                etDetails.setError(null);
    etDetails.requestFocus(); //add this
            }
            btnCreateEnalbled = false;
            invalidateOptionsMenu();
        }
    }

It will work.


问:
Is there a design pattern to collect and aggregate information and report it at the end?
I'm working on a desktop software with user interface. The software lets the user do certain things. Now, this software will need to keep track of certain things the user has done over time. Finally, when the time is right, this software should post the information it has accumulated over time. I'm wondering what design pattern would fit in this scenario.

I used to use a static class and a static string field to accumulate the bits and pieces of information and finally send that string to report on the state. But I'm in a similar situation again and I think I could do better than make calls to this static field throughout the code.

Is there a design pattern around this?

答:
Expect simple answer here (no pattern).

You would EventEmitter.emit() an Event for every interesting (at every interesting place) thing that you would want to track in your application (for what ever purpose). The EventCollector is responsible for keeping track of all the events that are emitted. At the right time, the EventReporter will generate() a Report based on the Events collected and stored by EventCollector. So below are the classes I see.

EventEmitter

emit(Event e)

Event

EventCollector

EventReporter

Report generateReport()

You can ignore EventCollector for your simple use case and can use a Java Collection (List if you want to preserve the order the events happened etc).

There is nothing wrong in using a static holder for your simple scenario. Sometime simple things look suspicious to us programmer's ;-)

Events are no longer Strings. They are abstractions on their own.

Single Responsibility Principle: Each class doing one logical thing and can be tested independently

Simple and easy to understand


问:
When I build Xamarin solution I see: "javac.exe" exited with code 2 error
I just created a new Xamarin solution in visual studio. Here is how the solution looks like:

And when I try to build, it shows the following error:

"javac.exe" exited with code 2.

Here is the error logs in output window:

1>------ Rebuild All started: Project: App2.Droid, Configuration:
  Debug Any CPU ------ 1>C:\Program Files
  (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(605,2):
  warning : Failed to get the Java SDK version. Found java version
  "9.0.1" 1>C:\Program Files
  (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(605,2):
  warning : Java(TM) SE Runtime Environment (build 9.0.1+11)
  1>C:\Program Files
  (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(605,2):
  warning : Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed
  mode) 1>C:\Program Files
  (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(605,2):
  warning :  but this does not seem to contain a valid version number.
  1>  App2.Droid -> C:\Users\abaig\documents\visual studio
  2015\Projects\App2\App2\App2.Droid\bin\Debug\App2.Droid.dll
  1>C:\Program Files
  (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(1914,3):
  error MSB6006: "javac.exe" exited with code 2.
  ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Any Idea what could be wrong?

答:
Here is what solved this problem.

While setting up Xamarin I had installed Java SE Development Kit 9. Now I've uninstalled it and instead I have installed Java SE Development Kit 8. After installing Java SE Development Kit 8, all I did is, update the JDK location in Android Settings, so that it now points to JDK v8. See below:


问:
Gammu send sms using two or more java app from ssh at the same time
I'm using gammu to send sms, and I was wondering if it is possible to send messages at the same time using two or more computer with java app. I tried it 10 times and 1 out of 10 times the message successfully sent from both computer. 9 times only one computer can send the sms with the other one failing to send.
Is there some kind of setting or command so I can send message from both of this computers at the same time? For the config I use the default config from Gammu

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class TestingSms {

public static void main(String[] args) {
        // TODO Auto-generated method stub
        String host = "MY GAMMU IP";
        String user = "MY USERNAME";
        String password = "MY PASSWORD";
        int port = 22;
        String sms ="haloo";

        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelExec exec = (ChannelExec) session.openChannel("exec");
            exec.setCommand("gammu sendsms TEXT 08xxxxxxxxxx -text \""+sms+"\"");
            exec.setErrStream(System.err);

            exec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            String temp;
            while((temp=reader.readLine())!=null) {
                System.out.println(temp);
            }
            exec.disconnect();
            session.disconnect();

            System.out.println("\n\nFinish");
        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
</code>```

Failed Message:

```<code>Warning: No configuration read, using builtin defaults!
No response in specified timeout. Probably phone not connected.
</code>```

Thank you in advance

答:
Maybe you rather want to use Gammu SMSD for this - it runs on the server and sends/receives messages from/to database. This way you can easily send messages from other hosts just by inserting them to the database.

The error Warning: No configuration read, using builtin defaults! indicates that Gammu didn't find the configuration file, maybe you're running it as different user? Or try to specify path to configuration file using --config parameter.

Body:
I'm using gammu to send sms, and I was wondering if it is possible to send messages at the same time using two or more computer with java app. I tried it 10 times and 1 out of 10 times the message successfully sent from both computer. 9 times only one computer can send the sms with the other one failing to send.
Is there some kind of setting or command so I can send message from both of this computers at the same time? For the config I use the default config from Gammu

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class TestingSms {

public static void main(String[] args) {
        // TODO Auto-generated method stub
        String host = "MY GAMMU IP";
        String user = "MY USERNAME";
        String password = "MY PASSWORD";
        int port = 22;
        String sms ="haloo";

        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelExec exec = (ChannelExec) session.openChannel("exec");
            exec.setCommand("gammu sendsms TEXT 08xxxxxxxxxx -text \""+sms+"\"");
            exec.setErrStream(System.err);

            exec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            String temp;
            while((temp=reader.readLine())!=null) {
                System.out.println(temp);
            }
            exec.disconnect();
            session.disconnect();

            System.out.println("\n\nFinish");
        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Failed Message:

Warning: No configuration read, using builtin defaults!
No response in specified timeout. Probably phone not connected.

Thank you in advance


问:
numpy read .csv with complex number
stackoverflow,

I have a matrix containing complex numbers (ex. -2.2982235934153075E-11+2.1179547211742553E-9i) that I need to import to a numpy array. I've been using genfromtext(file) to parse all my other, real values, but I'm getting a nan for all complex values. Any ideas?

```<code>self.raw = (genfromtxt(self.loc, delimiter=',', skip_header=9, dtype=float))
[m,n] = shape(self.raw)
data = zeros((m, n-3))
data[:, :] = self.raw[:, 3::]
</code>```

returns:

```<code>data = array([nan, nan, nan, ...])
</code>```

答:
Import the csv file as an array of strings with genfromtxt(...) with dtype='str'. Then you can manipulate each entry with np.vectorize(...).

```<code>import numpy as np
from numpy import genfromtxt

# import data as an array of strings using the dtype
temp = genfromtxt('matlab_sim_Z.csv', delimiter=',',dtype='str')

# perform elementwise conversion to complex numpers
mapping = np.vectorize(lambda t:complex(t.replace('i','j')))
data = mapping(temp)
</code>```

In a single line:

```<code>data = np.vectorize(lambda t:complex(t.replace('i','j'))) (genfromtxt('matlab_sim_Z.csv', delimiter=',',dtype='str'))
</code>```

Title: numpy read .csv with complex number

Body:
stackoverflow,

I have a matrix containing complex numbers (ex. -2.2982235934153075E-11+2.1179547211742553E-9i) that I need to import to a numpy array. I've been using genfromtext(file) to parse all my other, real values, but I'm getting a nan for all complex values. Any ideas?

self.raw = (genfromtxt(self.loc, delimiter=',', skip_header=9, dtype=float))
[m,n] = shape(self.raw)
data = zeros((m, n-3))
data[:, :] = self.raw[:, 3::]

returns:

data = array([nan, nan, nan, ...])

Body:
Import the csv file as an array of strings with genfromtxt(...) with dtype='str'. Then you can manipulate each entry with np.vectorize(...).

import numpy as np
from numpy import genfromtxt

# import data as an array of strings using the dtype
temp = genfromtxt('matlab_sim_Z.csv', delimiter=',',dtype='str')

# perform elementwise conversion to complex numpers
mapping = np.vectorize(lambda t:complex(t.replace('i','j')))
data = mapping(temp)

In a single line:

data = np.vectorize(lambda t:complex(t.replace('i','j'))) (genfromtxt('matlab_sim_Z.csv', delimiter=',',dtype='str'))


问:
AWS s3 mv command deletes the source directory
The objective is to move all the files from s3 "dir2" directory to EMR directory "mydir".

I am using the command:

aws s3 mv s3:///dir1/dir2/ /mnt/mydir/ --recursive

This command gets executed but the dir2 directory from s3 gets deleted.
The files within dir2 although moves to mydir of EMR.

How can I only move the files from source dir of s3 without removing the source directory?

答: Directories or folders do not actually exist in S3. What you are calling a directory is simply a common file name prefix in S3. When there are no files with that prefix anymore then the "directory" does not exist anymore in S3.</p>