问:
Angular2 - reactive forms and multiple checkboxes not behaving correctly
I'm learning reactive forms still, and I want to have multiple checkboxes for a property that is array (e.g. hobby). So I defined the group as follows

this.myForm = this.fb.group({

    name: ['', Validators.required],

    hobbies: this.fb.array([])

});
```

<p>Hobbies is an array: <code>hobbies = ['Cooking', 'Swimming', 'Hiking', 'Dancing'];</code></p>

<p>Now, in HTML, I defined the checkboxes as follows:</p>

<pre class="lang-html prettyprint-override"><code><div>
  <span *ngFor="let hobby of hobbies">
    <label>
      <input type="checkbox" [value]="hobby" (click)="addToHobby(hobby)"> {{hobby}}
    </label>
    <br />
  </span>
</div>
</code>```

Now when checking an element it doesn't add it to the hobbies property at all, it just duplicates the actual HTML element. What am I doing wrong?

Here's the code: https://plnkr.co/edit/j8V189VoWKvloNgwOr7p?p=preview

答:
OK I managed to get something working. The link is available below, but firstly, here's my chain of thought.

Firstly, we need to just define an array of all values, possibly we get this from a web service, but still, I mock them like this:

hobbies = [new Hobby(1, 'Cooking'), new Hobby(2, 'Swimming'), new Hobby(3, 'Hiking'), new Hobby(4, 'Dancing')];

I purposely added id as well, so it will mimic the real world more accurately. Now, we need to define the form. Since the multi checkboxes is not going to work, I decided to represent an array of individual checkboxes, each having several attributes, but at least two are necessary: the boolean to decide if that checkbox in array was selected and a name so we can know what we're selecting.

In order to achieve this, we need to firstly create an array that would fit the form, which is done as follows:

let hobbiesArray = [];

for (let hobby of this.hobbies) {
  hobbiesArray.push(this.fb.group({
    isChosen: false,
    name: hobby.hobbyName,
    id: hobby.id
  }));
}
```

<p>As evident, I created new <code>fb.group</code> for each hobby and they're all placed in an array. This array is then used to create the form, as follows:</p>

<pre class="lang-ts prettyprint-override"><code>this.myForm = this.fb.group({
  hobbiesList: this.fb.array(hobbiesArray)
});
</code>```

Now we have an fb.array of fb.groups. Now, when it comes to HTML, I have several concerns.
The logic is "go through the myForm.hobbiesList and manipulate isChosen while keeping the name readonly - sort of. Here's the code.

    <input type="checkbox" formControlName="isChosen" /> {{hobby.controls.name.value}}

```

<p>Here's my concern: can I just address the name like this: <code>{{hobby.controls.name.value}}</code>? What harm can this do? Am I breaking any Angular2/4 rules?</p>

<p>OK, so, when confirming the selected hobbies, we get the actual array with name and ids (without the <code>isChosen</code> values) as follows:</p>

<pre class="lang-ts prettyprint-override"><code>submitMe(): void {
    let items = this.myForm.value;
    this.mySelectedHobbies = items.hobbiesList.filter(x => x.isChosen).map(x => { return { name: x.name, id: x.id }; });
}
</code>```

So yeah, this is my design. I'm not sure if it's all allowed what I did but I find this the easiest way to solve the issue. What do you guys think?

Here's the code: https://plnkr.co/edit/8OKiQMK788R2uCt2OWzm?p=preview

ContentLicense: CC BY-SA 4.0

Body:
I'm learning reactive forms still, and I want to have multiple checkboxes for a property that is array (e.g. hobby). So I defined the group as follows

this.myForm = this.fb.group({

    name: ['', Validators.required],

    hobbies: this.fb.array([])

});

Hobbies is an array: hobbies = ['Cooking', 'Swimming', 'Hiking', 'Dancing'];

Now, in HTML, I defined the checkboxes as follows:

      <input type="checkbox" [value]="hobby" (click)="addToHobby(hobby)"> {{hobby}}

Now when checking an element it doesn't add it to the hobbies property at all, it just duplicates the actual HTML element. What am I doing wrong?

Here's the code: https://plnkr.co/edit/j8V189VoWKvloNgwOr7p?p=preview

Body:
OK I managed to get something working. The link is available below, but firstly, here's my chain of thought.

Firstly, we need to just define an array of all values, possibly we get this from a web service, but still, I mock them like this:

hobbies = [new Hobby(1, 'Cooking'), new Hobby(2, 'Swimming'), new Hobby(3, 'Hiking'), new Hobby(4, 'Dancing')];

I purposely added id as well, so it will mimic the real world more accurately. Now, we need to define the form. Since the multi checkboxes is not going to work, I decided to represent an array of individual checkboxes, each having several attributes, but at least two are necessary: the boolean to decide if that checkbox in array was selected and a name so we can know what we're selecting.

In order to achieve this, we need to firstly create an array that would fit the form, which is done as follows:

let hobbiesArray = [];

for (let hobby of this.hobbies) {
  hobbiesArray.push(this.fb.group({
    isChosen: false,
    name: hobby.hobbyName,
    id: hobby.id
  }));
}

As evident, I created new fb.group for each hobby and they're all placed in an array. This array is then used to create the form, as follows:

this.myForm = this.fb.group({
  hobbiesList: this.fb.array(hobbiesArray)
});

Now we have an fb.array of fb.groups. Now, when it comes to HTML, I have several concerns.
The logic is "go through the myForm.hobbiesList and manipulate isChosen while keeping the name readonly - sort of. Here's the code.

<div formArrayName="hobbiesList">
  <div *ngFor="let hobby of hobbiesList.controls; let i=index" [formGroupName]="i" >
    <input type="checkbox" formControlName="isChosen" /> {{hobby.controls.name.value}}
  </div>
</div>

Here's my concern: can I just address the name like this: {{hobby.controls.name.value}}? What harm can this do? Am I breaking any Angular2/4 rules?

OK, so, when confirming the selected hobbies, we get the actual array with name and ids (without the isChosen values) as follows:

submitMe(): void {
    let items = this.myForm.value;
    this.mySelectedHobbies = items.hobbiesList.filter(x => x.isChosen).map(x => { return { name: x.name, id: x.id }; });
}

So yeah, this is my design. I'm not sure if it's all allowed what I did but I find this the easiest way to solve the issue. What do you guys think?

Here's the code: https://plnkr.co/edit/8OKiQMK788R2uCt2OWzm?p=preview


来源: stackexchange

问:
Text to Time with Milliseconds
In column A1 I have 16304238, which represents Hour, Minutes, Seconds and Milliseconds, which I want to display in B1 as 4:30:42:380 PM.

I know how to format with hour and minutes, but can't get the seconds and millisecond correct. I tried

```<code>=TIME(LEFT(E2,2),MID(E2,3,2),RIGHT(E2,2))
</code>```

Which comes out as 16:30:38.000. Also, I'm using

```<code>[h]:mm:ss.000
</code>```

to format the result. What do I need to use, instead of [h], to get AM/PM instead or military time?

答:
With 16304238 as a true number in A1,

```<code>=--TEXT(A1*POWER(10, MIN(0, 6-LEN(A1))), "00\:00\:00.000")
</code>```

This covers 0, 1, 2 or 3 decimal places. The result requires cell formatting as h:mm:ss.000 AM/PM.

ContentLicense: CC BY-SA 3.0

Title: Text to Time with Milliseconds

Body:
In column A1 I have 16304238, which represents Hour, Minutes, Seconds and Milliseconds, which I want to display in B1 as 4:30:42:380 PM.

I know how to format with hour and minutes, but can't get the seconds and millisecond correct. I tried

=TIME(LEFT(E2,2),MID(E2,3,2),RIGHT(E2,2))

Which comes out as 16:30:38.000. Also, I'm using

[h]:mm:ss.000

to format the result. What do I need to use, instead of [h], to get AM/PM instead or military time?

Body:
With 16304238 as a true number in A1,

=--TEXT(A1*POWER(10, MIN(0, 6-LEN(A1))), "00\:00\:00.000")

This covers 0, 1, 2 or 3 decimal places. The result requires cell formatting as h:mm:ss.000 AM/PM.


问:
Spark Scala println requires a collect()?
Just getting started with Spark and Scala.  We've installed Spark 2 on our dev cloudera hadoop cluster, and I'm using spark2-shell.  I'm going through a book to learn some basics.  It's examples show println(foo) working without doing a collect, but that's not working for me:

```<code>scala> val numbers = sc.parallelize(10 to 50 by 10)
numbers: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[9] at parallelize at <console>:24

scala> numbers.collect().foreach(println)
10
20
30
40
50

scala> numbers.foreach(x => println(x))

scala>
</code>```

As you can see, nothing prints unless I do a collect().

What's going on, is the book wrong, or is something funny with my spark/scala/config?

Version Info:

```<code>Spark version 2.0.0.cloudera2
Using Scala version 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111)
</code>```

答: That's the correct behaviour you experience, the code passed to numbers.foreach will be executed on the different nodes, but the output won't be collected and returned to the driver.

Body:
Just getting started with Spark and Scala.  We've installed Spark 2 on our dev cloudera hadoop cluster, and I'm using spark2-shell.  I'm going through a book to learn some basics.  It's examples show println(foo) working without doing a collect, but that's not working for me:

scala> val numbers = sc.parallelize(10 to 50 by 10)
numbers: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[9] at parallelize at <console>:24

scala> numbers.collect().foreach(println)
10
20
30
40
50

scala> numbers.foreach(x => println(x))

scala>

As you can see, nothing prints unless I do a collect().

What's going on, is the book wrong, or is something funny with my spark/scala/config?

Version Info:

Spark version 2.0.0.cloudera2
Using Scala version 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111)


问:
Should jmeter master start after 1/2 minutes of server started when running tests in non gui mode (master and slave)
Bamboo-jmeter task: Should time gap there before starting the jmeter master/slave. We have created bamboo task (SSH task1-with slave host, SSHtask2-with 2nd slave host, SSH task3-with master host and run commands). When first time the the task getting an error remote engine is not able to configured whereas able to telnet the hosts, also jmeter-server is already started.
However when disable SSHtask1 and task2 for the 2nd time run, it is able to run successfully and getting results also.
Should jmeter master start after 1/2 minutes of server started? Please suggest</p>

答: Able to overcome the problem by adding sleep time of 120 seconds after running the jmeter-server before starting the jmeter master.</p>


问:
CoreData Basics Help
EDIT:
I have altered the NSPredicate as recommended so that my fetch code look like so. Having printed to the UITextView like this, when I press load it spits out the following:

```<code><NSManagedObject: 0x1c7cf0>(entity: DatedText; id: 0x1420c0 <x - coredata://B52D4F88-0210-4AE2-9DA6-C05ED64FE389/DatedText/p12> ; data: <fault>)
</code>```

So either its not getting any data data because it hasn't been saved/loaded correctly or I am trying to get the loaded result into a UITextView the incorrect way. Any ideas?

```<code>NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:testEntity];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
    [fetch setPredicate:pred];

    NSError *fetchError = nil;
    NSArray *fetchedObjs = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
    if (fetchError != nil) {
        NSLog(@" fetchError=%@,details=%@",fetchError,fetchError.userInfo);
        return nil;
    }
    NSString *object = [NSString stringWithFormat:@"%@",[fetchedObjs objectAtIndex:0]];
    noteTextView.text = object;
</code>```

I have been having all sorts of problems working out how to use Core Data, so I have gone back to basics, new window based ipad project using core data.

I have added a view and some code which doesn't work, hehe. Im basically trying to save some text to a date, then when going back to that date, the text which was previously saved will be shown again.

答:
You're setting your NSFetchRequest's predicate to an NSArray, not an NSPredicate.

If you had posted the actual crash, it would probably say something like an unknown selector was sent to an instance of NSArray.

ContentLicense: CC BY-SA 2.5

Title: CoreData Basics Help

Body:
EDIT:
I have altered the NSPredicate as recommended so that my fetch code look like so. Having printed to the UITextView like this, when I press load it spits out the following:

<NSManagedObject: 0x1c7cf0>(entity: DatedText; id: 0x1420c0 <x - coredata://B52D4F88-0210-4AE2-9DA6-C05ED64FE389/DatedText/p12> ; data: <fault>)

So either its not getting any data data because it hasn't been saved/loaded correctly or I am trying to get the loaded result into a UITextView the incorrect way. Any ideas?

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:testEntity];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
    [fetch setPredicate:pred];

    NSError *fetchError = nil;
    NSArray *fetchedObjs = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
    if (fetchError != nil) {
        NSLog(@" fetchError=%@,details=%@",fetchError,fetchError.userInfo);
        return nil;
    }
    NSString *object = [NSString stringWithFormat:@"%@",[fetchedObjs objectAtIndex:0]];
    noteTextView.text = object;

I have been having all sorts of problems working out how to use Core Data, so I have gone back to basics, new window based ipad project using core data.

I have added a view and some code which doesn't work, hehe. Im basically trying to save some text to a date, then when going back to that date, the text which was previously saved will be shown again.


答:
I'd suggest using a LEFT JOIN.

First, we generate a cross product of assessments and users, which contains for each user, all assessments that are required for their role.

Then, a LEFT JOIN checks if these assessments were passed.

```<code>SELECT ...
FROM
    users u
    JOIN assessments a ON (a.RoleRequired = u.Role)
    LEFT JOIN assessment_logs al ON (
            al.AssessmentID = a.AssessmentID
        AND al.UserID = u.UserID
        AND al.Verdict='Pass'
    )

WHERE
        a.required
    AND al.UserID IS NULL
</code>```

Title: Selecting rows from 3 tables

Body:
I appreciate there are many tutorials and examples out there explaining JOIN concepts- however I am struggling to apply the examples to my specific scenario. I would appreciate some help, and if it isn't too much to ask- a break down of what is going on in the solution to achieve the desired results.

3 Tables: users, assessments, assessment_log.

users

+--------+------+------+-----------+----------+-----------+-------+--------+-----------+---------------+------+----------+
| UserID | User | Pass | FirstName | LastName | LastLogin | Email | Mobile | Kenitalla | AccountStatus | Role | Operator |
+--------+------+------+-----------+----------+-----------+-------+--------+-----------+---------------+------+----------+

assessments

+--------------+------+-----------+-----------+-----------+-----------+-----------+--------------+----------+---------+----------+
| AssessmentID | Name | Criteria1 | Criteria2 | Criteria3 | Criteria4 | Criteria5 | RoleRequired | Required | Renewal | Operator |
+--------------+------+-----------+-----------+-----------+-----------+-----------+--------------+----------+---------+----------+

assessment_logs

+-----------------+------+----------------+------------+--------+-----------+----------+----------+----------+----------+----------+----------+---------+---------------+---------+
| AssessmentLogID | Date | AssessmentName | AssessedBy | UserID | StaffName | Comments | Verdict1 | Verdict2 | Verdict3 | Verdict4 | Verdict5 | Verdict | RenewalPeriod | NextDue |
+-----------------+------+----------------+------------+--------+-----------+----------+----------+----------+----------+----------+----------+---------+---------------+---------+

When a user takes an assessment, an entry goes in to the assessment_log. Some assessments are required (true or false in Required column) where as some are optional. The RoleRequired column stipulates which user Role the assessment is required for.

I would like to generate a list of users and assessments they are yet to pass. The assessments must be required, and the required role must match the users role. An absense of an entry into the assessment_log with a "Pass" in the Verdict column indicates the assessment has not yet been passed.

In plain speak, I am looking for a query that will achieve the following result:

+------------------+-----------------+----------------+
| assessments.Name | users.FirstName | users.LastName |
+------------------+-----------------+----------------+

Where the assessment is required (Required equals true), the RequiredRole matches the users.Role column, and there is no entry in the assessments_log for the assessment where the Verdict column holds a "Pass" value.

Please let me know if further clarification is required.

Thanks in advance!

Body:
I'd suggest using a LEFT JOIN.

First, we generate a cross product of assessments and users, which contains for each user, all assessments that are required for their role.

Then, a LEFT JOIN checks if these assessments were passed.

SELECT ...
FROM
    users u
    JOIN assessments a ON (a.RoleRequired = u.Role)
    LEFT JOIN assessment_logs al ON (
            al.AssessmentID = a.AssessmentID
        AND al.UserID = u.UserID
        AND al.Verdict='Pass'
    )

WHERE
        a.required
    AND al.UserID IS NULL


问:
Null Pointer in Java function
I writed some search function and I got a null pointer exception when I try add element to temporary list.

User :

```<code>public class User {

    private Id _id;
    private String number;
    private String name;
    private String mark;
    private String model;
    private List < Address > addresses;

    public Id get_id() {
        return _id;
    }

    public void set_id(Id _id) {
        this._id = _id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String user) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public List < Address > getAddresses() {
        return addresses;
    }

    public void setAddresses(List < Address > addresses) {
        this.addresses = addresses;
    }
}
</code>```

Address :

```<code>public class Address {

    private String name;
    private Date dateFrom;
    private Date dateTo;

    public Date getDateTo() {
        return dateTo;
    }

    public void setDateTo(Date dateTo) {
        this.dateTo = dateTo;
    }

    public Date getDateFrom() {
        return dateFrom;
    }

    public void setDateFrom(Date dateFrom) {
        this.dateFrom = dateFrom;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

private List < User > findUsers(List < User > users, String park) {
    List < User > tempList = null;
    List < Address > addresses = null;
    for (User user: users) {
        addresses = user.getAddresses();
        for (Address address: addresses) {
            if (address.getName().equals(park))
                tempList.add(user);
        }
    }
    return tempList;
}
</code>```

In line where tempList.add(user); is I get NPE.

答:
Null pointer exceptions are called when you try to run a method on a variable that points to null.

In your example you have

```<code>List<User> tempList = null;
</code>```

then you never initialize it and later you use it as:

```<code>tempList.add(user);
</code>```

All you need to do is initialize it :)

```<code>List<User> tempList = new ArrayList<User>();
</code>```

So, in your example:

```<code>private List<User> findUsers (List <User> users, String park){
    List<User> tempList = new ArrayList<User>();
    List<Address> addresses = new ArrayList<Address>();
    for (User user : users) {
        addresses = user.getAddresses();
        for (Address address : addresses) {
            if (address.getName().equals(park))
                tempList.add(user);
        }
    }
    return tempList;
}
</code>```

Cheers!

Title: Null Pointer in Java function

Body:
I writed some search function and I got a null pointer exception when I try add element to temporary list.

User :

public class User {

    private Id _id;
    private String number;
    private String name;
    private String mark;
    private String model;
    private List < Address > addresses;

    public Id get_id() {
        return _id;
    }

    public void set_id(Id _id) {
        this._id = _id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String user) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public List < Address > getAddresses() {
        return addresses;
    }

    public void setAddresses(List < Address > addresses) {
        this.addresses = addresses;
    }
}

Address :

public class Address {

    private String name;
    private Date dateFrom;
    private Date dateTo;

    public Date getDateTo() {
        return dateTo;
    }

    public void setDateTo(Date dateTo) {
        this.dateTo = dateTo;
    }

    public Date getDateFrom() {
        return dateFrom;
    }

    public void setDateFrom(Date dateFrom) {
        this.dateFrom = dateFrom;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

private List < User > findUsers(List < User > users, String park) {
    List < User > tempList = null;
    List < Address > addresses = null;
    for (User user: users) {
        addresses = user.getAddresses();
        for (Address address: addresses) {
            if (address.getName().equals(park))
                tempList.add(user);
        }
    }
    return tempList;
}

In line where tempList.add(user); is I get NPE.

Body:
Null pointer exceptions are called when you try to run a method on a variable that points to null.

In your example you have

List<User> tempList = null;

then you never initialize it and later you use it as:

tempList.add(user);

All you need to do is initialize it :)

List<User> tempList = new ArrayList<User>();

So, in your example:

private List<User> findUsers (List <User> users, String park){
    List<User> tempList = new ArrayList<User>();
    List<Address> addresses = new ArrayList<Address>();
    for (User user : users) {
        addresses = user.getAddresses();
        for (Address address : addresses) {
            if (address.getName().equals(park))
                tempList.add(user);
        }
    }
    return tempList;
}

Cheers!


问:
How can you repair all tables in all databases from the MySQL command prompt when MYI file is corrupted or missing?
When dealing with MySQL database corruption, if the MYI index file is missing or if its header is corrupted you can't use a myisamchk command:

```<code>myisamchk --safe-recover --force --sort_buffer_size=2G --key_buffer_size=2G /var/lib/mysql/*/*.MYI
</code>```

You have to do the repair from the MySQL command prompt with the use_frm option:

```<code>repair tbl_name use_frm;
</code>```

Per MySQL documentation's on repairing tables

The USE_FRM option is available for use if the .MYI index file is missing or if its header is corrupted. This option tells MySQL not to trust the information in the .MYI file header and to re-create it using information from the .frm file. This kind of repair cannot be done with myisamchk.

With myisamchk, you can easily drop into each database folder and repair every table by using asterisks at the end of command:

```<code>/var/lib/mysql/*/*.MYI
</code>```

You can't do anything similar from the MySQL command prompt.

There's a StackOverflow question with an answer that explains how to repair all tables within one specific database from the MySQL command prompt with a procedure:

```<code>CREATE DEFINER = 'root'@'localhost'
PROCEDURE MYDATABASE.repair_all()
BEGIN
  DECLARE endloop INT DEFAULT 0;
  DECLARE tableName char(100);
  DECLARE rCursor CURSOR FOR SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA`=DATABASE();
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET endloop=1;

  OPEN rCursor;
  FETCH rCursor INTO tableName;

  WHILE endloop = 0 DO
    SET @sql = CONCAT("REPAIR TABLE `", tableName, "`");
    PREPARE statement FROM @sql;
    EXECUTE statement;

    FETCH rCursor INTO tableName;
  END WHILE;

  CLOSE rCursor;
END
</code>```

Is it possible to modify a procedure like this to loop through all your MySQL databases and repair every table within those databases?

I think this could be useful for anyone who has a large number of databases and runs into serious corruption.

答:
Here's my solution for when I had to fix all of the MyISAM files in my DB:

```<code>find ./ -name "*.MYI" -exec myisamchk -r {} \;
</code>```

It traverses all of the databases.

Body:
When dealing with MySQL database corruption, if the MYI index file is missing or if its header is corrupted you can't use a myisamchk command:

myisamchk --safe-recover --force --sort_buffer_size=2G --key_buffer_size=2G /var/lib/mysql/*/*.MYI

You have to do the repair from the MySQL command prompt with the use_frm option:

repair tbl_name use_frm;

Per MySQL documentation's on repairing tables

The USE_FRM option is available for use if the .MYI index file is missing or if its header is corrupted. This option tells MySQL not to trust the information in the .MYI file header and to re-create it using information from the .frm file. This kind of repair cannot be done with myisamchk.

With myisamchk, you can easily drop into each database folder and repair every table by using asterisks at the end of command:

/var/lib/mysql/*/*.MYI

You can't do anything similar from the MySQL command prompt.

There's a StackOverflow question with an answer that explains how to repair all tables within one specific database from the MySQL command prompt with a procedure:

CREATE DEFINER = 'root'@'localhost'
PROCEDURE MYDATABASE.repair_all()
BEGIN
  DECLARE endloop INT DEFAULT 0;
  DECLARE tableName char(100);
  DECLARE rCursor CURSOR FOR SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA`=DATABASE();
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET endloop=1;

  OPEN rCursor;
  FETCH rCursor INTO tableName;

  WHILE endloop = 0 DO
    SET @sql = CONCAT("REPAIR TABLE `", tableName, "`");
    PREPARE statement FROM @sql;
    EXECUTE statement;

    FETCH rCursor INTO tableName;
  END WHILE;

  CLOSE rCursor;
END

Is it possible to modify a procedure like this to loop through all your MySQL databases and repair every table within those databases?

I think this could be useful for anyone who has a large number of databases and runs into serious corruption.

Body:
Here's my solution for when I had to fix all of the MyISAM files in my DB:

find ./ -name "*.MYI" -exec myisamchk -r {} \;

It traverses all of the databases.


问:
Function doing integer comparison in C++
I am writing a variadic template function which compare multiple integer.
I would like to use it this way :

```<code>template<typename T, typename... Args>
bool multiple_comparison(T first, bool(* compar)(T&, T&), T second, Args... args){
    return compar(first, second) && multiple_comparison(second, args...);
}

int main(){
  multiple_comparison(1, <, 3); //should return true
  return 0;
}
</code>```

However, I have compilation issue:

```<code>  error: no matches converting function ‘operator<’ to type ‘bool (*)(int&, int&)’
</code>```

I guess it is because this is not this function that is used for primitive type.
I found the "std::less" (and the others operators) online, but it is C++14 and I am stuck with C++11.

Is there a way to do it ? Because, for the moment, the only thing I can think of is replacing every comparison operator by a custom function.

Thanks.

答:
The comparison functions in functional existed before C++14; they just changed slightly in that release. If you look here, you see that before C++14, they didn’t have a default value for T and you had to specify it yourself, but they still existed.

If those functions had not existed, you could have written lambdas which used the operators directly (like [](const T& lhs, const T& rhs) { return lhs < rhs; }).

Body:
I am writing a variadic template function which compare multiple integer.
I would like to use it this way :

template<typename T, typename... Args>
bool multiple_comparison(T first, bool(* compar)(T&, T&), T second, Args... args){
    return compar(first, second) && multiple_comparison(second, args...);
}

int main(){
  multiple_comparison(1, <, 3); //should return true
  return 0;
}

However, I have compilation issue:

  error: no matches converting function ‘operator<’ to type ‘bool (*)(int&, int&)’

I guess it is because this is not this function that is used for primitive type.
I found the "std::less" (and the others operators) online, but it is C++14 and I am stuck with C++11.

Is there a way to do it ? Because, for the moment, the only thing I can think of is replacing every comparison operator by a custom function.

Thanks.


问:
Dynamic Variable Properties
I'm generating a variable in a foreach loop that's name is dynamic and I need to set properties

```<code>$variableName = "res" + $i
New-Variable -Name $variableName -Value New-Object System.Windows.Forms.Label
</code>```

And then I need to add the properties, but just using

```<code>$variableName.text = "ipsum"
</code>```

Would set the property of $variableName and not the created variable.

答:
you can do it too</p>

```<code>$listLabel=@{}

for ($i = 1; $i -lt 99; $i++)
{
   $listLabel[$i]+=New-Object System.Windows.Forms.Label
   $listLabel[$i].Name="Res$i"
   $listLabel[$i].Text="Text for $i"
}
</code>```

Title: Dynamic Variable Properties

Body:
I'm generating a variable in a foreach loop that's name is dynamic and I need to set properties

$variableName = "res" + $i
New-Variable -Name $variableName -Value New-Object System.Windows.Forms.Label

And then I need to add the properties, but just using

$variableName.text = "ipsum"

Would set the property of $variableName and not the created variable.

Body:
you can do it too

$listLabel=@{}

for ($i = 1; $i -lt 99; $i++)
{
   $listLabel[$i]+=New-Object System.Windows.Forms.Label
   $listLabel[$i].Name="Res$i"
   $listLabel[$i].Text="Text for $i"
}


问:
Xamarin Prism Android won't lose TabbedPage or change NavigationPage
We have a project using a NavigationPage and TabbedPage working as expected in iOS but not Android (Xamarin Forms (2.3.3.193) with Prism (6.3.0)).

I've set up a sample project available here.

This application consists of three pages which are nested in a NavigationPage and a TabbedPage (APage, BPage and CPage) and a fourth page which should lose the TabbedPage and keep a NavigationPage (B1Page is available through BPage).

NavigationService.NavigateAsync("NavigationPage/LayoutTabbedPage/APage");

Opening APage with navigation and tab bar on iOS and looks fine on Android

BPage has an 'Add' button on the navigation bar which also looks fine on Android

Clicking 'Add' should open B1Page.  This still has the navigation bar (with a 'Save' button instead of 'Add') but no tab bar.

m_navigationService.NavigateAsync("NavigationPage/LayoutTabbedPage/BPage/B1Page");

But on Android B1Page the tab bar remains and as does the original navigation bar (with the Add button instead of Save).

Is there something wrong I'm doing with navigation which makes these inconsistent?

答:
Yes, you have issues with your navigation.  First off, if you want to navigate within a TabbedPage and keep your tabs, you need to wrap your Tab in a NavigationPage, not the TabbedPage in a NavigationPage.  Something like this:

<NavigationPage Title="B">
    <x:Arguments>
    <local:BPage />
    </x:Arguments>
</NavigationPage>

This will allow yo to navigate within the actual Tab.

If this is not what you want to do, then keep your tabbedPage wrapped in a navigation page and then when you navigate to B1Page force an async nav call using 'NavigateAsync("B1Page", usemodalNavigation: false)`. This will bounce you out of the tabbed page but keep you within the navigation page with the back arrow and toolbar item.

Secondly, your navigation Uri's are a mess.  Navigation in Prism is relative to where you are calling it.

When you make this call m_navigationService.NavigateAsync("NavigationPage/LayoutTabbedPage/BPage/B1Page"); you are pushing all those pages onto the navigation stack again.  If you hit your back button on Android you will see what I mean.

All you have to do is from BPageViewModel call NavigateAsync("B1Page");.

That should get you pointed in the right direction.


答:
you need to replace

this

```<code>    List<User> tempList = null;
 List<Address> addresses = null;
</code>```

with  this

```<code>List<User> tempList = new List<User>;

 List<Address> addresses = new ArrayList<Address>();
</code>```

Title: Null Pointer in Java function

Body:
you need to replace

this

    List<User> tempList = null;
 List<Address> addresses = null;

with  this

List<User> tempList = new List<User>;

 List<Address> addresses = new ArrayList<Address>();


问:
Knp Snappy Bundle Options
I'm using KnpSnappyBundle for my Symfony project and I'm trying to define some options in my config file. However if I set, for example:

```<code>knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    [ 'no-outline' ]
</code>```

I get an error:
The option '0' does not exist.

How do I define options for the bundle?

答:
The answer is:</p>

```<code>knp_snappy:
    pdf:
        enabled: true
        binary: /path/to/wkhtmltopdf
        options:
            - { name: 'page-size', value: 'A4' }
</code>```

Title: Knp Snappy Bundle Options

Body:
I'm using KnpSnappyBundle for my Symfony project and I'm trying to define some options in my config file. However if I set, for example:

knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    [ 'no-outline' ]

I get an error:
The option '0' does not exist.

How do I define options for the bundle?

Body:
The answer is:

knp_snappy:
    pdf:
        enabled: true
        binary: /path/to/wkhtmltopdf
        options:
            - { name: 'page-size', value: 'A4' }


问:
What do curly braces in the Windows registry mean?
I've been wondering this for a while and can't seem to get answer.

In Windows (maybe other places too), what do the curly braces mean? I'm guessing it has to do with hex but not sure.

Any help would be appreciated.

*UPDATE

I'm sorry I wasn't as specific as I should have been. I was talking about in the registry, but I've also seen it in folder paths.

答:
Depends on the usage.

In C# {0} is a placeholder; it gets replaced with the value that follows the quoted text, i.e.:

```<code>Console.WriteLine("Radius = {0}, PI = {1}", radius, PI);
</code>```

Note that the first place holder is always a 0, the next usage is 1, etc...

Body:
Depends on the usage.

In C# {0} is a placeholder; it gets replaced with the value that follows the quoted text, i.e.:

Console.WriteLine("Radius = {0}, PI = {1}", radius, PI);

Note that the first place holder is always a 0, the next usage is 1, etc...


问:
Sampling video and making image cutoffs in python
I've got a videostream (for now I just use a video). I need to get a one frame per every second or more seconds and I need to cut some part of these pictures based on 8 coordinates(leftupper x/y, rightupper x/y, rightlower x/y and leftlower x/y).

I thinkg that I'm able to do that cutting in java but I would rather do it in python as entire application is written in python / django.

It's possible to do both of that things directly in python?
Could you point me to some documentation or whatever?

答:
You can start with some Video Handling in Python Using OpenCV

Python : Reading Video File and Saving Video File using OpenCV

It contains all the basic links like Reading from File and Camera , that gives a initial idea of how to process Frames .

Then after you get Each Frame in OpenCV mat , you can form a Bounding Box Rect to extract the Region or ROI from that

Close to this Question
Cropping Live Video Feed

Cropping a Single Frame can be done as done in
Cropping a Single Image in OpenCV Python

This can be repeated for every Frame and you can even Write to a Video File taking reference from First Reference.


问:
ListBox.Items.Contains is not working
I am using ListBox.Items.Contains to check for duplicates but it does not seem to be working. It's two strings that I'm comparing. I have looked at the values when debugging and they appear to be exactly the same, so it should show me a messagebox to say a duplicate was found.

The item gets added to the myListBox every time, even if there is a duplicate, up to a maximum of 6 items.

Note that I am using a vendor SDK and therefore have had to change some of the code a bit but it is functionally identical. Code below. I have commented on any custom controls to explain what they are.

```<code>//Custom control - is not inherited from ListBox but it does contain a listbox. It implements IBasicEnquiryControl2 which has a property Control which will be the .Net ListBox.
Class.Namespace.Windows.eListBox lstdisplay = (Class.Namespace.Windows.eListBox)EnquiryForm.GetControl("ListBox1",EnquiryControlMissing.Exception);
ListBox myListBox = (ListBox)lstdisplay.Control;

//Returns an object from a custom class. ID property is used a bit further down, which is an int64 value
Class.Namespace.CR _cr = new Class.Namespace.CR.GetCR;

//Value key pair object item.
EnquiryListItem item;
item = new EnquiryListItem(_cr.ID,ComboBox1.SelectedText);

//Logic to check for duplicates.
if(myListBox.Items.Count < 6) {

    if (!myListBox.Items.Contains(ComboBox1.SelectedText.ToString())) {
        myListBox.BeginUpdate();
        myListBox.Items.Add(item);
        myListBox.EndUpdate();
    }
    else {
        System.Windows.Forms.MessageBox.Show("Duplicate found", "Duped", MessageBoxButtons.OK);
    }

}
</code>```

Edit: The other question did not help as it doesn't seem to apply to my situation. It appears I cannot use Linq with this control, nor can I use the for loop suggested. I get errors such as System.Windows.Forms.ListBox does not contain a definition for 'Add' or the same but with Any as the missing definition. System.Linq is referenced.

答:
You cannot compare them using contains since that's used to compare the objects themselves. You will need to compare the string values directly.

You can change

```<code>if (!myListBox.Items.Contains(ComboBox1.SelectedText.ToString())) {
</code>```

to

```<code>if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){
</code>```

To compare the string values

Title: ListBox.Items.Contains is not working

Body:
I am using ListBox.Items.Contains to check for duplicates but it does not seem to be working. It's two strings that I'm comparing. I have looked at the values when debugging and they appear to be exactly the same, so it should show me a messagebox to say a duplicate was found.

The item gets added to the myListBox every time, even if there is a duplicate, up to a maximum of 6 items.

Note that I am using a vendor SDK and therefore have had to change some of the code a bit but it is functionally identical. Code below. I have commented on any custom controls to explain what they are.

//Custom control - is not inherited from ListBox but it does contain a listbox. It implements IBasicEnquiryControl2 which has a property Control which will be the .Net ListBox.
Class.Namespace.Windows.eListBox lstdisplay = (Class.Namespace.Windows.eListBox)EnquiryForm.GetControl("ListBox1",EnquiryControlMissing.Exception);
ListBox myListBox = (ListBox)lstdisplay.Control;

//Returns an object from a custom class. ID property is used a bit further down, which is an int64 value
Class.Namespace.CR _cr = new Class.Namespace.CR.GetCR;

//Value key pair object item.
EnquiryListItem item;
item = new EnquiryListItem(_cr.ID,ComboBox1.SelectedText);

//Logic to check for duplicates.
if(myListBox.Items.Count < 6) {

    if (!myListBox.Items.Contains(ComboBox1.SelectedText.ToString())) {
        myListBox.BeginUpdate();
        myListBox.Items.Add(item);
        myListBox.EndUpdate();
    }
    else {
        System.Windows.Forms.MessageBox.Show("Duplicate found", "Duped", MessageBoxButtons.OK);
    }

}

Edit: The other question did not help as it doesn't seem to apply to my situation. It appears I cannot use Linq with this control, nor can I use the for loop suggested. I get errors such as System.Windows.Forms.ListBox does not contain a definition for 'Add' or the same but with Any as the missing definition. System.Linq is referenced.

Body:
You cannot compare them using contains since that's used to compare the objects themselves. You will need to compare the string values directly.

You can change

if (!myListBox.Items.Contains(ComboBox1.SelectedText.ToString())) {

to

if (!myListBox.Items.Cast<String>().Any(item => item == ComboBox1.SelectedText.ToString())){

To compare the string values


问:
How to iterate over two dataframe columns and add values from a list based on the values in those two columns
I have a dataframe with three columns like this:

Subject{1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, ...} datetime{6/4/16 3:04:30, 6/5/16 6:02:15, ...} markers{}

It is sorted by subject then by datetime, and the markers column is empty

I also have a dictionary which maps subject numbers to lists of datetimes. These datetimes are not exactly the same as the ones already in the dataframe. I want to add all these datetimes to the markers column in their corresponding subject and date row for comparison purposes, so a dictionary with the key (subject) 1 with a list of values like {6/4/16 5:00:15, 6/5/16 6:10:30} would have its first value added to row 1 because the subject and date match and its second value added to row 2 for the same reason.

I thought of looping through each dictionary key and all it's corresponding datetimes, but then finding the corresponding row in the map for each datetime within the nested loops would be very inefficient. It would be something like this:

```<code>for subject in df.iloc[:, 0]:
    # go to subject in dictionary and loop through datetimes in corresponding list,
    # adding the matching datetime to the current row
    # O(n^2) time!
</code>```

Is there a more efficient way to do this?

Thanks!

答:
try this, you will have to customize the answer somewhat to meet your specific needs, but the logic is basically the same.</p>

```<code>df = pd.DataFrame({'colA': [100,200],'colB': ['NaN','NaN']})
dict1 = {100: ['rat','cat','hat'], 200: ['hen','men','den']}
df = pd.concat([df['colA'],df['colA'].map(dict1).apply(pd.Series)], axis = 1)
</code>```

Body:
I have a dataframe with three columns like this:

Subject{1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, ...} datetime{6/4/16 3:04:30, 6/5/16 6:02:15, ...} markers{}

It is sorted by subject then by datetime, and the markers column is empty

I also have a dictionary which maps subject numbers to lists of datetimes. These datetimes are not exactly the same as the ones already in the dataframe. I want to add all these datetimes to the markers column in their corresponding subject and date row for comparison purposes, so a dictionary with the key (subject) 1 with a list of values like {6/4/16 5:00:15, 6/5/16 6:10:30} would have its first value added to row 1 because the subject and date match and its second value added to row 2 for the same reason.

I thought of looping through each dictionary key and all it's corresponding datetimes, but then finding the corresponding row in the map for each datetime within the nested loops would be very inefficient. It would be something like this:

for subject in df.iloc[:, 0]:
    # go to subject in dictionary and loop through datetimes in corresponding list,
    # adding the matching datetime to the current row
    # O(n^2) time!

Is there a more efficient way to do this?

Thanks!

Body:
try this, you will have to customize the answer somewhat to meet your specific needs, but the logic is basically the same.

df = pd.DataFrame({'colA': [100,200],'colB': ['NaN','NaN']})
dict1 = {100: ['rat','cat','hat'], 200: ['hen','men','den']}
df = pd.concat([df['colA'],df['colA'].map(dict1).apply(pd.Series)], axis = 1)


问:
Create zip style file without compression
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them to decompress.

Anyone know how this could be approached, or if there are some libraries out there that do this that i am not aware of?

答:
Have a look at System.IO.Packaging namespace.

Quote from MSDN:

System.IO.Packaging

Provides classes that support storage
  of multiple data objects in a single
  container.

Package is an abstract class that can
  be used to organize objects into a
  single entity of a defined physical
  format for portability and efficient
  access.

A ZIP file is the primary physical
  format for the Package. Other Package
  implementations might use other
  physical formats such as an XML
  document, a database, or Web service.

You can select different compression options for your package:

NotCompressed - Compression is turned off.

Normal - Compression is optimized for a balance between size and
performance.

Maximum - Compression is optimized for
size.

Fast - Compression is optimized for
performance.

SuperFast - Compression is optimized for high performance.

OwnerDisplayName: Jason Miesionczek

OwnerDisplayName: aku

LastEditorDisplayName: aku


问:
How to align input forms in HTML
I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

```<code><form>
 First Name:<input type="text" name="first"><br />
 Last Name:<input type="text" name="last"><br />
 Email:<input type="text" name="email"><br />
</form>
</code>```

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

答:
The traditional method is to use a table.

However, many would argue that tables are restricting and prefer CSS.  The benefit of using CSS is that you could use various elements. From divs, ordered and un-ordered list, you could accomplish the same layout.

In the end, you'll want to use what you're most comfortable with.

Hint: Tables are easy to get started with.

Example:

        First Name:

        <input type="text" name="first">

        Last Name:

        <input type="text" name="last">

```

Title: How to align input forms in HTML

Body:
I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

<form>
 First Name:<input type="text" name="first">

 Last Name:<input type="text" name="last">

 Email:<input type="text" name="email">

</form>

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

Body:
The traditional method is to use a table.

However, many would argue that tables are restricting and prefer CSS.  The benefit of using CSS is that you could use various elements. From divs, ordered and un-ordered list, you could accomplish the same layout.

In the end, you'll want to use what you're most comfortable with.

Hint: Tables are easy to get started with.

Example:

<table>
  <tbody>
    <tr>
      <td>
        First Name:
      </td>
      <td>
        <input type="text" name="first">
      </td>
    </tr>
    <tr>
      <td>
        Last Name:
      </td>
      <td>
        <input type="text" name="last">
      </td>
    </tr>
  </tbody>
</table>


答:
This is your issue:

```<code>List<User> tempList = null;
List<Address> addresses = null;
</code>```

Your list are null you are never initialize them.
Add something like this:

```<code>List<User> tempList = new ArrayList();
List<Address> addresses = new ArrayList();
</code>```

Title: Null Pointer in Java function

Body:
I writed some search function and I got a null pointer exception when I try add element to temporary list.

User :

public class User {

    private Id _id;
    private String number;
    private String name;
    private String mark;
    private String model;
    private List < Address > addresses;

    public Id get_id() {
        return _id;
    }

    public void set_id(Id _id) {
        this._id = _id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String user) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    public List < Address > getAddresses() {
        return addresses;
    }

    public void setAddresses(List < Address > addresses) {
        this.addresses = addresses;
    }
}

Address :

public class Address {

    private String name;
    private Date dateFrom;
    private Date dateTo;

    public Date getDateTo() {
        return dateTo;
    }

    public void setDateTo(Date dateTo) {
        this.dateTo = dateTo;
    }

    public Date getDateFrom() {
        return dateFrom;
    }

    public void setDateFrom(Date dateFrom) {
        this.dateFrom = dateFrom;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

private List < User > findUsers(List < User > users, String park) {
    List < User > tempList = null;
    List < Address > addresses = null;
    for (User user: users) {
        addresses = user.getAddresses();
        for (Address address: addresses) {
            if (address.getName().equals(park))
                tempList.add(user);
        }
    }
    return tempList;
}

In line where tempList.add(user); is I get NPE.

Body:
This is your issue:

List<User> tempList = null;
List<Address> addresses = null;

Your list are null you are never initialize them.
Add something like this:

List<User> tempList = new ArrayList();
List<Address> addresses = new ArrayList();


问:
sort graph edges in increasing order
I am representing graphs using the standard adjacency list representation where each node is going out as an linked list. You can read more about adjacency list here.

Lets say below is my graph:

```<code>         10
    0--------1
    |  \     |
   6|   5\   |15
    |      \ |
    2--------3
        4
</code>```

Adjacency list would look like as :

```<code>[0,  1,  2,  3]
 |   |   |   |
 10  10  6   6
 |   |   |   |
[1] [0] [0] [2]
 |   |   |   |
 6   15  4   5
 |   |   |   |
[2] [3] [3] [0]
 |   |   |   |
 |   |   |   15
    NULL     |
            [1]
             |
             |
            NULL
</code>```

Since the graph is undirected, edges should be added from source to destination and from destination to source as well along with the weight of the edges. This is how code representation would looks like in that case.

```<code>// Linked list representation
class Adj_Node {
  public:
    int data;
    int weight;
    Adj_Node* next;
};

// Adjacency list representation
class Adj_List {
  public:
    Adj_Node* head;
};

// Graph representation
class Graph {
  public:
    int vertices;
    Adj_List* source;
    Graph(int v) {
      vertices = v;
      source = new Adj_List[vertices];

      for (int i = 0; i < vertices; ++i) {
        source[i].head = NULL;
      }
    }
    void addEdge(int, int, int);
    void printGraph();
};

// Creates an linked list node
Adj_Node* createNode(int d) {
  Adj_Node* tmp = new Adj_Node;
  tmp->data   = d;
  tmp->weight = 0;
  tmp->next   = NULL;

  return tmp;
}

// Adds edge to both src and destination
void Graph::addEdge(int src, int dest, int weight) {
  Adj_Node* node = createNode(dest);
  node->next = source[src].head;
  source[src].head = node;
  node->weight = weight;

  node = createNode(src);
  node->next = source[dest].head;
  source[dest].head = node;
  node->weight = weight;
}

void Graph::printGraph() {
  for(int i = 0; i < vertices; ++i) {
  Adj_Node* n = source[i].head;
  std::cout << i << " = ";
  while(n != NULL) {
    std::cout << n->data << " " << n->weight << ", ";
    n = n->next;
  }
  std::cout << std::endl;
}
</code>```

So, having said all of the above, I have above depiction linked list representation with me where each weighted edge of the graph is depicted as an node in an linked list.
Question is : What are the ways you will suggest to get the edges in increasing order?

答:
Well. What I implemented is something like this :

When I add an node in the linked list, add it in sorted way such that linked list remains sorted by weight. So, final graph depiction would look like as :

```<code>[0,  1,  2,  3]
 |   |   |   |
 6   10  4   5
 |   |   |   |
[2] [0] [3] [0]
 |   |   |   |
10   15  6   6
 |   |   |   |
[1] [3] [0] [2]
 |   |   |   |
 |   |   |   15
    NULL     |
            [1]
             |
             |
            NULL
</code>```

And then write an iterator which go over all the linked lists and put values into the vector. vector template would be :

```<code>// First int is weight, second is source, third is destination of the node.
std::vector < std::pair <int, std::pair<int, int> > >::iterator it = vv.begin();
</code>```

:) Work with vectors in case you need to.

Title: sort graph edges in increasing order

Body:
I am representing graphs using the standard adjacency list representation where each node is going out as an linked list. You can read more about adjacency list here.

Lets say below is my graph:

         10
    0--------1
    |  \     |
   6|   5\   |15
    |      \ |
    2--------3
        4

Adjacency list would look like as :

[0,  1,  2,  3]
 |   |   |   |
 10  10  6   6
 |   |   |   |
[1] [0] [0] [2]
 |   |   |   |
 6   15  4   5
 |   |   |   |
[2] [3] [3] [0]
 |   |   |   |
 |   |   |   15
    NULL     |
            [1]
             |
             |
            NULL

Since the graph is undirected, edges should be added from source to destination and from destination to source as well along with the weight of the edges. This is how code representation would looks like in that case.

// Linked list representation
class Adj_Node {
  public:
    int data;
    int weight;
    Adj_Node* next;
};

// Adjacency list representation
class Adj_List {
  public:
    Adj_Node* head;
};

// Graph representation
class Graph {
  public:
    int vertices;
    Adj_List* source;
    Graph(int v) {
      vertices = v;
      source = new Adj_List[vertices];

      for (int i = 0; i < vertices; ++i) {
        source[i].head = NULL;
      }
    }
    void addEdge(int, int, int);
    void printGraph();
};

// Creates an linked list node
Adj_Node* createNode(int d) {
  Adj_Node* tmp = new Adj_Node;
  tmp->data   = d;
  tmp->weight = 0;
  tmp->next   = NULL;

  return tmp;
}

// Adds edge to both src and destination
void Graph::addEdge(int src, int dest, int weight) {
  Adj_Node* node = createNode(dest);
  node->next = source[src].head;
  source[src].head = node;
  node->weight = weight;

  node = createNode(src);
  node->next = source[dest].head;
  source[dest].head = node;
  node->weight = weight;
}

void Graph::printGraph() {
  for(int i = 0; i < vertices; ++i) {
  Adj_Node* n = source[i].head;
  std::cout << i << " = ";
  while(n != NULL) {
    std::cout << n->data << " " << n->weight << ", ";
    n = n->next;
  }
  std::cout << std::endl;
}

So, having said all of the above, I have above depiction linked list representation with me where each weighted edge of the graph is depicted as an node in an linked list.
Question is : What are the ways you will suggest to get the edges in increasing order?

Body:
Well. What I implemented is something like this :

When I add an node in the linked list, add it in sorted way such that linked list remains sorted by weight. So, final graph depiction would look like as :

[0,  1,  2,  3]
 |   |   |   |
 6   10  4   5
 |   |   |   |
[2] [0] [3] [0]
 |   |   |   |
10   15  6   6
 |   |   |   |
[1] [3] [0] [2]
 |   |   |   |
 |   |   |   15
    NULL     |
            [1]
             |
             |
            NULL

And then write an iterator which go over all the linked lists and put values into the vector. vector template would be :

// First int is weight, second is source, third is destination of the node.
std::vector < std::pair <int, std::pair<int, int> > >::iterator it = vv.begin();

:) Work with vectors in case you need to.


问:
Opening new activities with different combination of check boxes checked?
I want to make an app which has checkboxes, so what i basically want to do is that if certain checkboxes are check i want to open a certain activity. For ex; there is a question whats your gender the checkboxes available are male and female the other question is what do eat the check boxes available are pizza and burger so if male and pizza are chosen i want to open a certain activity, i want to open different activities with different combinations.how should i do this?   </p>

答:
Just check if your CheckBox isChecked(). It will return boolean value. Then you can set your logic and call Intent accordingly. You can do as below:

```<code>if(cbMale.isChecked() && cbPizza.isChecked){
   Intent i = new Intent(YourCurrentActivity.this, YourNextActivity.class)
   startActivity(i);
}
</code>```

Do as above for rest of the conditions. Hope this helps.

Body:
Just check if your CheckBox isChecked(). It will return boolean value. Then you can set your logic and call Intent accordingly. You can do as below:

if(cbMale.isChecked() && cbPizza.isChecked){
   Intent i = new Intent(YourCurrentActivity.this, YourNextActivity.class)
   startActivity(i);
}

Do as above for rest of the conditions. Hope this helps.


问:
JS script - Value Dependent (multiple dropdown)
Right now I have two dropdowns and the goal is to have the User select "OFF" on the first option, the second dropdown automatically selects "ON" and vice versa.

The code currently below with the JavaScript works, but works for only one pair of the dropdown. I was wondering what I need to change to make it work for both pairs or even four pairs in the future.

Code:

<!DOCTYPE html>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

   </form>

```

答:
Here is your solution

<!DOCTYPE html>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

   </form>

```

Body:
Here is your solution

<!DOCTYPE html>
<html>
<body>
    <div class="cmicrophone" id="cmicrophone">Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>
    </div>
    <div class="microphone" id="microphone">Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>
    </div>

    <br>

    <div class="cmicrophone" id="cmicrophone">Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>
    </div>
    <div class="microphone" id="microphone">Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>
    </div>
   </form>
  </div>
    <script>
var cmicrophone = document.querySelectorAll('.select1');
var microphone = document.querySelectorAll('.select2');

function inputHandlerCmicrophone(thisSelect, otherSelect, j) {

    var test = document.querySelectorAll('.select1');
    for(i=0; i<test.length; i++){
        if(test[i] == j){
            otherSelect[i].selectedIndex =thisSelect[i].selectedIndex
            break;
}
}

        }
   function inputHandlerMicrophone(thisSelect, otherSelect, j) {

    var test = document.querySelectorAll('.select2');
    for(i=0; i<test.length; i++){
        if(test[i] == j){
            otherSelect[i].selectedIndex =thisSelect[i].selectedIndex
            break;
}

        }}
        for(i=0; i<cmicrophone.length; i++) {
            cmicrophone[i].addEventListener('change', function (e) {
    inputHandlerCmicrophone(cmicrophone, microphone, e.target);
  });
}

        for(k=0; k<microphone.length; k++) {
            microphone[k].addEventListener('change', function (e) {
    inputHandlerMicrophone(microphone, cmicrophone, e.target);
  });
}

</script>
</body>
</html>


问:
rows in Bootstrap grid don't line up
Just trying to make a second row of col-md-6s (I copied the "row" div and pasted it within the container div) but I can't seem to figure out why its not perfectly lined up.

The last two lines of HTML code reflect the beginning of the second row.

.btn-group-vertical{
  border: 2px solid black;
  border-radius: 10px;
}
.col-md-6 {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
#prod_view {
  height: 100%;
  background-color: lightcoral;
  display: flex;
  justify-content: flex-start;
  border: solid;
  border-radius: 10px;
}
.col-md-6 > div:last-child {
  width: 50%;
}
.boxclass {
  height: 95%;
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">

    <div class="col-md-6" style="background-color: lightcyan">
      <div class="btn-group-vertical btn-group-lg">
        <button type="button" class="btn btn-primary">Quick Select</button>
        <button type="button" class="btn btn-primary">Show in Depth</button>
        <button type="button" class="btn btn-primary">Delete Product</button>
      </div>
    <div>

    <div id="prod_view">
      <div class="boxclass" >
        <img alt="product" class="img-rounded" src="../Images/math.jpg" style="max-height: 100%; max-width: 100%;">
      </div>
      <div class="boxclass">some cool blocks all stacked up n shtufff</div>
    </div>

  </div>
</div>

<div class="col-md-6" style="background-color: lightgray">
  <div class="btn-group-vertical btn-group-lg">
    <button type="button" class="btn btn-primary">Quick Select</button>
    <button type="button" class="btn btn-primary">Show in Depth</button>
    <button type="button" class="btn btn-primary">Delete Product</button>
  </div>
<div>

<div id="prod_view">
  <div class="boxclass"></div>
  <div class="boxclass"></div>
</div>
</div>
</div>

<div class="row">

<div class="col-md-6" style="background-color: lightcyan"></code>```

答:
Works fine when the .row is closed properly...

http://www.codeply.com/go/OCsEsFb2Lr

```<code><div class="container">
    <div class="row">
        <div class="col-md-6" style="background-color: lightcyan">

        </div>
        <div class="col-md-6" style="background-color: lightgray">

        </div>
    </div>
    <div class="row">
        <div class="col-md-6" style="background-color: lightcyan">

        </div>
        <div class="col-md-6" style="background-color: lightgray">

        </div>
    </div>
</div>
</code>```

Title: rows in Bootstrap grid don't line up

Body:
Just trying to make a second row of col-md-6s (I copied the "row" div and pasted it within the container div) but I can't seem to figure out why its not perfectly lined up.

The last two lines of HTML code reflect the beginning of the second row.

.btn-group-vertical{
  border: 2px solid black;
  border-radius: 10px;
}
.col-md-6 {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
#prod_view {
  height: 100%;
  background-color: lightcoral;
  display: flex;
  justify-content: flex-start;
  border: solid;
  border-radius: 10px;
}
.col-md-6 > div:last-child {
  width: 50%;
}
.boxclass {
  height: 95%;
  width: 50%;
}

        <button type="button" class="btn btn-primary">Quick Select</button>
        <button type="button" class="btn btn-primary">Show in Depth</button>
        <button type="button" class="btn btn-primary">Delete Product</button>

some cool blocks all stacked up n shtufff

    <button type="button" class="btn btn-primary">Quick Select</button>
    <button type="button" class="btn btn-primary">Show in Depth</button>
    <button type="button" class="btn btn-primary">Delete Product</button>

Body:
Works fine when the .row is closed properly...

http://www.codeply.com/go/OCsEsFb2Lr

<div class="container">
    <div class="row">
        <div class="col-md-6" style="background-color: lightcyan">

        </div>
        <div class="col-md-6" style="background-color: lightgray">

        </div>
    </div>
    <div class="row">
        <div class="col-md-6" style="background-color: lightcyan">

        </div>
        <div class="col-md-6" style="background-color: lightgray">

        </div>
    </div>
</div>


答:
You get null on the code

```<code>tempList.add(user);
</code>```

because you haven't created an object tempList;

Instead of List<User> tempList = null;

List is an interface thus you cannot call its constructor.

You need to use the class that implements List such as ArrayList

you need to write List<User> tempList = new ArrayList<User>();

Title: Null Pointer in Java function

Body:
You get null on the code

tempList.add(user);

because you haven't created an object tempList;

Instead of List<User> tempList = null;

List is an interface thus you cannot call its constructor.

You need to use the class that implements List such as ArrayList

you need to write List<User> tempList = new ArrayList<User>();


问:
Uploading files with PhoneGap + iPhone
I understand that PhoneGap applications are largely (if not entirely) HTML5 + CSS + JavaScript. Natively, the iPhone doesn't provide controls to upload files.

Does PhoneGap provide any mechanisms that allow users to upload files? (images / video, in the case of the iPhone)

I know Titanium allows users to do this, but it's a different animal with its compiled Javascript and proprietary APIs. Thanks for your advice/input.

答:
I believe you might be able to read the files using the PhoneGap API and the upload them using and AJAX post if  the server application supported it.

The other option is to write a custom module/Plugin in PhoneGap that could specific to your needs.

Here are some Example Plugins

Title: Uploading files with PhoneGap + iPhone


答:
Whatever you want to achieve, this is not the way we do it in C++.
This is more idiomatic, (and works in any C++ pre C++11).

```<code>#include<functional>  //for std::less
template<typename T, class Comparison>
bool multiple_comparison(T first, Comparison comp, T second){
    return comp(first, second);
}

int main(){
  multiple_comparison(1, std::less<int>(), 3); //should return true
}
</code>```

I removed the variadic argument part because that was not part of the question and the recursion was wrong.

EDIT: From the comments I deduce that this is what you want.

Even mathematicians will agree that want you want to implement is a
  dangerous abuse of notation (for example if you drop a std::greater
  in the middle of the sequence everyone will be confused)

Here it is anyway:

```<code>#include<utility> //for std::forward
template<typename T>
constexpr bool multiple_comparison(T const& second){return true;}

template<typename T, class Compare, class... Rest>
bool multiple_comparison(T const& first, Compare comp, T const& second, Rest&&... rest){
    return comp(first, second) and multiple_comparison(second, std::forward<Rest>(rest)...);
}

#include<functional>  //for std::less and equal
#include<cassert>
int main(){
  // is    1 < 3 == 3 < 5 ?
  assert( multiple_comparison(1, std::less<int>(), 3, std::equal_to<int>(), 3, std::less<int>(), 5) );
  // is    1 < 3 == 4 < 5 ?
  assert( not multiple_comparison(1, std::less<int>(), 3, std::equal_to<int>(), 4, std::less<int>(), 5) );

// bonus for C++11, explicit type omitted
  assert( multiple_comparison(1, std::less<>(), 3, std::equal_to<>(), 3, std::less<>(), 5) );
  assert( not multiple_comparison(1, std::less<>(), 3, std::equal_to<>(), 4, std::less<>(), 5) );

}
</code>```

Title: Function doing integer comparison in C++

Body:
I am writing a variadic template function which compare multiple integer.
I would like to use it this way :

template<typename T, typename... Args>
bool multiple_comparison(T first, bool(* compar)(T&, T&), T second, Args... args){
    return compar(first, second) && multiple_comparison(second, args...);
}

int main(){
  multiple_comparison(1, <, 3); //should return true
  return 0;
}

However, I have compilation issue:

  error: no matches converting function ‘operator<’ to type ‘bool (*)(int&, int&)’

I guess it is because this is not this function that is used for primitive type.
I found the "std::less" (and the others operators) online, but it is C++14 and I am stuck with C++11.

Is there a way to do it ? Because, for the moment, the only thing I can think of is replacing every comparison operator by a custom function.

Thanks.

Body:
Whatever you want to achieve, this is not the way we do it in C++.
This is more idiomatic, (and works in any C++ pre C++11).

#include<functional>  //for std::less
template<typename T, class Comparison>
bool multiple_comparison(T first, Comparison comp, T second){
    return comp(first, second);
}

int main(){
  multiple_comparison(1, std::less<int>(), 3); //should return true
}

I removed the variadic argument part because that was not part of the question and the recursion was wrong.

EDIT: From the comments I deduce that this is what you want.

Even mathematicians will agree that want you want to implement is a
  dangerous abuse of notation (for example if you drop a std::greater
  in the middle of the sequence everyone will be confused)

Here it is anyway:

#include<utility> //for std::forward
template<typename T>
constexpr bool multiple_comparison(T const& second){return true;}

template<typename T, class Compare, class... Rest>
bool multiple_comparison(T const& first, Compare comp, T const& second, Rest&&... rest){
    return comp(first, second) and multiple_comparison(second, std::forward<Rest>(rest)...);
}

#include<functional>  //for std::less and equal
#include<cassert>
int main(){
  // is    1 < 3 == 3 < 5 ?
  assert( multiple_comparison(1, std::less<int>(), 3, std::equal_to<int>(), 3, std::less<int>(), 5) );
  // is    1 < 3 == 4 < 5 ?
  assert( not multiple_comparison(1, std::less<int>(), 3, std::equal_to<int>(), 4, std::less<int>(), 5) );

// bonus for C++11, explicit type omitted
  assert( multiple_comparison(1, std::less<>(), 3, std::equal_to<>(), 3, std::less<>(), 5) );
  assert( not multiple_comparison(1, std::less<>(), 3, std::equal_to<>(), 4, std::less<>(), 5) );

}


问:
How to detect how many active Unicorn workers are busy?
I am using Ruby unicorn, and have configured it to have 15 worker processes.

How do I tell how many workers are actually processing work (are not idle, waiting for work) at any current time?

答: You can use Raindrops or New Relic' RPM.</p>


问:
Difference between "//" and "/" in XPath?
I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

This expression

```<code>//webengagedata//preceding-sibling::*
</code>```

returned 14 results

And this expression

```<code>//webengagedata/preceding-sibling::*
</code>```

returned 9 results

What does the "//" do to match 5 more results?

答:
The difference is that x//y is shorthand for x/descendant-or-self::node()/y.

That's all.

So while the first query selects all the descendants of <webengagedata> that have another tag after them, the second only selects the preceding siblings of the tag itself.

The rules of abbreviated xpath syntax are explained here.

Body:
I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

This expression

//webengagedata//preceding-sibling::*

returned 14 results

And this expression

//webengagedata/preceding-sibling::*

returned 9 results

What does the "//" do to match 5 more results?


问:
How can I clear a specific filter without clearing all filters?
Background:

I am creating an app that stores record of trainings that employees in a company took in table. I want to filter the rows of the table based on training name and/or employee name. I was able to figure out this first part, and I was able to create a button that clears all the filters and reloads the entire table using the clearFilters() function.

Problem:

I want to create two buttons that clear the filter selections one ("All Trainings") for the training name and one ("All Employees") for the employee name. To be more clear, when I click on the "All Trainings" button, I want to clear the filters on the training name, but not on the Employee name. This will become useful once I have a table with multiple fields that I want to filter, and I want to navigate the table without having to reset all fields every time.

I tried searching the functions available on Google App Maker, but there was nothing that seemed to be able to solve my problem. Any suggestions?

答:
I am sure there is a better way to do this, so you may want to wait for someone smarter to chime in, but I BELIEVE you can just have your button clear the filters, but reapply a new filter.

So for my situation I have the table do a filter for items that are listed as "Complete", so those are hidden when the user opens the page.

Then, when the users filter another field and want to clear out that search I didn't want the "Complete" items to reappear (which is what happened when I just used the clearFilters() function. So my workaround was to make the clear button actually clear the filter, but apply the original "Complete" filter.

So for my OnClick action, for my "Clear Button" I have:

```<code>widget.datasource.query.clearFilters();
widget.datasource.load();
app.closeDialog();
var datasource = app.datasources.TestModel;
 datasource.query.filters.Status._notContains = 'Complete';
 datasource.load();
</code>```

The

```<code>widget.datasource.load();
    app.closeDialog();
</code>```

May be redundant/unnecessary.

Body:
I am sure there is a better way to do this, so you may want to wait for someone smarter to chime in, but I BELIEVE you can just have your button clear the filters, but reapply a new filter.

So for my situation I have the table do a filter for items that are listed as "Complete", so those are hidden when the user opens the page.

Then, when the users filter another field and want to clear out that search I didn't want the "Complete" items to reappear (which is what happened when I just used the clearFilters() function. So my workaround was to make the clear button actually clear the filter, but apply the original "Complete" filter.

So for my OnClick action, for my "Clear Button" I have:

widget.datasource.query.clearFilters();
widget.datasource.load();
app.closeDialog();
var datasource = app.datasources.TestModel;
 datasource.query.filters.Status._notContains = 'Complete';
 datasource.load();

The

widget.datasource.load();
    app.closeDialog();

May be redundant/unnecessary.


问:
sending php excel as attachment using php mail
I have the following:

```<code>$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
$xlsData1= "data:application/vnd.ms-excel;base64,".base64_encode($xlsData);
ob_end_clean();

        //Require for mailing functionality
        require_once('../../PHPMailer/PHPMailer-master/class.phpmailer.php');

        //Send mail function
        $mail= new PHPMailer(); // defaults to using php "mail()"
        $sender ="emailadddress";
        $mail->SetFrom($sender);
        $mail->AddAddress('emailaddress');
        $mail->Subject="Combined repair and production report from ".$reportDate;
        $encoding = "base64";
        //$type = "image/png";
        $mail->AddStringAttachment(base64_decode($xlsData1), "combined_report".$reportDate."xlsx");
        //$mail->AddAttachment($xlsData, $filename);
        $message= "Please see attached combined report";
        $message = "</body></html>";
        $mail->MsgHTML($message);

        if(!$mail->Send())
        {
            $response =  array(
                'op' => 'failed',
                'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
            );
        }
        else
        {
            $response =  array(
                'op' => 'ok',
                'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
            );

        }

die(json_encode($response));
pg_close($conn);
</code>```

this sends an email with an attachemnt but the attachment is a blank file. When I try to save it it has the filename and the extension like this: "filenamexlsx" so it looks like it is not getting the correct xlsx format. I have tried this too:

```<code>$mail->AddStringAttachment("data:application/vnd.ms-excel;base64,".base64_encode($xlsData);
</code>```

I have also tried:

```<code>    $encoding = "base64";
    $type = "application/vnd.ms-excel"; // and :application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    $mail->AddStringAttachment(base64_decode($xlsData1), "combined_report".$reportDate."xlsx",$encoding,$type);
</code>```

I also tried using the AddAttachment() instead of the string attachment and there is no attachment on the email when I do that.

I have followed :
 php send e-mail with attachment

and have also looked at multiple things out there like PHPMailer, AddStringAttachment and Data URI Scheme

but it doesnt appear to be working :( any help will be appreciated!

答: I think there is mistake in your file name. Your file name should be filename.xlsx not this filenamexlsx

Body:
I have the following:

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
$xlsData1= "data:application/vnd.ms-excel;base64,".base64_encode($xlsData);
ob_end_clean();

        //Require for mailing functionality
        require_once('../../PHPMailer/PHPMailer-master/class.phpmailer.php');

        //Send mail function
        $mail= new PHPMailer(); // defaults to using php "mail()"
        $sender ="emailadddress";
        $mail->SetFrom($sender);
        $mail->AddAddress('emailaddress');
        $mail->Subject="Combined repair and production report from ".$reportDate;
        $encoding = "base64";
        //$type = "image/png";
        $mail->AddStringAttachment(base64_decode($xlsData1), "combined_report".$reportDate."xlsx");
        //$mail->AddAttachment($xlsData, $filename);
        $message= "Please see attached combined report";
        $message = "";
        $mail->MsgHTML($message);

        if(!$mail->Send())
        {
            $response =  array(
                'op' => 'failed',
                'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
            );
        }
        else
        {
            $response =  array(
                'op' => 'ok',
                'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
            );

        }

die(json_encode($response));
pg_close($conn);

this sends an email with an attachemnt but the attachment is a blank file. When I try to save it it has the filename and the extension like this: "filenamexlsx" so it looks like it is not getting the correct xlsx format. I have tried this too:

$mail->AddStringAttachment("data:application/vnd.ms-excel;base64,".base64_encode($xlsData);

I have also tried:

    $encoding = "base64";
    $type = "application/vnd.ms-excel"; // and :application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    $mail->AddStringAttachment(base64_decode($xlsData1), "combined_report".$reportDate."xlsx",$encoding,$type);

I also tried using the AddAttachment() instead of the string attachment and there is no attachment on the email when I do that.

I have followed :
 php send e-mail with attachment

and have also looked at multiple things out there like PHPMailer, AddStringAttachment and Data URI Scheme

but it doesnt appear to be working :( any help will be appreciated!


答:
It looks like you are adding EnquiryListItem to your Listbox.Items, not strings. When you ask your ListBox if it contains a string it uses the default equality comparer for EnquiryListItem. It will always be "No" because enquiryListItem.Equals(someString) will never be true.

You will probably need to iterate over the items collection and find a duplicate yourself. This is relatively easy with Linq

```<code>myListBox.Items.Cast<EnquiryListItem>().Any(item=> item.Text == ComboBox1.SelectedText.ToString())
</code>```

Title: ListBox.Items.Contains is not working

Body:
I am using ListBox.Items.Contains to check for duplicates but it does not seem to be working. It's two strings that I'm comparing. I have looked at the values when debugging and they appear to be exactly the same, so it should show me a messagebox to say a duplicate was found.

The item gets added to the myListBox every time, even if there is a duplicate, up to a maximum of 6 items.

Note that I am using a vendor SDK and therefore have had to change some of the code a bit but it is functionally identical. Code below. I have commented on any custom controls to explain what they are.

//Custom control - is not inherited from ListBox but it does contain a listbox. It implements IBasicEnquiryControl2 which has a property Control which will be the .Net ListBox.
Class.Namespace.Windows.eListBox lstdisplay = (Class.Namespace.Windows.eListBox)EnquiryForm.GetControl("ListBox1",EnquiryControlMissing.Exception);
ListBox myListBox = (ListBox)lstdisplay.Control;

//Returns an object from a custom class. ID property is used a bit further down, which is an int64 value
Class.Namespace.CR _cr = new Class.Namespace.CR.GetCR;

//Value key pair object item.
EnquiryListItem item;
item = new EnquiryListItem(_cr.ID,ComboBox1.SelectedText);

//Logic to check for duplicates.
if(myListBox.Items.Count < 6) {

    if (!myListBox.Items.Contains(ComboBox1.SelectedText.ToString())) {
        myListBox.BeginUpdate();
        myListBox.Items.Add(item);
        myListBox.EndUpdate();
    }
    else {
        System.Windows.Forms.MessageBox.Show("Duplicate found", "Duped", MessageBoxButtons.OK);
    }

}

Edit: The other question did not help as it doesn't seem to apply to my situation. It appears I cannot use Linq with this control, nor can I use the for loop suggested. I get errors such as System.Windows.Forms.ListBox does not contain a definition for 'Add' or the same but with Any as the missing definition. System.Linq is referenced.

Body:
It looks like you are adding EnquiryListItem to your Listbox.Items, not strings. When you ask your ListBox if it contains a string it uses the default equality comparer for EnquiryListItem. It will always be "No" because enquiryListItem.Equals(someString) will never be true.

You will probably need to iterate over the items collection and find a duplicate yourself. This is relatively easy with Linq

myListBox.Items.Cast<EnquiryListItem>().Any(item=> item.Text == ComboBox1.SelectedText.ToString())


问:
How to build a standard Linux .so library with stable Rust without using std?
Cargo.toml:

```<code>[package]
name = "proba"
version = "0.1.0"

[lib]
name = "mycoollib"
path = "src/mycoollib.rs"
crate-type = ["cdylib"]
</code>```

src/mycoollib.rs:

```<code>#![no_std]

fn func(v: i32) -> i32 {
    v + 10
}
</code>```

When I try to run cargo build:

error: language item required, but not found: `panic_fmt`
error: language item required, but not found: `eh_personality`
```

A nightly build is needed to implement panic_fmt and eh_personality, but "Using Rust Without the Standard Library" of the Rust book says that libs can build on stable.

答:
I believe that the documentation is misleading in this case. The problem is in the definition of the word "library".

A Rust library (sometimes known as an rlib) can use #[no_std] and not require definitions for panic_fmt or eh_personality. That's because eventually it will be linked against into a binary that does use the standard library, which defines these symbols.

A native library (either dylib, cdylib, or probably staticlib) has no guarantee of being linked with these symbols / language items, so they must be defined up front.

As you can see, both of these could be called a "library". I think that the book is being a little loose with the terminology, leading to the confusion.

Body:
Cargo.toml:

[package]
name = "proba"
version = "0.1.0"

[lib]
name = "mycoollib"
path = "src/mycoollib.rs"
crate-type = ["cdylib"]

src/mycoollib.rs:

#![no_std]

fn func(v: i32) -> i32 {
    v + 10
}

When I try to run cargo build:

error: language item required, but not found: `panic_fmt`
error: language item required, but not found: `eh_personality`

A nightly build is needed to implement panic_fmt and eh_personality, but "Using Rust Without the Standard Library" of the Rust book says that libs can build on stable.


问:
Golang JSON config for routes
I have been trying to setup a JSON config file to setup dynamic routes for my application. The idea is that I will be able to setup my own URL structure depending on who is using the service. I have a struct that takes in JSON and that works fine. I am using gorilla mux.

```<code> type CustomRoute struct {
    Name string
    Method string
    Path string
    HandleFunc string
 }
</code>```

The JSON is basically identical to the struct and it goes in fine.

The issue I have is getting the HandleFunc section.

Here is the code:

```<code>func NewRouter() *mux.Router {

routerInstance := mux.NewRouter().StrictSlash(true)

    /*
    All routes from the routing table
    */

    // r = []CustomRoute with the JSON data
    r := loadRoute()
    for _, route := range r {
       var handler http.Handler

       handler = route.HandlerFunc
       handler = core.Logger(handler, route.Name)

       routerInstance.
           Methods(route.Method).
           Path(route.Path).
           Name(route.Name).
           Handler(handler)

    }

    return routerInstance
}
</code>```

I always get the following error (as one would expect)

cannot use route.HandlerFunc (type string) as type http.Handler in assignment:
          string does not implement http.Handler (missing ServeHTTP method)

I was told to use something like:

```<code>var functions = map[string]interface{}{
    "HandleFunc1": HandleFunc1,
}
</code>```

But I have no idea how to make this work

答:
Thanks to RayenWindspear I was able to fix the problem. It was very simple (like everything). The map code should look like this:</p>

```<code>var functions = map[string]http.HandlerFunc{
    "HandleFunc1": HandleFunc1,
}
</code>```

Title: Golang JSON config for routes

Body:
I have been trying to setup a JSON config file to setup dynamic routes for my application. The idea is that I will be able to setup my own URL structure depending on who is using the service. I have a struct that takes in JSON and that works fine. I am using gorilla mux.

 type CustomRoute struct {
    Name string
    Method string
    Path string
    HandleFunc string
 }

The JSON is basically identical to the struct and it goes in fine.

The issue I have is getting the HandleFunc section.

Here is the code:

func NewRouter() *mux.Router {

routerInstance := mux.NewRouter().StrictSlash(true)

    /*
    All routes from the routing table
    */

    // r = []CustomRoute with the JSON data
    r := loadRoute()
    for _, route := range r {
       var handler http.Handler

       handler = route.HandlerFunc
       handler = core.Logger(handler, route.Name)

       routerInstance.
           Methods(route.Method).
           Path(route.Path).
           Name(route.Name).
           Handler(handler)

    }

    return routerInstance
}

I always get the following error (as one would expect)

cannot use route.HandlerFunc (type string) as type http.Handler in assignment:
          string does not implement http.Handler (missing ServeHTTP method)

I was told to use something like:

var functions = map[string]interface{}{
    "HandleFunc1": HandleFunc1,
}

But I have no idea how to make this work

Body:
Thanks to RayenWindspear I was able to fix the problem. It was very simple (like everything). The map code should look like this:

var functions = map[string]http.HandlerFunc{
    "HandleFunc1": HandleFunc1,
}