问:
Objc - UIAlertController buttons to add cells to a TableView
I have in my tableView, a BarButtonItem that shows me this Alert Controller:

```<code>    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"Feed RSS: info?"
                                                                          message: @""
                                                                   preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"Feed URL";
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"Feed Title";
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"Feed category";
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;

}];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

    NSArray * textfields = alertController.textFields;

    UITextField * urlfield = textfields[0];
    UITextField * titlefield = textfields[1];
    UITextField * categoryfield = textfields[2];

}]];

[self presentViewController:alertController animated:YES completion:nil];
</code>```

Now, I would like to say that when I press "OK" in the Alert Controller, the text of one of the textfields is written in the first cell of the tableview. Next, if I enter other data I will have to appear in the second cell of the tableview and so on.

According to you, how should I do it?
Do I have to modify this part?

```<code>[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
</code>```

Thanks!

答:
Create a model class to save the data entered by user in alert controller's textField.

```<code>@interface FeedInfo : NSObject
    @property (nonatomic,strong) NSString *feedURL;
    @property (nonatomic,strong) NSString *feedTitle;
    @property (nonatomic,strong) NSString *feedCategory;
@end
</code>```

Once done, create a NSMutableArray to hold the multiple feed info entered by user. In your TableViewController write

```<code>@interface ViewController ()
@property(nonatomic,strong) NSMutableArray *feedArray;
@end
</code>```

Now modify the OK action of your alert controller to create a entry in FeedArray.

```<code>[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        NSArray * textfields = alertController.textFields;

        UITextField * urlfield = textfields[0];
        UITextField * titlefield = textfields[1];
        UITextField * categoryfield = textfields[2];

        FeedInfo *newFeed = [[FeedInfo alloc] init];
        newFeed.feedURL = urlfield.text;
        newFeed.feedTitle = titlefield.text;
        newFeed.feedCategory = categoryfield.text;

        [self.feedArray addObject:newFeed];
        [self.tableView reloadData];
    }]];
</code>```

Once you add the entry to array reload the tableView using [self.tableView reloadData]; as shown above.

Implement the delegates and datasource of UITableView as below.

```<code>-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.feedArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YourCellSubclass *cell = [self.tableView dequeueReusableCellWithIdentifier:@"your_cell_identifier"];
    FeedInfo *feedToShow = [self.feedArray objectAtIndex:indexPath.row];
    cell.feedTitle.text = feedToShow.feedTitle;
    return cell;
}
</code>```

Use the FeedArray you created as the tableView data source. In cellForRowAt index path access the corresponding FeedObject and populate the fields of UITableViewCell.

You can either use default cell or use custom cell of your own. Thats all u need. If you have any doubt as to how to load the custom cell u can refer
How to load custom cell ( xib) in UICollectionView cell using swift

Body:
I have in my tableView, a BarButtonItem that shows me this Alert Controller:

    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"Feed RSS: info?"
                                                                          message: @""
                                                                   preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"Feed URL";
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"Feed Title";
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"Feed category";
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;

}];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

    NSArray * textfields = alertController.textFields;

    UITextField * urlfield = textfields[0];
    UITextField * titlefield = textfields[1];
    UITextField * categoryfield = textfields[2];

}]];

[self presentViewController:alertController animated:YES completion:nil];

Now, I would like to say that when I press "OK" in the Alert Controller, the text of one of the textfields is written in the first cell of the tableview. Next, if I enter other data I will have to appear in the second cell of the tableview and so on.

According to you, how should I do it?
Do I have to modify this part?

[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

Thanks!

Body:
Create a model class to save the data entered by user in alert controller's textField.

@interface FeedInfo : NSObject
    @property (nonatomic,strong) NSString *feedURL;
    @property (nonatomic,strong) NSString *feedTitle;
    @property (nonatomic,strong) NSString *feedCategory;
@end

Once done, create a NSMutableArray to hold the multiple feed info entered by user. In your TableViewController write

@interface ViewController ()
@property(nonatomic,strong) NSMutableArray *feedArray;
@end

Now modify the OK action of your alert controller to create a entry in FeedArray.

[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        NSArray * textfields = alertController.textFields;

        UITextField * urlfield = textfields[0];
        UITextField * titlefield = textfields[1];
        UITextField * categoryfield = textfields[2];

        FeedInfo *newFeed = [[FeedInfo alloc] init];
        newFeed.feedURL = urlfield.text;
        newFeed.feedTitle = titlefield.text;
        newFeed.feedCategory = categoryfield.text;

        [self.feedArray addObject:newFeed];
        [self.tableView reloadData];
    }]];

Once you add the entry to array reload the tableView using [self.tableView reloadData]; as shown above.

Implement the delegates and datasource of UITableView as below.

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.feedArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YourCellSubclass *cell = [self.tableView dequeueReusableCellWithIdentifier:@"your_cell_identifier"];
    FeedInfo *feedToShow = [self.feedArray objectAtIndex:indexPath.row];
    cell.feedTitle.text = feedToShow.feedTitle;
    return cell;
}

Use the FeedArray you created as the tableView data source. In cellForRowAt index path access the corresponding FeedObject and populate the fields of UITableViewCell.

You can either use default cell or use custom cell of your own. Thats all u need. If you have any doubt as to how to load the custom cell u can refer
How to load custom cell ( xib) in UICollectionView cell using swift


来源: stackexchange

问:
How to print with line number and stack trace in Haskell?
I Java I appended this to my print statements and they had a stack trace...

How can we print line numbers to the log in java

```<code>public static int getLineNumber() {
    // The second row of the stack trace had the caller file name, etc.
    return Thread.currentThread().getStackTrace()[2];
}
</code>```

How do I do this is Haskell?

答:
As noted in @user2407038's comment, modern GHC makes a CallStack available, see docs at https://www.stackage.org/haddock/lts-17.13/base-4.14.1.0/GHC-Stack.html#t:HasCallStack

Print the callstack like this:

```<code>import           GHC.Stack

msgStacktraced :: HasCallStack => String -> IO ()
msgStacktraced msg = putStrLn (msg ++ "\n" ++ prettyCallStack callStack)
</code>```

You'll need that HasCallStack constraint on anything that can call msgStacktraced as well, or it'll be hidden from the call stack.

ContentLicense: CC BY-SA 3.0

Body:
I Java I appended this to my print statements and they had a stack trace...

How can we print line numbers to the log in java

public static int getLineNumber() {
    // The second row of the stack trace had the caller file name, etc.
    return Thread.currentThread().getStackTrace()[2];
}

How do I do this is Haskell?

Body:
As noted in @user2407038's comment, modern GHC makes a CallStack available, see docs at https://www.stackage.org/haddock/lts-17.13/base-4.14.1.0/GHC-Stack.html#t:HasCallStack

Print the callstack like this:

import           GHC.Stack

msgStacktraced :: HasCallStack => String -> IO ()
msgStacktraced msg = putStrLn (msg ++ "\n" ++ prettyCallStack callStack)

You'll need that HasCallStack constraint on anything that can call msgStacktraced as well, or it'll be hidden from the call stack.

ContentLicense: CC BY-SA 4.0


问:
Adding new UITextFields by users in Swift
I'm new to Swift, and I can't figure out how to let users add new textFields on UIView.

For example, user taps on plus sign and 3 new textFields appear right after the previous ones. Also users can remove them all by one click at another button, which appears near the new textFields (the only simmilar system that I found is presented in standard Contacts application, where you can add new phone numbers, adresses, dates and so on).

Maybe inside of the "+" sign I should programmatically add these textFields and constraints for them, but I still can't figure out how to do it.
Any suggestions?

答:
You can use UIStackView or UITableView to achieve this functionality.

To create a UITextField use the following snippet.

```<code>let tf = UITextField()
tf.borderStyle = .roundedRect
tf.setContentHuggingPriority(UILayoutPriority(integerLiteral: 750), for: .horizontal)
tf.setContentHuggingPriority(UILayoutPriority(integerLiteral: 750), for: .vertical)
</code>```

Using StackView,

To Add UITextField, create a TextField and add it using func insertArrangedSubview(_ view: UIView, at stackIndex: Int) method. More information can be found here.

To Remove all the UITextFields, use func removeArrangedSubview(_ view: UIView) method. Here, you'll need to specify the views you want to remove. use arrangedSubviews property of UIStackView to get array of all the subviews. More information can be found here

Using UITableView,

You'll need a UITableViewCell configured to have a UITextField in it. Once you have the cell, simply keep a variable which keeps a count of all the UITextFields Every time user taps plus button, add a TextField using func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation). DO NOT FORGET TO INCREMENT YOUR COUNT. More information can be found here. You can also just Increase the count variable and reload the Table.

To Remove all, you can either use func deleteRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) or simply set the count variable as zero and use func reloadData(). More information can be found here and here

Body:
You can use UIStackView or UITableView to achieve this functionality.

To create a UITextField use the following snippet.

let tf = UITextField()
tf.borderStyle = .roundedRect
tf.setContentHuggingPriority(UILayoutPriority(integerLiteral: 750), for: .horizontal)
tf.setContentHuggingPriority(UILayoutPriority(integerLiteral: 750), for: .vertical)

Using StackView,

To Add UITextField, create a TextField and add it using func insertArrangedSubview(_ view: UIView, at stackIndex: Int) method. More information can be found here.

To Remove all the UITextFields, use func removeArrangedSubview(_ view: UIView) method. Here, you'll need to specify the views you want to remove. use arrangedSubviews property of UIStackView to get array of all the subviews. More information can be found here

Using UITableView,

You'll need a UITableViewCell configured to have a UITextField in it. Once you have the cell, simply keep a variable which keeps a count of all the UITextFields Every time user taps plus button, add a TextField using func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation). DO NOT FORGET TO INCREMENT YOUR COUNT. More information can be found here. You can also just Increase the count variable and reload the Table.

To Remove all, you can either use func deleteRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) or simply set the count variable as zero and use func reloadData(). More information can be found here and here


问:
All buttons have same width - jQuery
Im programming a calculator and Im trying that all the buttons in the same column has the same width. For that Im using jQuery (Im doing it this way cause I have an exam in some days and I wanna practice).

My HTML code:

```<code><html>
  <head>
    <meta charset="UTF-8">
    <title>CORE2017 P3</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="calculadora.js"></script>
    <link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
  </head>
  <body onload="igualarBotones()">
    <header>
      <p>Calculator</p>
    </header>
    <section id="main">
      <p>
        Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
      </p>

      <p>
        <button id="suma" class="columna1">+</button>
        <button id="resta" class="columna2">-</button>
        <button id="cuadrado" class="columna3">x<sup>2</sup></button>
      </p>
      <p>
        <button id="inverso" class="columna1">1/x</button>
        <button id="raiz" class="columna2">sqrt(x)</button>
        <button id="pentera" class="columna3">parte_entera(x)</button>
      </p>
      <p>
        <button id="potencia2" class="columna1">2<sup>x</sup></button>
        <button id="factorial" class="columna2">x!</button>
        <button id="igual" class="columna3">=</button>
      </p>

    </section>
  </body>
</html>
</code>```

My JavaScript code:

```<code>$(function() {
  function igualarBotones(){
    var columna1 = $(".columna1");
    setMax(columna1);
    var columna2 = $(".columna2");
    setMax(columna2);
    var columna3 = $(".columna3");
    setMax(columna3);
  }

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(columna[i].css("width") > maxColumna){
        maxColumna = columna[i].css("width");
      }
    }
    for(i=0; i<columna.length; i++){
      columna[i].css("width",maxColumna);
    }
  }

});
</code>```

Anyone knows why it isnt working?

EDIT: I used $(columna[i]).css instead of columna[i].css and it worked. However I dont achieve that my function igualarBotones() gets defined when loading the body, I think it must be something related to how I named or wrote the function. If I write the Javascript this way:

```<code>$(function() {
  var columna1 = $(".columna1");
  setMax(columna1);
  var columna2 = $(".columna2");
  setMax(columna2);
  var columna3 = $(".columna3");
  setMax(columna3);

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
        maxColumna = $(columna[i]).css("width");
      }
    }
    columna.css("width",maxColumna);
  }
});
</code>```

it works, but I want to do it with a function igualarBotones() that gets loaded with the body. Any idea what am I doing wrong?

Thank you all, Luis.

答:
The issue is understanding the different between jquery representation of elements and "raw" elements in javascript.

Given var columna1 = $(".columna1"); what this means is that it will return a jquery object that is a collection of all elements that the selector (.column1 in this case) has specified.

When you iterate through this jquery collection (columna[i]) you don't get a jquery representation of the elements but actually the raw elements themselves (or a native javascript representation of the elements). Native javascript elements do not have a .css function.

So when you wrap each element around $(...) by doing this $(columna[i])you are then once again dealing with a jquery representation of each element and as such you are able to use .css. That is why the former does not work and the later works.

EXTRA SUGGESTION

Since you are learning jquery let me add this: Jquery has a .each function that you should actually use to loop over a jquery object that contains elements.

So this function:

```<code>function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
        if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
            maxColumna = $(columna[i]).css("width");
        }
    }
    columna.css("width",maxColumna);
}
</code>```

Could/Should be:

```<code>function setMax(columna){
    var maxColumna = -1;
    columna.each(function(){
        // note the use of "this" to represent each
        // element currently being iterated over.
        // this = raw element, $(this) = jquery object representing element.
        if(parseFloat($(this).css("width")) > parseFloat(maxColumna)){
            maxColumna = $(this).css("width");
        }
    });
    columna.css("width",maxColumna);
}
</code>```

LAST TIP

I personally assist/help myself remember jquery object in my javascript code by prepending $ to all variables that are jquery objects so as to not forget them.

So this:

```<code>var columna1 = $(".columna1");
</code>```

Would be:

```<code>var $columna1 = $(".columna1");
</code>```

Title: All buttons have same width - jQuery

Body:
Im programming a calculator and Im trying that all the buttons in the same column has the same width. For that Im using jQuery (Im doing it this way cause I have an exam in some days and I wanna practice).

My HTML code:

    <meta charset="UTF-8">
    <title>CORE2017 P3</title>

    <link href="calculadora.css" rel="stylesheet" type="text/css" media="all">

Calculator

        Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>

        <button id="suma" class="columna1">+</button>
        <button id="resta" class="columna2">-</button>
        <button id="cuadrado" class="columna3">x2</button>

        <button id="inverso" class="columna1">1/x</button>
        <button id="raiz" class="columna2">sqrt(x)</button>
        <button id="pentera" class="columna3">parte_entera(x)</button>

        <button id="potencia2" class="columna1">2x</button>
        <button id="factorial" class="columna2">x!</button>
        <button id="igual" class="columna3">=</button>

My JavaScript code:

$(function() {
  function igualarBotones(){
    var columna1 = $(".columna1");
    setMax(columna1);
    var columna2 = $(".columna2");
    setMax(columna2);
    var columna3 = $(".columna3");
    setMax(columna3);
  }

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(columna[i].css("width") > maxColumna){
        maxColumna = columna[i].css("width");
      }
    }
    for(i=0; i<columna.length; i++){
      columna[i].css("width",maxColumna);
    }
  }

});

Anyone knows why it isnt working?

EDIT: I used $(columna[i]).css instead of columna[i].css and it worked. However I dont achieve that my function igualarBotones() gets defined when loading the body, I think it must be something related to how I named or wrote the function. If I write the Javascript this way:

$(function() {
  var columna1 = $(".columna1");
  setMax(columna1);
  var columna2 = $(".columna2");
  setMax(columna2);
  var columna3 = $(".columna3");
  setMax(columna3);

  function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
      if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
        maxColumna = $(columna[i]).css("width");
      }
    }
    columna.css("width",maxColumna);
  }
});

it works, but I want to do it with a function igualarBotones() that gets loaded with the body. Any idea what am I doing wrong?

Thank you all, Luis.

Body:
The issue is understanding the different between jquery representation of elements and "raw" elements in javascript.

Given var columna1 = $(".columna1"); what this means is that it will return a jquery object that is a collection of all elements that the selector (.column1 in this case) has specified.

When you iterate through this jquery collection (columna[i]) you don't get a jquery representation of the elements but actually the raw elements themselves (or a native javascript representation of the elements). Native javascript elements do not have a .css function.

So when you wrap each element around $(...) by doing this $(columna[i])you are then once again dealing with a jquery representation of each element and as such you are able to use .css. That is why the former does not work and the later works.

EXTRA SUGGESTION

Since you are learning jquery let me add this: Jquery has a .each function that you should actually use to loop over a jquery object that contains elements.

So this function:

function setMax(columna){
    var maxColumna = -1;
    for(i=0; i<columna.length; i++){
        if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
            maxColumna = $(columna[i]).css("width");
        }
    }
    columna.css("width",maxColumna);
}

Could/Should be:

function setMax(columna){
    var maxColumna = -1;
    columna.each(function(){
        // note the use of "this" to represent each
        // element currently being iterated over.
        // this = raw element, $(this) = jquery object representing element.
        if(parseFloat($(this).css("width")) > parseFloat(maxColumna)){
            maxColumna = $(this).css("width");
        }
    });
    columna.css("width",maxColumna);
}

LAST TIP

I personally assist/help myself remember jquery object in my javascript code by prepending $ to all variables that are jquery objects so as to not forget them.

So this:

var columna1 = $(".columna1");

Would be:

var $columna1 = $(".columna1");


问:
Can't bind to 'disabled' since it isn't a known property of '<button>'
I just started learning Angular but I'm having the following error:
Can't bind to 'disabled' since it isn't a known property of <button>.
Searching on internet I just found similar errors but they are related to the fact the that the FormsModule is not imported, that doesn't seem to be my case.

app.components.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  Button = false;
}
</code>```

app.component.html

```<code><div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <button [Disabled]="!Button">Click me</button>
</div>
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
Try this </p>

```<code> <button [disabled]="!Button">Click me</button>
</code>```

Body:
I just started learning Angular but I'm having the following error:
Can't bind to 'disabled' since it isn't a known property of <button>.
Searching on internet I just found similar errors but they are related to the fact the that the FormsModule is not imported, that doesn't seem to be my case.

app.components.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  Button = false;
}

app.component.html

    Welcome to {{title}}!!

  <button [Disabled]="!Button">Click me</button>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
Try this

 <button [disabled]="!Button">Click me</button>


问:
Generate PDF from PHP/HTML file including CSS
I know: opinion-based stuff shouldn't be asked etc., but this isn't about opinion, but for now simply about what still exists or rather what will still work today.

My concern: I am looking for a solution to generate one-page pdf files from PHP/HTML pages that get their content from a database and are rather heavily styled with CSS (also including tabular data and images). A function that lets you open or download the PDF when clicking on a link. The PDF should just basically look the same as the corresponding webpage at size A4 (I'll style it that way). As if you choose "preview/save as PDF" in MacOS' printing dialog, but without the user needing any particular software, working on any OS and browser.

I searched SO and the web, and I found a lot of old posts and pages (3 years and much older), like Convert HTML + CSS to PDF with PHP? , Generate PDF report from php and Generate PDF from HTML PHP I can't see in these posts if any of this is still up-to-date / working.

So I'd have to download all that stuff and build it into my pages, maybe only find out that it doesn't work anymore or isn't really applicable for my situation.

Could people who have experience with that kind of stuff please point me to places where I can find scripts/libraries which are able to do this and work with PHP 5.6 and 7? It doesn't have to support CSS3, I can restrict these pages to CSS2, and although I am using webfonts on that website, I can get along without them for the PDFs. Possibly for free, but also a not-too-expensive commercial solution would be okay. I'd be very grateful for any help.

答:
You can use the mpdf library. It's very easy to learn. Here is the sample code.
It works perfectly.

You can get value from another page, using post method also. Your choice.

```<code><?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
    background-image: url(\"images/ok.jpg\");

    background-repeat: no-repeat;
    padding-top:10pt;
    margin-top: 100px;
    padding-top: 50px;
}
td { vertical-align: top;
    border-left: 0.6mm solid #000000;
    border-right: 0.6mm solid #000000;
    align: center;
}

p.student_id{
    padding-left : 140px;
    padding-top  : -27px;
}

</style>
</head>
<body>
<!--mpdf

<p class=\"student_id\">$student_id</p>

<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->

</body>
</html>
";

$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');

$mpdf->Output();
?>
</code>```

Body:
You can use the mpdf library. It's very easy to learn. Here is the sample code.
It works perfectly.

You can get value from another page, using post method also. Your choice.

<?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
    background-image: url(\"images/ok.jpg\");

    background-repeat: no-repeat;
    padding-top:10pt;
    margin-top: 100px;
    padding-top: 50px;
}
td { vertical-align: top;
    border-left: 0.6mm solid #000000;
    border-right: 0.6mm solid #000000;
    align: center;
}

p.student_id{
    padding-left : 140px;
    padding-top  : -27px;
}

</style>
</head>
<body>
<!--mpdf

<p class=\"student_id\">$student_id</p>

<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->

</body>
</html>
";

$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');

$mpdf->Output();
?>


问:
Tool for examining potential casting problems in C#
I have the following situation on my hands. In the project I work on we have this abstract class A which has two descendants, A_concrete1 and A_concrete2. These two were around for some time now.

The time has come to add the third descendant, A_concrete3. The problem is, a lot of time in existing codebase you'll find something like that:

```<code>A instance;
// ...
// assignment of instance
// ...
if (!(A is A_concrete1))
  A_concrete2 = (A_concrete2)A;
</code>```

So now, when A has more than two descendants, this code is obviously broken and will fail at runtime.

My question is: how do I locate all these situations automatically so I could fix them? What is the best way/tool to do it? I tried to use Resharper, but it doesn't provide anything for casting analysis. So I'd be glad to hear some suggestions and pointers on this one.

Thanks in advance

答:
The best way to do it is to have methods in A (that might be overridden in the subclasses) and for any code given an A to use it only to call methods of A, and to never cast it to either subclass.  That way you won't have to do this again.

Probably Find in Files (the toolbar button features binoculars on a file folder) is the best way to find (A_concrete2) and is A_concrete1. But don't just get in there and replace the if with a bunch of ifs - change A so it's a more appropriate base class.

ContentLicense: CC BY-SA 2.5

Body:
I have the following situation on my hands. In the project I work on we have this abstract class A which has two descendants, A_concrete1 and A_concrete2. These two were around for some time now.

The time has come to add the third descendant, A_concrete3. The problem is, a lot of time in existing codebase you'll find something like that:

A instance;
// ...
// assignment of instance
// ...
if (!(A is A_concrete1))
  A_concrete2 = (A_concrete2)A;

So now, when A has more than two descendants, this code is obviously broken and will fail at runtime.

My question is: how do I locate all these situations automatically so I could fix them? What is the best way/tool to do it? I tried to use Resharper, but it doesn't provide anything for casting analysis. So I'd be glad to hear some suggestions and pointers on this one.

Thanks in advance


问:
Using a standard Inno Setup message in the Run entry description
There is a related question for those who are interested here. I was encouraged to ask one of the questions separately.

So I have this [Run] code:

```<code>Filename: "{cmd}"; Parameters: "/C exit"; Description: "Exit Setup";  \
    Flags: nowait postinstall runasoriginaluser unchecked skipifsilent; Check: IsWin64
</code>```

It works well. It shows the following window at the end of the installation:

But the problem is that the wording Exit Setup is hard coded in English. Now, I have looked at the default.isl file and located:

```<code>ExitSetupTitle=Exit Setup
ClickFinish=Click Finish to exit Setup.
</code>```

I don't know if I should be using either of these messages. It makes sense to me to use the ClickFinish because that is what the user will be doing.

But I can't work out how to use that message in the run statement.

Update

I have modified the supplied answer to:

```<code>function GetClickFinishSetupMessage(Param: string): string;
var
  I: integer;
  S1: string;
  S2: string;
begin

  S1 := SetupMessage(msgClickFinish);
  I := Length(S1);
  S2 := Copy(S1, I-1, 1);
  if(S2 = '.') then
      S1 := Delete(S1, I-1, 1);
  end;

  result := S1;
end;
</code>```

So I could remove the final period. But it will not compiled. It says there is a mismatch for the third parameter of Delete.

答:
Use SetupMessage support function from a scripted constant:

[Run]
Filename: ...; Description: {code:GetClickFinishSetupMessage}
```

<pre class="lang-pascal prettyprint-override"><code>[Code]

function GetClickFinishSetupMessage(Param: string): string;
begin
  Result := SetupMessage(msgClickFinish);

  { Drop trailing dot, if any }
  if Copy(Result, Length(Result), 1) = '.' then
    SetLength(Result, Length(Result) - 1);
end;
</code>```

Body:
There is a related question for those who are interested here. I was encouraged to ask one of the questions separately.

So I have this [Run] code:

Filename: "{cmd}"; Parameters: "/C exit"; Description: "Exit Setup";  \
    Flags: nowait postinstall runasoriginaluser unchecked skipifsilent; Check: IsWin64

It works well. It shows the following window at the end of the installation:

But the problem is that the wording Exit Setup is hard coded in English. Now, I have looked at the default.isl file and located:

ExitSetupTitle=Exit Setup
ClickFinish=Click Finish to exit Setup.

I don't know if I should be using either of these messages. It makes sense to me to use the ClickFinish because that is what the user will be doing.

But I can't work out how to use that message in the run statement.

Update

I have modified the supplied answer to:

function GetClickFinishSetupMessage(Param: string): string;
var
  I: integer;
  S1: string;
  S2: string;
begin

  S1 := SetupMessage(msgClickFinish);
  I := Length(S1);
  S2 := Copy(S1, I-1, 1);
  if(S2 = '.') then
      S1 := Delete(S1, I-1, 1);
  end;

  result := S1;
end;

So I could remove the final period. But it will not compiled. It says there is a mismatch for the third parameter of Delete.

Body:
Use SetupMessage support function from a scripted constant:

[Run]
Filename: ...; Description: {code:GetClickFinishSetupMessage}

[Code]

function GetClickFinishSetupMessage(Param: string): string;
begin
  Result := SetupMessage(msgClickFinish);

  { Drop trailing dot, if any }
  if Copy(Result, Length(Result), 1) = '.' then
    SetLength(Result, Length(Result) - 1);
end;


问:
How to empty this panel and add new panels
I have one main JPanel container and three JPanels inside. How to empty this panel and add new panels? I tried with remove(Component) but it doesn't work. Can anybody give me advice?

答:
I too had the same problem. All I did to resolve the issue was

```<code>panelName.setVisible(false);
mainPanel.remove(panelName);
</code>```

In my case, panelName is a JPanel which lies inside mainPanel.

Body:
I too had the same problem. All I did to resolve the issue was

panelName.setVisible(false);
mainPanel.remove(panelName);

In my case, panelName is a JPanel which lies inside mainPanel.


问:
How can I return null or bool from a function
I have this function:

```<code>public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}
</code>```

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

答:
I would recommend you to return true or false and get rid of strange null logic.

Using C# 7 syntax this can be made in one line:

```<code>public bool GetBoolSetting(Settings setting) => int.TryParse(GetStringSetting(setting), out int i) && i == 1;
</code>```

Body:
I have this function:

public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

Body:
I would recommend you to return true or false and get rid of strange null logic.

Using C# 7 syntax this can be made in one line:

public bool GetBoolSetting(Settings setting) => int.TryParse(GetStringSetting(setting), out int i) && i == 1;


问:
How can I show the total number of elements in ReCharts?
I want to know how to access the other data items in the 'payload' field of recharts from material-ui. I tried looking up but found no references. I want to access the other groupnames and values in the 'return' function</p>

```<code>const {PieChart, Pie, Sector} = Recharts;
const data = [{name: 'Group B', value: 14},{name: 'Group A', value: 2}, {name: 'Group C', value: 10}];

const renderActiveShape = (props) => {
  const RADIAN = Math.PI / 180;
  const { cx, cy, midAngle, innerRadius, outerRadius, startAngle, endAngle,
    fill, payload, percent, value } = props;
  //payload is the data here...
  const sin = Math.sin(-RADIAN * midAngle);
  const cos = Math.cos(-RADIAN * midAngle);
  const sx = cx + (outerRadius + 10) * cos;
  const sy = cy + (outerRadius + 10) * sin;
  const mx = cx + (outerRadius + 30) * cos;
  const my = cy + (outerRadius + 30) * sin;
  const ex = mx + (cos >= 0 ? 1 : -1) * 22;
  const ey = my;
  const textAnchor = cos >= 0 ? 'start' : 'end';

  return (
    <g>
      <text x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}>{payload.name}</text>

      {/*I want to know how to access the second element in the payload*/}

      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius}
        outerRadius={outerRadius}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
      />
      <Sector
        cx={cx}
        cy={cy}
        startAngle={startAngle}
        endAngle={endAngle}
        innerRadius={outerRadius + 6}
        outerRadius={outerRadius + 10}
        fill={fill}
      />
      <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none"/>
      <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none"/>
      <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} textAnchor={textAnchor} fill="#333">{`PV ${value}`}</text>
      <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} dy={18} textAnchor={textAnchor} fill="#999">
        {`(Rate ${(percent * 100).toFixed(2)}%)`}
      </text>
    </g>
  );
};

const TwoLevelPieChart = React.createClass({
    getInitialState() {
    return {
      activeIndex: 0,
    };
  },

    render () {
    return (
        <PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
        <Pie
            activeIndex={this.state.activeIndex}
          activeShape={renderActiveShape}
          data={data}
          cx={300}
          cy={200}
          innerRadius={60}
          outerRadius={80}
          fill="#8884d8"/>
       </PieChart>
    );
  }
})

ReactDOM.render(
  <TwoLevelPieChart />,
  document.getElementById('container')
);
</code>```

答:
You can't access the whole dataset from inside renderActiveShape as it only get's passed a single section of your chart, namely the active section. What you could do is providing a <Legend>component:

const renderLegend = (props) => {
  const { payload } = props;

  return (

Total count: {payload.length}

  );
}
```

<p>Then inside your Chart:</p>

<pre class="lang-js prettyprint-override"><code><Legend content={renderLegend} />
</code>```

Body:
I want to know how to access the other data items in the 'payload' field of recharts from material-ui. I tried looking up but found no references. I want to access the other groupnames and values in the 'return' function

const {PieChart, Pie, Sector} = Recharts;
const data = [{name: 'Group B', value: 14},{name: 'Group A', value: 2}, {name: 'Group C', value: 10}];

const renderActiveShape = (props) => {
  const RADIAN = Math.PI / 180;
  const { cx, cy, midAngle, innerRadius, outerRadius, startAngle, endAngle,
    fill, payload, percent, value } = props;
  //payload is the data here...
  const sin = Math.sin(-RADIAN * midAngle);
  const cos = Math.cos(-RADIAN * midAngle);
  const sx = cx + (outerRadius + 10) * cos;
  const sy = cy + (outerRadius + 10) * sin;
  const mx = cx + (outerRadius + 30) * cos;
  const my = cy + (outerRadius + 30) * sin;
  const ex = mx + (cos >= 0 ? 1 : -1) * 22;
  const ey = my;
  const textAnchor = cos >= 0 ? 'start' : 'end';

  return (
    <g>
      <text x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}>{payload.name}</text>

      {/*I want to know how to access the second element in the payload*/}

      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius}
        outerRadius={outerRadius}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
      />
      <Sector
        cx={cx}
        cy={cy}
        startAngle={startAngle}
        endAngle={endAngle}
        innerRadius={outerRadius + 6}
        outerRadius={outerRadius + 10}
        fill={fill}
      />
      <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none"/>
      <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none"/>
      <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} textAnchor={textAnchor} fill="#333">{`PV ${value}`}</text>
      <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} dy={18} textAnchor={textAnchor} fill="#999">
        {`(Rate ${(percent * 100).toFixed(2)}%)`}
      </text>
    </g>
  );
};

const TwoLevelPieChart = React.createClass({
    getInitialState() {
    return {
      activeIndex: 0,
    };
  },

    render () {
    return (
        <PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
        <Pie
            activeIndex={this.state.activeIndex}
          activeShape={renderActiveShape}
          data={data}
          cx={300}
          cy={200}
          innerRadius={60}
          outerRadius={80}
          fill="#8884d8"/>
       </PieChart>
    );
  }
})

ReactDOM.render(
  <TwoLevelPieChart />,
  document.getElementById('container')
);

Body:
You can't access the whole dataset from inside renderActiveShape as it only get's passed a single section of your chart, namely the active section. What you could do is providing a <Legend>component:

const renderLegend = (props) => {
  const { payload } = props;

  return (
    <p>Total count: {payload.length}</p>
  );
}

Then inside your Chart:

<Legend content={renderLegend} />


问:
Easy way to turn JavaScript array into comma-separated list?
I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)</p>

答:
Papa Parse  handles commas in values and other edge cases.

(Baby Parse for Node has been deprecated - you can now use Papa Parse in the Browser and in Node.)

Eg. (node)

```<code>const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;
</code>```

1,,"a,b"

OwnerDisplayName: Herb Caudill

Body:
Papa Parse  handles commas in values and other edge cases.

(Baby Parse for Node has been deprecated - you can now use Papa Parse in the Browser and in Node.)

Eg. (node)

const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;

1,,"a,b"


问:
How do i combine a list and a form in the same page using django?
Am building a Q&A page, sort of stackoverflow kinda page! Am having a bit of a problem trying to render the form. Am pasing 3 objects to the template that renders the page i.e. Question object, Answers related to the question and Answer form object.

In the first part of the page i want to display the Question, then the answers list follows, then at the bottom  i display my form to enter the new answer.

On my template when i use the {{ extends "base_site.html" }} tag then only the form get rendered,
When i remove that tag then only the Question section  get displayed minus the form!!

How can i go round this problem?

答:
Tricky to answer without seeing some code, but I suspect it's something to do with the way you are using {{ extends }} and inheriting/over-riding {{ block }} sections.

I would check the names of all your {{ block }} sections, and that you are over-riding the blocks that you think you are. It may be that you have blocks in the inheriting page that aren't defined in the base page?

OwnerDisplayName: Gath

LastEditorDisplayName: Gath

OwnerDisplayName: Andy Hume


问:
Profile picture default size
AS in facebook,orkut what should be  the profile pic settings height,width etc so that the image is clear and do not have any distortion when viewing it</p>

```<code>     <img src="image.gif"  style="height:75px;width:130px;"  />
</code>```

答:
There isnt a standard size, you should choose what looks the best with your design.

I would recommend avoiding setting a fixed size in the image tag. You should rather resize the image programatically to the desired size.

If distortion is a concern, you can follow this algo:

Identify the max possible width and height for the image placeholder with reference to your design.

if the user uploaded pic has height > width, then resize the pic to match the placeholder height and adjust the width to keep the image proportion intact.

If the user uploaded pic has width > height, resize the pic to match the placeholder width and adjust the height to keep the proportion intact.

This way your image would always fit the placeholder and will not have any distortion.

Title: Profile picture default size


问:
'sharedApplication' is unavailable: not available on iOS (App Extension)
I'm building an app and developed a Today Extension for it a month or two ago. Randomly, while running it maybe the 10th time in in iOS 11 Beta, I got an error for the first time and now the entire app will not build.

/Users/Documents/AppName/Pods/CarbonKit/CarbonKit/CarbonTabSwipeNavigation.m:622:27:
  'sharedApplication' is unavailable: not available on iOS (App
  Extension) - Use view controller based solutions where appropriate
  instead.

The error appears in a Pod, but it's in a file that in written in Obj-C, not Swift, so it is hard to understand.

These are the lines the error appears on:

```<code>  // Some projects use GTM_BACKGROUND_TASK_FETCHING to avoid compile-time references
  // to UIApplication.
#if GTM_BACKGROUND_TASK_FETCHING
  return (id<GTMUIApplicationProtocol>) [UIApplication sharedApplication]; <- error
#else
  return nil;
#endif
</code>```

Could anyone give advice on how to solve this error? Any help would be immensely appreciated. Thanks a ton in advance!

Cheers,
Theo

答:
As the error clearly states, the following API is not available for use in Today Extensions:

```<code>[UIApplication sharedApplication]
</code>```

Please read the Apple provided documentation on App Extensions:

Some APIs Are Unavailable to App Extensions

Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:

Access a sharedApplication object, and so cannot use any of the methods on that object

- Apple, App Extension Programming Guide

Make sure that CarbonKit (or, really, anything that uses these APIs) is not included in your Today App Extension target. Xcode should have automatically warned you about this as soon as it was included in your extension target (although it is possible to silence these warnings temporarily).

Body:
I'm building an app and developed a Today Extension for it a month or two ago. Randomly, while running it maybe the 10th time in in iOS 11 Beta, I got an error for the first time and now the entire app will not build.

/Users/Documents/AppName/Pods/CarbonKit/CarbonKit/CarbonTabSwipeNavigation.m:622:27:
  'sharedApplication' is unavailable: not available on iOS (App
  Extension) - Use view controller based solutions where appropriate
  instead.

The error appears in a Pod, but it's in a file that in written in Obj-C, not Swift, so it is hard to understand.

These are the lines the error appears on:

  // Some projects use GTM_BACKGROUND_TASK_FETCHING to avoid compile-time references
  // to UIApplication.
#if GTM_BACKGROUND_TASK_FETCHING
  return (id<GTMUIApplicationProtocol>) [UIApplication sharedApplication]; <- error
#else
  return nil;
#endif

Could anyone give advice on how to solve this error? Any help would be immensely appreciated. Thanks a ton in advance!

Cheers,
Theo

Body:
As the error clearly states, the following API is not available for use in Today Extensions:

[UIApplication sharedApplication]

Please read the Apple provided documentation on App Extensions:

Some APIs Are Unavailable to App Extensions

Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:

Access a sharedApplication object, and so cannot use any of the methods on that object

- Apple, App Extension Programming Guide

Make sure that CarbonKit (or, really, anything that uses these APIs) is not included in your Today App Extension target. Xcode should have automatically warned you about this as soon as it was included in your extension target (although it is possible to silence these warnings temporarily).


问:
Lazy eval, dplyr "filter" and NAs
I am having some silly problem using lazy evaluation and dplyr.
I'm trying to filter some NAs and don't know why the lazyeval version doesn't work. Probably I'm missing something, but I can't find it. Is that so, or is it a bug?

Here is a minimum reproducible example:

```<code>library(dplyr)
library(lazyeval)

data(iris)
iris$t <- c(1:140, rep(NA, 10))

#This Works
temp <- filter(iris, !is.na(t))

#This doesn't
temp <- filter_(iris, interp(~(!is.na(x)), x="t"))
</code>```

Both codes run without throwing out an error.

答:
You need to pass "t" as a name.

```<code>interp(~(!is.na(x)), x = as.name("t"))
# ~!is.na(t)
</code>```

As your code stands, you are inserting "t" into is.na() to make is.na("t"), which is FALSE every time.  And negating that gives TRUE every time, hence all rows.

```<code>interp(~(!is.na(x)), x = "t")
# ~!is.na("t")
</code>```

Title: Lazy eval, dplyr "filter" and NAs

Body:
I am having some silly problem using lazy evaluation and dplyr.
I'm trying to filter some NAs and don't know why the lazyeval version doesn't work. Probably I'm missing something, but I can't find it. Is that so, or is it a bug?

Here is a minimum reproducible example:

library(dplyr)
library(lazyeval)

data(iris)
iris$t <- c(1:140, rep(NA, 10))

#This Works
temp <- filter(iris, !is.na(t))

#This doesn't
temp <- filter_(iris, interp(~(!is.na(x)), x="t"))

Both codes run without throwing out an error.

Body:
You need to pass "t" as a name.

interp(~(!is.na(x)), x = as.name("t"))
# ~!is.na(t)

As your code stands, you are inserting "t" into is.na() to make is.na("t"), which is FALSE every time.  And negating that gives TRUE every time, hence all rows.

interp(~(!is.na(x)), x = "t")
# ~!is.na("t")


问:
Read many SPSS files at once in R
I am trying to read all SPSS files in a folder in R to different data.frames. I only need that, all of those files read into R dataframes.

I believe I need a for loop or maybe some solution with lapply or sapply. I have tried many options with loops or lapply, but the best I got was to create all the data.

The best I got so far was with the following code (adapted from a solution to open multiple CSV files):

```<code>library(foreign)

filenames <- list.files()

filelist <- lapply(filenames, read.spss, to.data.frame = TRUE)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col",
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)
assign(x,filelist[[x]],envir=.GlobalEnv)))
</code>```

With this code, I got all the files read, but as lists, not as data.frames. I don't know where I could put a "as.data.frame" or something like this to get what I want.

Maybe a solution would be to loop for all the files in the folder, so that the first element in the list (the first file), would be read as df.1, then df.2, etc. It doesn't matter what the names of the dataframes will be, I just need a simple code to read all of them into dataframes.

答:
It finally worked. The same code as I've put in the update of the question, but with the slight difference of using haven instead of foreign :</p>

```<code>library(haven)

filenames <- list.files()

filelist <- lapply(filenames, read_spss)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col",
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)
assign(x,filelist[[x]],envir=.GlobalEnv)))
</code>```

Title: Read many SPSS files at once in R

Body:
I am trying to read all SPSS files in a folder in R to different data.frames. I only need that, all of those files read into R dataframes.

I believe I need a for loop or maybe some solution with lapply or sapply. I have tried many options with loops or lapply, but the best I got was to create all the data.

The best I got so far was with the following code (adapted from a solution to open multiple CSV files):

library(foreign)

filenames <- list.files()

filelist <- lapply(filenames, read.spss, to.data.frame = TRUE)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col",
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)
assign(x,filelist[[x]],envir=.GlobalEnv)))

With this code, I got all the files read, but as lists, not as data.frames. I don't know where I could put a "as.data.frame" or something like this to get what I want.

Maybe a solution would be to loop for all the files in the folder, so that the first element in the list (the first file), would be read as df.1, then df.2, etc. It doesn't matter what the names of the dataframes will be, I just need a simple code to read all of them into dataframes.

Body:
It finally worked. The same code as I've put in the update of the question, but with the slight difference of using haven instead of foreign :

library(haven)

filenames <- list.files()

filelist <- lapply(filenames, read_spss)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col",
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)
assign(x,filelist[[x]],envir=.GlobalEnv)))


问:
How to test external redirects with cucumber?
How can I test that I'm being redirected to an external location using Cucumber? For example after an action is executed I may want to redirect the user to an external location. Is this possible with capybara?</p>

答:
HTTP redirection mechanism includes two steps:

HTTP server returns a 301 HTTP status ("Moved Permanently") with a new location (URI)

HTTP agent (capybara in your case) re-sends previous request to the new location

You are to find a way to recognize 301 HTTP response status (shouldn't be hard) using Capybara's DSL.

Also, you may want to turn Capybara's "follow_redirect" (or something similar) option off in order to prevent step #2.

Hope it helps.


问:
How does the CACHE option of CREATE SEQUENCE work?
CREATE SEQUENCE has CACHE option

MSDN defines it as

```<code>[ CACHE [<constant> ] | NO CACHE ]
</code>```

Increases performance for applications that use sequence objects by
  minimizing the number of disk IOs that are required to generate
  sequence numbers. Defaults to CACHE. For example, if a cache size of
  50 is chosen, SQL Server does not keep 50 individual values cached. It
  only caches the current value and the number of values left in the
  cache. This means that the amount of memory required to store the
  cache is always two instances of the data type of the sequence object.

I understand it improves performance by avoiding reads from disk IO and maintaining some info in the memory that would help reliably generate the next number in the sequence, but I cannot imagine what a simple memory representation of the cache would look like for what the MSDN describes in the example.

Can someone explain how would the cache work with this sequence

```<code>CREATE SEQUENCE s
    AS INT
    START WITH 0
    INCREMENT BY 25
    CACHE 5
</code>```

describing what the cache memory would hold when each of the following statements is executed independently:

```<code>SELECT NEXT VALUE FOR s -- returns 0
SELECT NEXT VALUE FOR s -- returns 25
SELECT NEXT VALUE FOR s -- returns 50
SELECT NEXT VALUE FOR s -- returns 75
SELECT NEXT VALUE FOR s -- returns 100
SELECT NEXT VALUE FOR s -- returns 125
</code>```

答:
This paragraph in the doc is very helpful:

For an example, a new sequence is created with a starting value of 1 and a cache size of 15. When the first value is needed, values 1
  through 15 are made available from memory. The last cached value (15)
  is written to the system tables on the disk. When all 15 numbers are
  used, the next request (for number 16) will cause the cache to be
  allocated again. The new last cached value (30) will be written to the
  system tables.

So, in your scenario

```<code>CREATE SEQUENCE s
    AS INT
    START WITH 0
    INCREMENT BY 25
    CACHE 5
</code>```

You will have 0, 25, 50, 75 and 100 in Memory and you will get only one I/O write in disk: 100.

The problem you could have, explained in the the doc, is if the server goes down and you haven't used all the 5 items, next time you ask for a value you'll get 125.

Body:
CREATE SEQUENCE has CACHE option

MSDN defines it as

[ CACHE [<constant> ] | NO CACHE ]

Increases performance for applications that use sequence objects by
  minimizing the number of disk IOs that are required to generate
  sequence numbers. Defaults to CACHE. For example, if a cache size of
  50 is chosen, SQL Server does not keep 50 individual values cached. It
  only caches the current value and the number of values left in the
  cache. This means that the amount of memory required to store the
  cache is always two instances of the data type of the sequence object.

I understand it improves performance by avoiding reads from disk IO and maintaining some info in the memory that would help reliably generate the next number in the sequence, but I cannot imagine what a simple memory representation of the cache would look like for what the MSDN describes in the example.

Can someone explain how would the cache work with this sequence

CREATE SEQUENCE s
    AS INT
    START WITH 0
    INCREMENT BY 25
    CACHE 5

describing what the cache memory would hold when each of the following statements is executed independently:

SELECT NEXT VALUE FOR s -- returns 0
SELECT NEXT VALUE FOR s -- returns 25
SELECT NEXT VALUE FOR s -- returns 50
SELECT NEXT VALUE FOR s -- returns 75
SELECT NEXT VALUE FOR s -- returns 100
SELECT NEXT VALUE FOR s -- returns 125

Body:
This paragraph in the doc is very helpful:

For an example, a new sequence is created with a starting value of 1 and a cache size of 15. When the first value is needed, values 1
  through 15 are made available from memory. The last cached value (15)
  is written to the system tables on the disk. When all 15 numbers are
  used, the next request (for number 16) will cause the cache to be
  allocated again. The new last cached value (30) will be written to the
  system tables.

So, in your scenario

CREATE SEQUENCE s
    AS INT
    START WITH 0
    INCREMENT BY 25
    CACHE 5

You will have 0, 25, 50, 75 and 100 in Memory and you will get only one I/O write in disk: 100.

The problem you could have, explained in the the doc, is if the server goes down and you haven't used all the 5 items, next time you ask for a value you'll get 125.


问:
Preserve prototypes in ADVANCED mode
I need to compile my code with closure compiler in ADVANCED mode. I also need to keep prototypes of my objects in my application because I'm looping on Javascript objects prototypes. Trying to get both results in some ReferenceError when starting the application.

When compiling with ADVANCED mode, some prototypes are removed and replaced by a function that is using an object parameter in order to recover "this" keyword. This is due to crossModuleCodeMotionNoStubMethods attribute of CompilerOptions.java.

Example of code before compilation :

```<code>function MyClass() = { // Some code }
MyClass.prototype.someFunc = function() { // Some code calling someOtherFunc };
MyClass.prototype.someOtherFunc = function(someParam) { // Some code };
</code>```

Example of code after compilation :

```<code>function MyCompiledClass = { // Some code }
MyCompiledClass.prototype.someCompiledFunc = function() { // Some code calling someOtherFunc }
function someOtherCompiledFunc(that, someParam) = { // Some code }
</code>```

I first tried to use @this and @preserve JSDoc tags to solve the problem, without success. Using @export is not a solution, because functions will then keep their original names.

I've found two options to solve my problem for now :

Refactor the code as seen here

Build a custom version of Closure Compiler as seen here

Option 1 will need to much modifications in my code and will make it less readable, if it's the only solution, I will have a go for this one.

Option 2 seems to be a nice workaround, but I've read that some changes on CompilationLevel.java may violate some core assumptions of the compiler. Can someone tell me if by modifying setCrossModuleMethodMotion from true to false, will it still respect all core assumptions of the compiler ?

I'm currently building a custom version of the compiler to check if the code is compiling properly, but even if the code is usable, I need to be sure it will be properly obfuscated.

Thank you !

答:
You can export constructors and prototype properties in the same way.
  For example:

MyClass = function(name) {
  this.myName = name;
};
MyClass.prototype.myMethod = function() {
  alert(this.myName);
};
window['MyClass'] = MyClass; // <-- Constructor
MyClass.prototype['myMethod'] = MyClass.prototype.myMethod;```

As in https://developers.google.com/closure/compiler/docs/api-tutorial3

Title: Preserve prototypes in ADVANCED mode

Body:
I need to compile my code with closure compiler in ADVANCED mode. I also need to keep prototypes of my objects in my application because I'm looping on Javascript objects prototypes. Trying to get both results in some ReferenceError when starting the application.

When compiling with ADVANCED mode, some prototypes are removed and replaced by a function that is using an object parameter in order to recover "this" keyword. This is due to crossModuleCodeMotionNoStubMethods attribute of CompilerOptions.java.

Example of code before compilation :

function MyClass() = { // Some code }
MyClass.prototype.someFunc = function() { // Some code calling someOtherFunc };
MyClass.prototype.someOtherFunc = function(someParam) { // Some code };

Example of code after compilation :

function MyCompiledClass = { // Some code }
MyCompiledClass.prototype.someCompiledFunc = function() { // Some code calling someOtherFunc }
function someOtherCompiledFunc(that, someParam) = { // Some code }

I first tried to use @this and @preserve JSDoc tags to solve the problem, without success. Using @export is not a solution, because functions will then keep their original names.

I've found two options to solve my problem for now :

Refactor the code as seen here

Build a custom version of Closure Compiler as seen here

Option 1 will need to much modifications in my code and will make it less readable, if it's the only solution, I will have a go for this one.

Option 2 seems to be a nice workaround, but I've read that some changes on CompilationLevel.java may violate some core assumptions of the compiler. Can someone tell me if by modifying setCrossModuleMethodMotion from true to false, will it still respect all core assumptions of the compiler ?

I'm currently building a custom version of the compiler to check if the code is compiling properly, but even if the code is usable, I need to be sure it will be properly obfuscated.

Thank you !

Body:
You can export constructors and prototype properties in the same way.
  For example:

MyClass = function(name) {
  this.myName = name;
};
MyClass.prototype.myMethod = function() {
  alert(this.myName);
};
window['MyClass'] = MyClass; // <-- Constructor
MyClass.prototype['myMethod'] = MyClass.prototype.myMethod;

As in https://developers.google.com/closure/compiler/docs/api-tutorial3


问:
How to represent len('') in a form different to the standard integer - Python
I'm making a hangman game in python. I want to display the amount of characters in the word, but instead of it producing the integer as the amount of characters, I would like it instead to be '_'(one for every character.)</p>

```<code>word = input('Please enter a word for your opponent:')
print(len(word) as '_') #Instead of an integer
</code>```

Body:
I'm making a hangman game in python. I want to display the amount of characters in the word, but instead of it producing the integer as the amount of characters, I would like it instead to be '_'(one for every character.)

word = input('Please enter a word for your opponent:')
print(len(word) as '_') #Instead of an integer

Body:
It might look better as:

' '.join('_' * 5) # '_ _ _ _ _'


问:
JPA / Hibernate @OneToMany with optional Child on JoinTable - Save parent affect multiple Inserts on JoinTable
I have a relation between Parent (Property) and Children (Credit), my Hibernate Configuration works fine for me as long I don`t try to save a new Child (Credit) by Cascade through the Parent (Property).

Hibernate Configurations:

```<code>@Entity
public class Property implements Ownable {

    ...

        @Valid
        // ALSO TRIED WITH CascadeType.ALL !!!
        @OneToMany(fetch = LAZY, cascade = {PERSIST, MERGE, REMOVE}, orphanRemoval = true)
        @JoinTable(
                name = "PROPERTY_CREDIT_OPTIONS",
                joinColumns = @JoinColumn(name="PROPERTY_ID", nullable = false),
                inverseJoinColumns = @JoinColumn(name = "CREDIT_ID", nullable = false, unique = true)
        )
        List<NotActiveCredit> creditOptions = new ArrayList<>();

    ...

}

@Entity
public class NotActiveCredit extends Credit {

    @ManyToOne
    @JoinTable(
        name                = "PROPERTY_CREDIT_OPTIONS",
        inverseJoinColumns  = @JoinColumn(name="PROPERTY_ID", nullable = false),
        joinColumns         = @JoinColumn(name = "CREDIT_ID", nullable = false, unique = true)
    )
    @NotNull @NonNull
    Property    property;
}
</code>```

Controller Call:

```<code>@PostMapping("/save")
public String save (
        @ModelAttribute("property") @Valid Property formProperty,
        BindingResult errors,
        ModelMap modelMap
) {
    if (!errors.hasErrors()) {

        // formProperty has new Credit in the creditOptions List
        // SAVE ONLY DELEGATS TO SPRING DATA REPOSITORY ...
        final Property savedProperty = propertyService.save(formProperty);
        ...

    } else {
        // BLABLA
    }
}
</code>```

The Logging looks like:

```<code>Enter InvestmentController.save( ... )
Enter PropertyServiceImpl.save( ... )

insert into not_active_credit (id, interest_rate_nominal_in_percent, name_of_institution, redemption_at_begin_in_percent, special_redemption_each_year_in_percent) values (default, ?, ?, ?, ?)
binding parameter [1] as [NUMERIC] - [null]
binding parameter [2] as [VARCHAR] - [test]
binding parameter [3] as [NUMERIC] - [null]
binding parameter [4] as [NUMERIC] - [null]

insert into property_credit_options (property_id, credit_id) values (?, ?)
binding parameter [1] as [BIGINT] - [1]
binding parameter [2] as [BIGINT] - [1]

Exit PropertyServiceImpl.save Returns Property

// THEN WHEN IT CLOSE THE TRANSACTION IT WANTS TO INSERT JOIN TABLE AGAIN!
insert into property_credit_options (property_id, credit_id) values (?, ?)
binding parameter [1] as [BIGINT] - [1]
binding parameter [2] as [BIGINT] - [1]

SQL Error: -104, SQLState: 23505
integrity constraint violation: unique constraint or index violation; SYS_PK_10222 table: PROPERTY_CREDIT_OPTIONS
</code>```

My Object`s Content

Any hints are very welcome.

Edit:
Additional Information. After Call of Repository.Save the List is still considered as dirty (dirty=true). Shouldn't it be false then when it has been just saved, because in console I can see it just send SQL to db making an insert. While debugging if I give the List the dirty=false then the second time Insert will not be triggered more and everything is fine. Why doesn`t it set it to false after sending inserts to DB. It shouldn't be dirty more, or do I think wrong?

SOLUTION

As crizzis suggested I removed @JoinTable from collection property creditOptions in class Property and added mappedBy='property'. The Collection is now updateable from parent.

```<code>@Valid
@OneToMany(mappedBy="property", fetch = LAZY, cascade = ALL, orphanRemoval = true)
Collection<NotActiveCredit>     creditOptions = new ArrayList<>();
</code>```

On the other side on class NotActiveCredit it is as follows:

```<code>@ManyToOne
@JoinTable(
        name                = "PROPERTY_CREDIT_OPTIONS",
        inverseJoinColumns  = @JoinColumn(name="PROPERTY_ID", nullable = false),
        joinColumns         = @JoinColumn(name = "CREDIT_ID", nullable = false, unique = true)
)
@NotNull
Property    property;
</code>```

答:
The reason the association entry is being inserted twice into the join table is that you've actually declared two separate associations (which just happen to be using the same join table) intead of just one.

When modelling a bidirectional association in JPA, one of the side must be the owning side, and the other side must be the inverse side. The inverse side is the one whose association mapping declares the mappedBy attribute.

The solution is, simply, to declare one of the sides of the association as the inverse side, and remove the @JoinTable annotation from that side. Otherwise JPA will treat each side as a separate unidirectional association.

Note that for all JPA knows, you could for some reason want to have two separate unidirectional associations (using different join tables, for example). JPA simply does not automagically know your intentions - you need the mappedBy attribute to make them clear.

Body:
I have a relation between Parent (Property) and Children (Credit), my Hibernate Configuration works fine for me as long I don`t try to save a new Child (Credit) by Cascade through the Parent (Property).

Hibernate Configurations:

@Entity
public class Property implements Ownable {

    ...

        @Valid
        // ALSO TRIED WITH CascadeType.ALL !!!
        @OneToMany(fetch = LAZY, cascade = {PERSIST, MERGE, REMOVE}, orphanRemoval = true)
        @JoinTable(
                name = "PROPERTY_CREDIT_OPTIONS",
                joinColumns = @JoinColumn(name="PROPERTY_ID", nullable = false),
                inverseJoinColumns = @JoinColumn(name = "CREDIT_ID", nullable = false, unique = true)
        )
        List<NotActiveCredit> creditOptions = new ArrayList<>();

    ...

}

@Entity
public class NotActiveCredit extends Credit {

    @ManyToOne
    @JoinTable(
        name                = "PROPERTY_CREDIT_OPTIONS",
        inverseJoinColumns  = @JoinColumn(name="PROPERTY_ID", nullable = false),
        joinColumns         = @JoinColumn(name = "CREDIT_ID", nullable = false, unique = true)
    )
    @NotNull @NonNull
    Property    property;
}

Controller Call:

@PostMapping("/save")
public String save (
        @ModelAttribute("property") @Valid Property formProperty,
        BindingResult errors,
        ModelMap modelMap
) {
    if (!errors.hasErrors()) {

        // formProperty has new Credit in the creditOptions List
        // SAVE ONLY DELEGATS TO SPRING DATA REPOSITORY ...
        final Property savedProperty = propertyService.save(formProperty);
        ...

    } else {
        // BLABLA
    }
}

The Logging looks like:

Enter InvestmentController.save( ... )
Enter PropertyServiceImpl.save( ... )

insert into not_active_credit (id, interest_rate_nominal_in_percent, name_of_institution, redemption_at_begin_in_percent, special_redemption_each_year_in_percent) values (default, ?, ?, ?, ?)
binding parameter [1] as [NUMERIC] - [null]
binding parameter [2] as [VARCHAR] - [test]
binding parameter [3] as [NUMERIC] - [null]
binding parameter [4] as [NUMERIC] - [null]

insert into property_credit_options (property_id, credit_id) values (?, ?)
binding parameter [1] as [BIGINT] - [1]
binding parameter [2] as [BIGINT] - [1]

Exit PropertyServiceImpl.save Returns Property

// THEN WHEN IT CLOSE THE TRANSACTION IT WANTS TO INSERT JOIN TABLE AGAIN!
insert into property_credit_options (property_id, credit_id) values (?, ?)
binding parameter [1] as [BIGINT] - [1]
binding parameter [2] as [BIGINT] - [1]

SQL Error: -104, SQLState: 23505
integrity constraint violation: unique constraint or index violation; SYS_PK_10222 table: PROPERTY_CREDIT_OPTIONS

My Object`s Content

Any hints are very welcome.

Edit:
Additional Information. After Call of Repository.Save the List is still considered as dirty (dirty=true). Shouldn't it be false then when it has been just saved, because in console I can see it just send SQL to db making an insert. While debugging if I give the List the dirty=false then the second time Insert will not be triggered more and everything is fine. Why doesn`t it set it to false after sending inserts to DB. It shouldn't be dirty more, or do I think wrong?

SOLUTION

As crizzis suggested I removed @JoinTable from collection property creditOptions in class Property and added mappedBy='property'. The Collection is now updateable from parent.

@Valid
@OneToMany(mappedBy="property", fetch = LAZY, cascade = ALL, orphanRemoval = true)
Collection<NotActiveCredit>     creditOptions = new ArrayList<>();

On the other side on class NotActiveCredit it is as follows:

@ManyToOne
@JoinTable(
        name                = "PROPERTY_CREDIT_OPTIONS",
        inverseJoinColumns  = @JoinColumn(name="PROPERTY_ID", nullable = false),
        joinColumns         = @JoinColumn(name = "CREDIT_ID", nullable = false, unique = true)
)
@NotNull
Property    property;


问:
What is idle mode in Android
What is idle mode in android? Is it when my phone's screen is off or is it when no application is in foreground or something else?

Actually I have got a requirement, where some power management scripts need to be run once the phone is in Idle mode.

答: According to the developer docs IDLE means that the phone is on sleep. Doze mode is for Android 6 and later.</p>

Title: What is idle mode in Android


问:
Lookup data with EF6
Hello i'd like to create relation between EF Poco and DTO.
Here is my situation
I've got these 2 entities in my application

```<code>public partial class RFID_TAG
{
    public int TAG_ID { get; set; }
    public string RFID { get; set; }
    public Nullable<int> EMPLOYEE_ID{ get; set; }

    public virtual EMPLOYEE EMPLOYEE{ get; set; }
}

public partial class EMPLOYEE
{
    public int EMPLOYEE_ID{ get; set; }
    public string FIRST_NAME{ get; set; }
    public string LAST_NAME{ get; set; }
    //ETC...
}
</code>```

I also have this DTO

```<code>public class EMPLOYEELookUpData
{
    public int EMPLOYEE_ID{ get; set; }
    public string FULL_NAME{ get; set; }
}
</code>```

I'm using this DTO for specific selects where i only need EMPLOYEE's id and name, I've got CRUD view where user can add new tags it contains datagrid with that contains all tags and textbox thats bound to currently selected tags RFID and combobox which has SelectedItem bound to currently selected tags EMPLOYEE property. This is how i'm selecting data:

```<code>    private async void GetData()
    {
        Data = await DbContext.RFID_TAG.Include(x => x.EMPLOYEE).ToListAsync();
        EmployeesList = await DbContext.MPLOYEE.Where(x => x.ACTIVE == 1)
                                        .Select(x => new EMPLOYEELookUpData{EMPLOYEE_ID = x.EMPLOYEE_ID, FULL_NAME= x.FIRST_NAME + " " + x.LAST_NAME})
                                            .ToListAsync();
    }
</code>```

But i can't figure how to make relation between EMPLOYEE and EMPLOYEELookUpData so that EF knows how to convert EMPLOYEELookUpData to EMPLOYEE.

答:
I believe you can use AutoMapper for this: https://www.nuget.org/packages/AutoMapper/.  It can be installed using Nuget.

The code would look something like this:

```<code>using (MyEntities myEntities = new MyEntities())
            {
                List<EMPLOYEELookUpData> employeeLookupData;
                try
                {
                    employeeLookupData = myDB
                        .Employee
                        .Select(EMPLOYEELookUpData)
                        .Where(c => x => x.ACTIVE == 1)
                        .ToList();
                }
                catch (InvalidOperationException e)
                {
                    //Write a log entry
                }
</code>```

I have not tested the code.  You would have to create the mappings and create special mappings for : EMPLOYEELookUpData .FullName as it equals EMPLOYEE.FirstName + EMPLOYEE.Surname.  You can find out how to do this by reading the documentation or posting another question on here.

Title: Lookup data with EF6

Body:
Hello i'd like to create relation between EF Poco and DTO.
Here is my situation
I've got these 2 entities in my application

public partial class RFID_TAG
{
    public int TAG_ID { get; set; }
    public string RFID { get; set; }
    public Nullable<int> EMPLOYEE_ID{ get; set; }

    public virtual EMPLOYEE EMPLOYEE{ get; set; }
}

public partial class EMPLOYEE
{
    public int EMPLOYEE_ID{ get; set; }
    public string FIRST_NAME{ get; set; }
    public string LAST_NAME{ get; set; }
    //ETC...
}

I also have this DTO

public class EMPLOYEELookUpData
{
    public int EMPLOYEE_ID{ get; set; }
    public string FULL_NAME{ get; set; }
}

I'm using this DTO for specific selects where i only need EMPLOYEE's id and name, I've got CRUD view where user can add new tags it contains datagrid with that contains all tags and textbox thats bound to currently selected tags RFID and combobox which has SelectedItem bound to currently selected tags EMPLOYEE property. This is how i'm selecting data:

    private async void GetData()
    {
        Data = await DbContext.RFID_TAG.Include(x => x.EMPLOYEE).ToListAsync();
        EmployeesList = await DbContext.MPLOYEE.Where(x => x.ACTIVE == 1)
                                        .Select(x => new EMPLOYEELookUpData{EMPLOYEE_ID = x.EMPLOYEE_ID, FULL_NAME= x.FIRST_NAME + " " + x.LAST_NAME})
                                            .ToListAsync();
    }

But i can't figure how to make relation between EMPLOYEE and EMPLOYEELookUpData so that EF knows how to convert EMPLOYEELookUpData to EMPLOYEE.

Body:
I believe you can use AutoMapper for this: https://www.nuget.org/packages/AutoMapper/.  It can be installed using Nuget.

The code would look something like this:

using (MyEntities myEntities = new MyEntities())
            {
                List<EMPLOYEELookUpData> employeeLookupData;
                try
                {
                    employeeLookupData = myDB
                        .Employee
                        .Select(EMPLOYEELookUpData)
                        .Where(c => x => x.ACTIVE == 1)
                        .ToList();
                }
                catch (InvalidOperationException e)
                {
                    //Write a log entry
                }

I have not tested the code.  You would have to create the mappings and create special mappings for : EMPLOYEELookUpData .FullName as it equals EMPLOYEE.FirstName + EMPLOYEE.Surname.  You can find out how to do this by reading the documentation or posting another question on here.


问:
No output, it says <terminated> on Eclipse console
This is Name class:

```<code>public class Name implements Comparable<Name> {

    public String lastName, firstName;
    public Name(String last, String first) {
        lastName = last; firstName = first;
    }

}
</code>```

This is PhoneBook class, the problem is in this class:

```<code>public class PhoneBook {

    private SortedMap<Name, Integer> directory = new TreeMap<Name, Integer>();

    public PhoneBook(ArrayList<Name> names, ArrayList<Integer> phones) {
        for (int i = 0; i < names.size(); i++) {
            directory.put(names.get(i), phones.get(i));
        }
    }

    public void print() {
        for (Map.Entry<Name,Integer> entry : directory.entrySet()) {
            System.out.print(entry.getKey());
            System.out.print(entry.getValue());
            System.out.println();
      }
    }

    public static void main(String[] args) {
        ArrayList<Integer> phones = new ArrayList<>();
        ArrayList<Name> names = new ArrayList<>();
        PhoneBook pb = new PhoneBook(names, phones);
        phones.add(8888);
        phones.add(9999);
        names.add(new Name("Shaun-Williams", "Joe"));
        names.add(new Name("Baltimore", "Paul"));
        pb.print();
    }
</code>```

I don't understand what I did wrong but this doesn't print anything. Please help.

答:
Java does not pass method arguments by reference but rather by value so the value your passing in that constructor is empty hence the not printing when you call the print method.

Initialize your objects first, then pass the build up into the constructor like below.

```<code> ArrayList<Integer> phones = new ArrayList<>();
 ArrayList<Name> names = new ArrayList<>();
 phones.add(8888);
 phones.add(9999);
 names.add(new Name("Shaun-Williams", "Joe"));
 names.add(new Name("Baltimore", "Paul"));
 //pass the object after you've done your initializations
 PhoneBook pb = new PhoneBook(names, phones);
 pb.print();
</code>```

Hope this article can help out

Body:
This is Name class:

public class Name implements Comparable<Name> {

    public String lastName, firstName;
    public Name(String last, String first) {
        lastName = last; firstName = first;
    }

}

This is PhoneBook class, the problem is in this class:

public class PhoneBook {

    private SortedMap<Name, Integer> directory = new TreeMap<Name, Integer>();

    public PhoneBook(ArrayList<Name> names, ArrayList<Integer> phones) {
        for (int i = 0; i < names.size(); i++) {
            directory.put(names.get(i), phones.get(i));
        }
    }

    public void print() {
        for (Map.Entry<Name,Integer> entry : directory.entrySet()) {
            System.out.print(entry.getKey());
            System.out.print(entry.getValue());
            System.out.println();
      }
    }

    public static void main(String[] args) {
        ArrayList<Integer> phones = new ArrayList<>();
        ArrayList<Name> names = new ArrayList<>();
        PhoneBook pb = new PhoneBook(names, phones);
        phones.add(8888);
        phones.add(9999);
        names.add(new Name("Shaun-Williams", "Joe"));
        names.add(new Name("Baltimore", "Paul"));
        pb.print();
    }

I don't understand what I did wrong but this doesn't print anything. Please help.

Body:
Java does not pass method arguments by reference but rather by value so the value your passing in that constructor is empty hence the not printing when you call the print method.

Initialize your objects first, then pass the build up into the constructor like below.

 ArrayList<Integer> phones = new ArrayList<>();
 ArrayList<Name> names = new ArrayList<>();
 phones.add(8888);
 phones.add(9999);
 names.add(new Name("Shaun-Williams", "Joe"));
 names.add(new Name("Baltimore", "Paul"));
 //pass the object after you've done your initializations
 PhoneBook pb = new PhoneBook(names, phones);
 pb.print();

Hope this article can help out


问:
vue.js: external npm package functionality not working
I'm developing using the vue-cli tool, and I'm having trouble getting the Swiper.js npm package to work on my site. TLDR I've loaded in the imports, js initialization, and css, but the swiper is unable to move to other slides past the first slide and remains static on the page.

Here is a demo of what I'm trying to implement, and here is the source code for that demo.

I'm importing the js and css files from the package right into the particular view home.vue where I'm trying to use it.

```<code><script>

    //import js and css files
    import Swiper from 'swiper'
    import 'swiper/dist/css/swiper.min.css'

    export default {}

    //initialize swiper
    var swiper = new Swiper('.swiper-container');

</script>
</code>```

I've also tried importing these files globally into the main.js file, although that seems to give the same results.

Here is the HTML from the demo that I've placed within home.vue's template:

```<code><template>
  <div>
    <!-- Swiper -->
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide">Slide 1</div>
            <div class="swiper-slide">Slide 2</div>
            <div class="swiper-slide">Slide 3</div>
            <div class="swiper-slide">Slide 4</div>
            <div class="swiper-slide">Slide 5</div>
            <div class="swiper-slide">Slide 6</div>
            <div class="swiper-slide">Slide 7</div>
            <div class="swiper-slide">Slide 8</div>
            <div class="swiper-slide">Slide 9</div>
            <div class="swiper-slide">Slide 10</div>
        </div>
    </div>
  </div>
</template>
</code>```

This renders to the page in the same way as the demo (with Slide 1 displaying and no others visible), but I am unable to move to different slides.

As well as the accepted answer, this initialization within the view also works:

```<code><script>

  import Swiper from 'swiper'
  import 'swiper/dist/css/swiper.min.css'

  export default {
    mounted(){
      //initialize swiper when document ready
      var mySwiper = new Swiper ('.swiper-container', {
      // Optional parameters
      loop: true
      })
    }
  }

</script>
</code>```

答:
As the documentation says, use jquery.onready or document.onload functions. http://idangero.us/swiper/get-started/#.WWEJplGQyUk</p>

```<code>window.onload = function () {
    //initialize swiper when document ready
    var mySwiper = new Swiper ('.swiper-container', {
       // Optional parameters
       direction: 'vertical',
       loop: true
    });
};
</code>```

Body:
I'm developing using the vue-cli tool, and I'm having trouble getting the Swiper.js npm package to work on my site. TLDR I've loaded in the imports, js initialization, and css, but the swiper is unable to move to other slides past the first slide and remains static on the page.

Here is a demo of what I'm trying to implement, and here is the source code for that demo.

I'm importing the js and css files from the package right into the particular view home.vue where I'm trying to use it.

I've also tried importing these files globally into the main.js file, although that seems to give the same results.

Here is the HTML from the demo that I've placed within home.vue's template:

<template>

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10

</template>

This renders to the page in the same way as the demo (with Slide 1 displaying and no others visible), but I am unable to move to different slides.

As well as the accepted answer, this initialization within the view also works:

Body:
As the documentation says, use jquery.onready or document.onload functions. http://idangero.us/swiper/get-started/#.WWEJplGQyUk

window.onload = function () {
    //initialize swiper when document ready
    var mySwiper = new Swiper ('.swiper-container', {
       // Optional parameters
       direction: 'vertical',
       loop: true
    });
};


问:
hide image inside UItableview cell when button is clicked
I have a cell that contains labels and image. When user clicks on the edit button on top of the View Controller I want the image inside the cell to appear and when the edit button is clicked again the image should be hidden.

The closest example is the email cells in the iPhone. when I click on the edit button every email has a checkbox next to it and when I click cancel the check disappears.

Thank you

答:
Some easy way to start with is to create some property isImageDisplaying which will indicate current state of your view controller. When user click to the button you will simply change the state of this var and reload your table view. Here you can find some sample solution:

```<code>var isImageDisplaying: Bool = false {
    didSet {
        tableView.reloadData()
    }
}

@IBAction func editButtonDidClick(_ sender: UIBarButtonItem) {
    isImageDisplaying = !isImageDisplaying
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ... // get cell
    cell.imageView.isHidden = !isImageDisplaying
    // configure rest of the cell
    return cell
}
</code>```

Body:
Some easy way to start with is to create some property isImageDisplaying which will indicate current state of your view controller. When user click to the button you will simply change the state of this var and reload your table view. Here you can find some sample solution:

var isImageDisplaying: Bool = false {
    didSet {
        tableView.reloadData()
    }
}

@IBAction func editButtonDidClick(_ sender: UIBarButtonItem) {
    isImageDisplaying = !isImageDisplaying
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ... // get cell
    cell.imageView.isHidden = !isImageDisplaying
    // configure rest of the cell
    return cell
}


问:
Javascript code review - Make element "toggleable"
I wrote a Javascript function that solves a typical problem: Given an HTML element, whenever the user clicks on it another HTML element will be shown, on another click it will be hidden.

As I am not a big Javascript guru and I have just recently started to discover the real power of Javascript, I am sure there is at least a couple of problems with my code.

Any feedback is highly appreciated.

(Note that the I'm using jQuery)

```<code>/**
 * Makes an HTML element with given with ID "targetId" being toggleable
 * controlled by the click event of the HTML element with ID "controlId".
 * The "controlFunction" is a function that should return true/false based
 * on a whether the target should be showed or hidden.
 * If there is no controlFunction "!targetElement.is(":visible")" will be used.
 * The controlFunction is applied in the context of the control element (so
 * the "this" is going to be the controlElement.
 *
 * @param targetId
 * @param controlId
 * @param controlFunction
 * @returns
 */

var makeToggleableOnClick = function (targetId, controlId, controlFunction) {
    var targetElement, controlElement, showHideValue;

    if (!targetId || !controlId) {
        return;
    }
    targetElement = $('#' + targetId);
    controlElement = $('#' + controlId);

    controlElement.css('cursor','pointer');
    controlElement.click(function() {
        if (controlFunction) {
            showHideValue = controlFunction.apply(controlElement,[]);
        } else {
            showHideValue = !targetElement.is(":visible");
        }

        if (showHideValue) {
            targetElement.slideDown();
        } else {
            targetElement.slideUp();
        }
    });
}

/************/
/* EXAMPLE  */
/************/

<input id="controlElement" type="checkbox"/>
<div id="targetElement">
  Bla-bla.
</div>

<script type="text/javascript">
  makeToggleableOnClick('targetElement', 'controlElement', function() {
    return this.is(':checked');
  });
</script>
</code>```

答:
spelling mistake. toogle is spelt 'toggle'

edit: maybe also make your function name smaller i.e toggle or makeToggle

Body:
I wrote a Javascript function that solves a typical problem: Given an HTML element, whenever the user clicks on it another HTML element will be shown, on another click it will be hidden.

As I am not a big Javascript guru and I have just recently started to discover the real power of Javascript, I am sure there is at least a couple of problems with my code.

Any feedback is highly appreciated.

(Note that the I'm using jQuery)

/**
 * Makes an HTML element with given with ID "targetId" being toggleable
 * controlled by the click event of the HTML element with ID "controlId".
 * The "controlFunction" is a function that should return true/false based
 * on a whether the target should be showed or hidden.
 * If there is no controlFunction "!targetElement.is(":visible")" will be used.
 * The controlFunction is applied in the context of the control element (so
 * the "this" is going to be the controlElement.
 *
 * @param targetId
 * @param controlId
 * @param controlFunction
 * @returns
 */

var makeToggleableOnClick = function (targetId, controlId, controlFunction) {
    var targetElement, controlElement, showHideValue;

    if (!targetId || !controlId) {
        return;
    }
    targetElement = $('#' + targetId);
    controlElement = $('#' + controlId);

    controlElement.css('cursor','pointer');
    controlElement.click(function() {
        if (controlFunction) {
            showHideValue = controlFunction.apply(controlElement,[]);
        } else {
            showHideValue = !targetElement.is(":visible");
        }

        if (showHideValue) {
            targetElement.slideDown();
        } else {
            targetElement.slideUp();
        }
    });
}

/************/
/* EXAMPLE  */
/************/

<input id="controlElement" type="checkbox"/>

  Bla-bla.


问:
How to use PHP code in HTML to generate a PDF with mPDF
I want generate an invoice in PDF from our PHP code. We use mPDF, but we see mPDF uses $html to generate PDF, meaning when our matter is stable and only in HTML, then it converts to a PDF file.

We want generate a PDF of a dynamic table of products from our database, but it always shows an error when we use PHP code in the $html tag.

How can we use our dynamic PHP code in HTML to generate a PDF with mPDF?

答:
You can use mpdf library. This code works perfectly. I hope this will save your time. You can get value from another page, using post method also. Your choice.</p>

```<code><?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
    background-image: url(\"images/ok.jpg\");

    background-repeat: no-repeat;
    padding-top:10pt;
    margin-top: 100px;
    padding-top: 50px;
}
td { vertical-align: top;
    border-left: 0.6mm solid #000000;
    border-right: 0.6mm solid #000000;
    align: center;
}

p.student_id{
    padding-left : 140px;
    padding-top  : -27px;
}

</style>
</head>
<body>
<!--mpdf

<p class=\"student_id\">$student_id</p>

<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->

</body>
</html>
";

$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');

$mpdf->Output();
?>
</code>```

Body:
You can use mpdf library. This code works perfectly. I hope this will save your time. You can get value from another page, using post method also. Your choice.

<?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
    font-size: 10pt;
    background-image: url(\"images/ok.jpg\");

    background-repeat: no-repeat;
    padding-top:10pt;
    margin-top: 100px;
    padding-top: 50px;
}
td { vertical-align: top;
    border-left: 0.6mm solid #000000;
    border-right: 0.6mm solid #000000;
    align: center;
}

p.student_id{
    padding-left : 140px;
    padding-top  : -27px;
}

</style>
</head>
<body>
<!--mpdf

<p class=\"student_id\">$student_id</p>

<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->

</body>
</html>
";

$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');

$mpdf->Output();
?>