问:
Div take the height of another div even when the later is smaller
I'm developing a web page and in it I have a list of news, divs with 2 other divs inside, an image on the left, and the title, date and the first 30 words of the news on the right. I want the image div to take the height of the text div, no matter what the size of the image is. The images usually don't have the same size/aspect ratio. I prefer to avoid fixed dimensions, since I want it to be responsive. By the way I'm using Bootstrap 3.3.7.

Here an example of what I have so far.

This is my HTML

```<code><!-- First News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/412x112/" alt="img_1" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 1</h4>
    <p>Nov 6, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Second News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4  news-img-div">
    <img src="https://fakeimg.pl/350x232/" alt="img_2" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 2</h4>
    <p>Nov 5, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Third News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/243x242/" alt="img_curso" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 3</h4>
    <p>Nov 4, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
</code>```

And this is my CSS (for visualization purposes)

```<code>.news-img-div {
  background-color: red;
}
.news-text-div {
  background-color:aqua;
}
</code>```

I set a background color to the divs for better visualization. You might need to expand the result tab so the image and the text stay in the same row.

Is there a way to accomplish using only CSS? Otherwise I welcome solutions with js.

答:
On the div that contains the two divs (which has container-fluid class), use

```<code>display: flex;
</code>```

This makes the image div take the same height as the other div, which is the same height of the container.

Here is the modified version of your code: jsFiddle

Edit

It turns out that the solution above is not what you want.

What I want is the image div to always take the height of the text div.

Here is a solution in pure JavaScript:

function adjustHeight() {
  var containers = document.querySelectorAll(".news-card");
  Array.prototype.forEach.call(containers, function(con) {
    var imgDiv = con.getElementsByClassName("news-img-cont")[0];
    var textDiv = con.getElementsByClassName("news-text-cont")[0];
    var img = imgDiv.getElementsByClassName("news-img")[0];
    var textDivHeight = textDiv.offsetHeight;
    imgDiv.style.height = String(textDivHeight) + 'px';
    img.style.maxHeight = String(textDivHeight) + 'px';
  });
}
adjustHeight();
var sch = false;
window.addEventListener("resize", function() {
  if (!sch) {
    sch = true;
    setTimeout(function() {
      sch = false;
      adjustHeight();
    }, 500);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.news-img-cont {
  background-color: red;
}

.news-text-cont {
  background-color: aqua;
}</code>```

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

News Title 1

Nov 6, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 2

Nov 5, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 3

Nov 4, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

```
</div>
</div>
</p>

<p>In the code above, we get the height of <em>each</em> text <code>div</code>, then make the height of each corresponding image <code>div</code> equal to it.</p>

<p>The purpose of the last two lines:</p>

```var img = imgDiv.getElementsByClassName("news-img")[0];
img.style.maxHeight = String(textDivHeight) + 'px';
```

is to make images always contained in their divs. Without them, big images will go outside its container.

Edit 2

You said

Sorry but this doesn't solve my problem, because as you expand the screen the images get bigger and their parent div does not sitck to the height of the text div.

I've edited the code to solve this problem: The previous adjustment of height is now done by a function (adjustHeight). This function is called on page load, and whenever the page gets resized.

Since resizing the page fires a lot of events while resizing, and adjusting the height for each of those events may be not a good idea, a scheduling approach has been implemented to make the solution more efficient.

Body:
I'm developing a web page and in it I have a list of news, divs with 2 other divs inside, an image on the left, and the title, date and the first 30 words of the news on the right. I want the image div to take the height of the text div, no matter what the size of the image is. The images usually don't have the same size/aspect ratio. I prefer to avoid fixed dimensions, since I want it to be responsive. By the way I'm using Bootstrap 3.3.7.

Here an example of what I have so far.

This is my HTML

News Title 1

Nov 6, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 2

Nov 5, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 3

Nov 4, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

And this is my CSS (for visualization purposes)

.news-img-div {
  background-color: red;
}
.news-text-div {
  background-color:aqua;
}

I set a background color to the divs for better visualization. You might need to expand the result tab so the image and the text stay in the same row.

Is there a way to accomplish using only CSS? Otherwise I welcome solutions with js.

Body:
On the div that contains the two divs (which has container-fluid class), use

display: flex;

This makes the image div take the same height as the other div, which is the same height of the container.

Here is the modified version of your code: jsFiddle

Edit

It turns out that the solution above is not what you want.

What I want is the image div to always take the height of the text div.

Here is a solution in pure JavaScript:

function adjustHeight() {
  var containers = document.querySelectorAll(".news-card");
  Array.prototype.forEach.call(containers, function(con) {
    var imgDiv = con.getElementsByClassName("news-img-cont")[0];
    var textDiv = con.getElementsByClassName("news-text-cont")[0];
    var img = imgDiv.getElementsByClassName("news-img")[0];
    var textDivHeight = textDiv.offsetHeight;
    imgDiv.style.height = String(textDivHeight) + 'px';
    img.style.maxHeight = String(textDivHeight) + 'px';
  });
}
adjustHeight();
var sch = false;
window.addEventListener("resize", function() {
  if (!sch) {
    sch = true;
    setTimeout(function() {
      sch = false;
      adjustHeight();
    }, 500);
  }
});

.news-img-cont {
  background-color: red;
}

.news-text-cont {
  background-color: aqua;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- First News -->
<div class="container-fluid panel panel-default news-card">
  <div class="col-xs-12 col-sm-4 news-img-cont">
    <img src="https://fakeimg.pl/412x112/" alt="img_1" class="img-responsive news-img">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-cont">
    <h4>News Title 1</h4>
    <p>Nov 6, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Second News -->
<div class="container-fluid panel panel-default news-card">
  <div class="col-xs-12 col-sm-4 news-img-cont">
    <img src="https://fakeimg.pl/350x232/" alt="img_2" class="img-responsive news-img">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-cont">
    <h4>News Title 2</h4>
    <p>Nov 5, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Third News -->
<div class="container-fluid panel panel-default news-card">
  <div class="col-xs-12 col-sm-4 news-img-cont">
    <img src="https://fakeimg.pl/243x242/" alt="img_curso" class="img-responsive news-img">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-cont">
    <h4>News Title 3</h4>
    <p>Nov 4, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>

In the code above, we get the height of each text div, then make the height of each corresponding image div equal to it.

The purpose of the last two lines:

var img = imgDiv.getElementsByClassName("news-img")[0];
img.style.maxHeight = String(textDivHeight) + 'px';

is to make images always contained in their divs. Without them, big images will go outside its container.

Edit 2

You said

Sorry but this doesn't solve my problem, because as you expand the screen the images get bigger and their parent div does not sitck to the height of the text div.

I've edited the code to solve this problem: The previous adjustment of height is now done by a function (adjustHeight). This function is called on page load, and whenever the page gets resized.

Since resizing the page fires a lot of events while resizing, and adjusting the height for each of those events may be not a good idea, a scheduling approach has been implemented to make the solution more efficient.


来源: stackexchange

问:
Python - If I create a variable inside a function, how can I then use it outside the function?
I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example:

```<code>def Function():
    score = 5

Function()

print(score)
</code>```

Thank you :)

答:
You have a couple options (anyone who has more, feel free to contribute):

Method 1. Declare the variable outside of the function, set it inside the function.

```<code>score = None
def Function():
    global score # This tells the function to use the variable above
    score = 5

Function()

print(score) # Or "print score" if using a different version of python
</code>```

Method 2. Return the variable and set it using that.

```<code>def Function():
    score = 5
    return score

print(Function()) # This bypasses the need to declare score outside the function.
# print(score) # This would not do anything useful, as score was never declared in this scope.
</code>```

Method 3. Use an object orientated approach.

```<code>class App:
    def __init__(self):
        App.score = 5

App()
print(App.score)
</code>```

Note that in the first method, you need to declare the variable score outside of the function in order for it to work.

ContentLicense: CC BY-SA 3.0

Body:
I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example:

def Function():
    score = 5

Function()

print(score)

Thank you :)

Body:
You have a couple options (anyone who has more, feel free to contribute):

Method 1. Declare the variable outside of the function, set it inside the function.

score = None
def Function():
    global score # This tells the function to use the variable above
    score = 5

Function()

print(score) # Or "print score" if using a different version of python

Method 2. Return the variable and set it using that.

def Function():
    score = 5
    return score

print(Function()) # This bypasses the need to declare score outside the function.
# print(score) # This would not do anything useful, as score was never declared in this scope.

Method 3. Use an object orientated approach.

class App:
    def __init__(self):
        App.score = 5

App()
print(App.score)

Note that in the first method, you need to declare the variable score outside of the function in order for it to work.


问:
Is there a way to install and run a local server on my Windows XP Home laptop?
I'm looking to set up a local server on my laptop which is running Windows XP Home Edition. I've noticed that it is impossible to install IIS on the Home Edition, but is there a way around this? Is there other software that I can install to run a server?

the purpose behind this is to mess around and play with ASP to create dynamic websites and my only computer I own has Home Edition.

Also, would running a server on my 5 year old laptop with 2GB of RAM be a good idea?

答: You can always install Apache. It should work fine on your HW.</p>

ContentLicense: CC BY-SA 2.5


问:
Angular 5: Subscription isn't triggered on next value
When a next value is pushed towards a Subject, the Subscription in the parent component isn't triggered (it does when I change the Subject to a BehaviorSubject which I can't use because there's no default value).

option.component.ts

```<code>import { Component, OnInit, Input } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-option',
  templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {

    @Input() httpHeader;

    period: Subject<string> = new Subject<string>();

    constructor(){}

    ngOnInit(){}

    setPeriod(period: string){
        this.period.next(period);
        console.log('Next period: ' + period);
    }
}
</code>```

option.component.html

```<code><mat-radio-group [(ngModel)]="periode" (ngModelChange)="setPeriod($event)">
    <span *ngFor="let option of httpHeader.option"><mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button><br /></span>
</mat-radio-group>
</code>```

Parent component:

periodeomzet.component.ts

```<code>import { Component, OnInit, Output } from '@angular/core';
import { Subscription } from 'rxjs';
import { httpService } from 'app/services/http.service';
import { OptionComponent } from 'app/units/option/option.component';

@Component({
  selector: 'app-periodeomzet',
    templateUrl: './periodeomzet.component.html',
    providers: [OptionComponent]
})
export class PeriodeomzetComponent implements OnInit {

    httpHeader: Object;
    subData: Subscription;
    subOptions: Subscription;
    period: string = 'period=d';

    constructor(
        private httpService: httpService,
        private option: OptionComponent
    ){}

    getReport(){
        this.subData = this.httpService.getReport().subscribe((res: Response) => {
            this.httpHeader = res.json()['header'];
        });
    }

    ngOnInit(){
        this.subOptions = this.option.period.subscribe(period => {
            console.log('subOptions subscription fired');

            this.period = period;
            this.getReport();
            // Do other stuff
        });
    }

    ngOnDestroy(){
        this.subData.unsubscribe();
        this.subOptions.unsubscribe();
    }
}
</code>```

periodeomzet.component.html

```<code><app-option [httpHeader]="httpHeader"></app-option>
</code>```

I expect to see "subOptions fired" in the console when I change the selection of a radio button but it only shows "Next period: ...". Why it doesn't work?

答:
You can't inject components like you're doing. Instead, you need to reference the component and use ViewChild (or ViewChildren) in order to select it.

In your template, you can use

```<code><app-option #option [httpHeader]="httpHeader"></app-option>
</code>```

Then, in the period component:

```<code>@ViewChild('option') option: OptionComponent;
</code>```

If you don't want to use the #option template syntax you can also select it based on the component class:

```<code>@ViewChild(OptionComponent) option: OptionComponent;
</code>```

Body:
When a next value is pushed towards a Subject, the Subscription in the parent component isn't triggered (it does when I change the Subject to a BehaviorSubject which I can't use because there's no default value).

option.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-option',
  templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {

    @Input() httpHeader;

    period: Subject<string> = new Subject<string>();

    constructor(){}

    ngOnInit(){}

    setPeriod(period: string){
        this.period.next(period);
        console.log('Next period: ' + period);
    }
}

option.component.html

<mat-radio-group [(ngModel)]="periode" (ngModelChange)="setPeriod($event)">
    <mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button>

</mat-radio-group>

Parent component:

periodeomzet.component.ts

import { Component, OnInit, Output } from '@angular/core';
import { Subscription } from 'rxjs';
import { httpService } from 'app/services/http.service';
import { OptionComponent } from 'app/units/option/option.component';

@Component({
  selector: 'app-periodeomzet',
    templateUrl: './periodeomzet.component.html',
    providers: [OptionComponent]
})
export class PeriodeomzetComponent implements OnInit {

    httpHeader: Object;
    subData: Subscription;
    subOptions: Subscription;
    period: string = 'period=d';

    constructor(
        private httpService: httpService,
        private option: OptionComponent
    ){}

    getReport(){
        this.subData = this.httpService.getReport().subscribe((res: Response) => {
            this.httpHeader = res.json()['header'];
        });
    }

    ngOnInit(){
        this.subOptions = this.option.period.subscribe(period => {
            console.log('subOptions subscription fired');

            this.period = period;
            this.getReport();
            // Do other stuff
        });
    }

    ngOnDestroy(){
        this.subData.unsubscribe();
        this.subOptions.unsubscribe();
    }
}

periodeomzet.component.html

<app-option [httpHeader]="httpHeader"></app-option>

I expect to see "subOptions fired" in the console when I change the selection of a radio button but it only shows "Next period: ...". Why it doesn't work?

Body:
You can't inject components like you're doing. Instead, you need to reference the component and use ViewChild (or ViewChildren) in order to select it.

In your template, you can use

<app-option #option [httpHeader]="httpHeader"></app-option>

Then, in the period component:

@ViewChild('option') option: OptionComponent;

If you don't want to use the #option template syntax you can also select it based on the component class:

@ViewChild(OptionComponent) option: OptionComponent;


问:
warning illegal string offset while fetching result from database
I am using the following code to find the data from database

```<code>echo $query = "select * from `oc_order` where `store_url`='' ORDER BY `order_id` DESC LIMIT 5";
$mysqlq = mysqli_query($connection,$query) or die(mysqli_error($connection));
$mysqlw = mysqli_fetch_array($mysqlq);
echo "```";
print_r($mysqlw);
foreach($mysqlw as $mysqlw)
{
    echo $mysqlw['telephone'];
}
?>
```

<p>I am getting the following array</p>

```Array
(
    [0] => 73
    [order_id] => 73
    [1] => 0
    [invoice_no] => 0
    [2] =>
    [invoice_prefix] =>
    [3] => 0
    [store_id] => 0
    [4] =>
    [store_name] =>
    [5] =>
    [store_url] =>
    [6] => 9
    [customer_id] => 9
    [7] => 1
    [customer_group_id] => 1
    [8] => T****
    [firstname] => ****
    [9] =>
    [lastname] =>
    [10] => ********
    [email] => *******
    [11] => *****
    [telephone] => *****
    [12] =>
    [fax] =>
    [13] => 364ce6e2003bb1404f34
    [custom_field] => 364ce6e2003bb1404f34
    [14] =>
    [payment_firstname] =>
    [15] =>
    [payment_lastname] =>
    [16] =>
    [payment_company] =>
    [17] =>
    [payment_address_1] =>
    [18] =>
    [payment_address_2] =>
    [19] =>
    [payment_city] =>
    [20] =>
    [payment_postcode] =>
    [21] =>
    [payment_country] =>
    [22] => 0
    [payment_country_id] => 0
    [23] =>
    [payment_zone] =>
    [24] => 0
    [payment_zone_id] => 0
    [25] =>
    [payment_address_format] =>
    [26] =>
    [payment_custom_field] =>
    [27] =>
    [payment_method] =>
    [28] =>
    [payment_code] =>
    [29] =>
    [shipping_firstname] =>
    [30] =>
    [shipping_lastname] =>
    [31] =>
    [shipping_company] =>
    [32] =>
    [shipping_address_1] =>
    [33] =>
    [shipping_address_2] =>
    [34] =>
    [shipping_city] =>
    [35] =>
    [shipping_postcode] =>
    [36] =>
    [shipping_country] =>
    [37] => 0
    [shipping_country_id] => 0
    [38] =>
    [shipping_zone] =>
    [39] => 0
    [shipping_zone_id] => 0
    [40] =>
    [shipping_address_format] =>
    [41] =>
    [shipping_custom_field] =>
    [42] =>
    [shipping_method] =>
    [43] =>
    [shipping_code] =>
    [44] => 1,19
    [comment] => 1,19
    [45] => 100.0000
    [total] => 100.0000
    [46] => 0
    [order_status_id] => 0
    [47] => 0
    [affiliate_id] => 0
    [48] => 0.0000
    [commission] => 0.0000
    [49] => 0
    [marketing_id] => 0
    [50] =>
    [tracking] =>
    [51] => 0
    [language_id] => 0
    [52] => 0
    [currency_id] => 0
    [53] => INR
    [currency_code] => INR
    [54] => 1.00000000
    [currency_value] => 1.00000000
    [55] =>
    [ip] =>
    [56] =>
    [forwarded_ip] =>
    [57] =>
    [user_agent] =>
    [58] =>
    [accept_language] =>
    [59] => 0000-00-00 00:00:00
    [date_added] => 0000-00-00 00:00:00
    [60] => 0000-00-00 00:00:00
    [date_modified] => 0000-00-00 00:00:00
)
```

but when i am trying to print the value of echo $mysqlw['telephone']; it is throwing warning Warning: Illegal string offset 'telephone' in

What mistake I am making in this code ?

答:
Note your foreach statement has same variable name on both sides of 'as'

```<code>foreach($mysqlw as $mysqlw)
</code>```

If you want to loop and access each value of an array do this instead:

```<code>foreach($mysqlw as $value)
{
    echo $value;
}
</code>```

Body:
I am using the following code to find the data from database

echo $query = "select * from `oc_order` where `store_url`='' ORDER BY `order_id` DESC LIMIT 5";
$mysqlq = mysqli_query($connection,$query) or die(mysqli_error($connection));
$mysqlw = mysqli_fetch_array($mysqlq);
echo "
";
print_r($mysqlw);
foreach($mysqlw as $mysqlw)
{
    echo $mysqlw['telephone'];
}
?>

I am getting the following array

Array
(
    [0] => 73
    [order_id] => 73
    [1] => 0
    [invoice_no] => 0
    [2] =>
    [invoice_prefix] =>
    [3] => 0
    [store_id] => 0
    [4] =>
    [store_name] =>
    [5] =>
    [store_url] =>
    [6] => 9
    [customer_id] => 9
    [7] => 1
    [customer_group_id] => 1
    [8] => T****
    [firstname] => ****
    [9] =>
    [lastname] =>
    [10] => ********
    [email] => *******
    [11] => *****
    [telephone] => *****
    [12] =>
    [fax] =>
    [13] => 364ce6e2003bb1404f34
    [custom_field] => 364ce6e2003bb1404f34
    [14] =>
    [payment_firstname] =>
    [15] =>
    [payment_lastname] =>
    [16] =>
    [payment_company] =>
    [17] =>
    [payment_address_1] =>
    [18] =>
    [payment_address_2] =>
    [19] =>
    [payment_city] =>
    [20] =>
    [payment_postcode] =>
    [21] =>
    [payment_country] =>
    [22] => 0
    [payment_country_id] => 0
    [23] =>
    [payment_zone] =>
    [24] => 0
    [payment_zone_id] => 0
    [25] =>
    [payment_address_format] =>
    [26] =>
    [payment_custom_field] =>
    [27] =>
    [payment_method] =>
    [28] =>
    [payment_code] =>
    [29] =>
    [shipping_firstname] =>
    [30] =>
    [shipping_lastname] =>
    [31] =>
    [shipping_company] =>
    [32] =>
    [shipping_address_1] =>
    [33] =>
    [shipping_address_2] =>
    [34] =>
    [shipping_city] =>
    [35] =>
    [shipping_postcode] =>
    [36] =>
    [shipping_country] =>
    [37] => 0
    [shipping_country_id] => 0
    [38] =>
    [shipping_zone] =>
    [39] => 0
    [shipping_zone_id] => 0
    [40] =>
    [shipping_address_format] =>
    [41] =>
    [shipping_custom_field] =>
    [42] =>
    [shipping_method] =>
    [43] =>
    [shipping_code] =>
    [44] => 1,19
    [comment] => 1,19
    [45] => 100.0000
    [total] => 100.0000
    [46] => 0
    [order_status_id] => 0
    [47] => 0
    [affiliate_id] => 0
    [48] => 0.0000
    [commission] => 0.0000
    [49] => 0
    [marketing_id] => 0
    [50] =>
    [tracking] =>
    [51] => 0
    [language_id] => 0
    [52] => 0
    [currency_id] => 0
    [53] => INR
    [currency_code] => INR
    [54] => 1.00000000
    [currency_value] => 1.00000000
    [55] =>
    [ip] =>
    [56] =>
    [forwarded_ip] =>
    [57] =>
    [user_agent] =>
    [58] =>
    [accept_language] =>
    [59] => 0000-00-00 00:00:00
    [date_added] => 0000-00-00 00:00:00
    [60] => 0000-00-00 00:00:00
    [date_modified] => 0000-00-00 00:00:00
)

but when i am trying to print the value of echo $mysqlw['telephone']; it is throwing warning Warning: Illegal string offset 'telephone' in

What mistake I am making in this code ?

Body:
Note your foreach statement has same variable name on both sides of 'as'

foreach($mysqlw as $mysqlw)

If you want to loop and access each value of an array do this instead:

foreach($mysqlw as $value)
{
    echo $value;
}


问:
Docusign for Salesforce template - Show merge fields to all roles
I am trying to setup a template using Docusign for Salesforce. My template is 20 page long and has about 50 merge fields to be populated from Saleforce. These merge fields are read only. We have multiple signer roles - 6 signer roles to be specific. In the template, all 6 signer roles should see all the merge fields.

Problem is when these merge fields are added to template by drag and drop, you have to select a single role and then drag and drop a field on template.

Is there a way to prepare a template so that merge field display on the template can be added for all roles in a single go?

答:
Docusign support was able to resolve the question.

We need to edit the tags after they are added to the template. Click on each tag and go to Collaboration and check the box to "Recipients Can Collaborate.


问:
Keras maximize cross-sequence correlation
I am using Keras with Tensorflow backend to do sequence prediction on multiple sequences simultaneously one step at a time; that is, I have n sequences each with m timesteps and I load them all into Keras with one model.predict() command and the model returns an 'n' element array with each element corresponding to the predicted next step for each of the n sequences.

So my goal is to maximize the ability for Keras to detect cross-correlations between the sequences. For example, say sequence a strongly correlates with sequence b with some time delay and scaling factor difference, then in theory Keras should be able to use sequence b to better predict the next step for sequence a. How I have it now I am testing with 4 sequences, each 30 elements long, and sending them to my model as exactly that, input data has the shape (4, 30, 1) and output data has the shape (4, 1):

```<code>model = Sequential()

model.add(LSTM(
    input_shape=(30, 1),
    output_dim=100,
    return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(
    200,
    return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(
    output_dim=1,
    return_sequences=False))
model.add(Activation("linear"))

model.compile(loss="mse", optimizer="rmsprop")
return model
</code>```

What I'm wondering is if Keras is already cross-correlating the sequences, or if my model currently views them as independent and just predicts them all at the same time (i.e. it would be the same as predicting the next step for sequence a, then b, then c, etc.). Would Keras be able to better cross-correlate the sequences if I treated them as 1 sequences with n features per time-step (that is, input data of shape (1, 30, 4) and output data of shape (1, 4))? And if so would I still be able to output an n-element array with each element still being correlated to one of the input arrays (i.e. would they maintain distinguish-ability)?

Thanks!

答:
I went ahead and just tested both ways, and found that - to answer my own question:

Yes, Keras was originally treating the sequences individually, not cross-correlating at all.

Yes, therefore by inputting the data as a single sequences with multiple features it was able to better cross-correlate (in this case that was the only scenario that offered any cross-correlation)

Yes, Keras was able to maintain distinguish-ability between the features.

To determine this I did multiple trials with each input format and originally was calculating a chi^2 fit for the prediction vs. the actual test data to see whether inputting sequences A-D better improved the prediction of A over just inputting A and B. When doing this however, I quickly noticed that in my original format inputs B-D had no effect on the prediction of A (using a pre-trained model for 4 inputs, switching sequence C with D - which since distinguish-ability is maintained and required should have significantly changed the output - caused absolutely no change in the prediction). When doing the same input switch with the new model for 4 features, there was a clear dependence of the prediction for A on the other inputs B-D. Using the multiple features model over the multiple inputs model also resulted in a far smoother output, which is better for my application and makes sense as it is now dependent on more variables which presumably act to control outliers.

Body:
I am using Keras with Tensorflow backend to do sequence prediction on multiple sequences simultaneously one step at a time; that is, I have n sequences each with m timesteps and I load them all into Keras with one model.predict() command and the model returns an 'n' element array with each element corresponding to the predicted next step for each of the n sequences.

So my goal is to maximize the ability for Keras to detect cross-correlations between the sequences. For example, say sequence a strongly correlates with sequence b with some time delay and scaling factor difference, then in theory Keras should be able to use sequence b to better predict the next step for sequence a. How I have it now I am testing with 4 sequences, each 30 elements long, and sending them to my model as exactly that, input data has the shape (4, 30, 1) and output data has the shape (4, 1):

model = Sequential()

model.add(LSTM(
    input_shape=(30, 1),
    output_dim=100,
    return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(
    200,
    return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(
    output_dim=1,
    return_sequences=False))
model.add(Activation("linear"))

model.compile(loss="mse", optimizer="rmsprop")
return model

What I'm wondering is if Keras is already cross-correlating the sequences, or if my model currently views them as independent and just predicts them all at the same time (i.e. it would be the same as predicting the next step for sequence a, then b, then c, etc.). Would Keras be able to better cross-correlate the sequences if I treated them as 1 sequences with n features per time-step (that is, input data of shape (1, 30, 4) and output data of shape (1, 4))? And if so would I still be able to output an n-element array with each element still being correlated to one of the input arrays (i.e. would they maintain distinguish-ability)?

Thanks!


问:
Align buttons to line up with fieldset
Background:The website I am working on there are several different filters that people can use in order to show only the data they need; basic stuff. To make things look nice since I am not css inclined, I am using bootstrap to make things look clean.

Problem: I can't seem to get the buttons to line up with the right side of the fields. I can make them pull to the very edge of the field set, I can make push/pull them to the general area they should be in, but I can't get them to line up nicely and stay that way regardless of how you rearrange the size of the page window.

JSFiddle: https://jsfiddle.net/v3cugpx1/1/

```<code><div class="form-group col-md-12">
    <div class="input-group-btn">
        <div class="pull-right">
            <a class="btn btn-info" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left"></i> Clear</a>
            <button class="btn btn-primary" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
        </div>
    </div>
</div>
</code>```

Any help would be greatly appreciated.

Cheers!

答:
Don't use .input-group instead use col-sm-* classes to give extra padding multiple times, so that you can match the padding available on all other form elements. And then arrange the buttons inside of it, like:

```<code><div class="form-group col-md-12"> <!-- Extra Padding (15px) -->
  <div class="col-xs-12"> <!-- Extra Padding (15px) -->
    <div class="col-xs-12"> <!-- Extra Padding (15px) -->
      <a class="btn btn-info" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left pull-left"></i> Clear</a>
      <button class="btn btn-primary pull-right" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
      </div>
  </div>
</div>
</code>```

Have a look at the updated Fiddle.

Hope this helps!

Title: Align buttons to line up with fieldset

Body:
Background:The website I am working on there are several different filters that people can use in order to show only the data they need; basic stuff. To make things look nice since I am not css inclined, I am using bootstrap to make things look clean.

Problem: I can't seem to get the buttons to line up with the right side of the fields. I can make them pull to the very edge of the field set, I can make push/pull them to the general area they should be in, but I can't get them to line up nicely and stay that way regardless of how you rearrange the size of the page window.

JSFiddle: https://jsfiddle.net/v3cugpx1/1/

             Clear
            <button class="btn btn-primary" title="Filter" type="submit"> Filter</button>

Any help would be greatly appreciated.

Cheers!

Body:
Don't use .input-group instead use col-sm-* classes to give extra padding multiple times, so that you can match the padding available on all other form elements. And then arrange the buttons inside of it, like:

<div class="form-group col-md-12"> <!-- Extra Padding (15px) -->
  <div class="col-xs-12"> <!-- Extra Padding (15px) -->
    <div class="col-xs-12"> <!-- Extra Padding (15px) -->
      <a class="btn btn-info" href="#" title="Clear"><i class="glyphicon glyphicon-arrow-left pull-left"></i> Clear</a>
      <button class="btn btn-primary pull-right" title="Filter" type="submit"><i class="glyphicon glyphicon-search"></i> Filter</button>
      </div>
  </div>
</div>

Have a look at the updated Fiddle.

Hope this helps!


问:
ngrx/store init store is not working properly
My store contains the following reducers :

```<code>export const centralStampState = {
  layoutState : layoutReducer, //this one is not initialized
  eventTabState : eventTabReducer,
  eventTimelineState: eventTimelineReducer,
  eventWorkflowState : eventWorkflowReducer,
  displayLayerState : displayLayerReducer,
  treeState : TreeReducer
}
</code>```

The problem is that Angular initilize all the reducers , only one 'layoutState' is initilized after firing the first action(Which cause an access to an undefined Object).

I am following the same implementation for all the reducers and states, and I didn't figure out the cause of this strange behavior.

The following is  the state of the Store after the initialization and after the first action

My implementation is the same for all the reducers.

```<code>export function layoutReducer(state: LayoutState = INITIAL_LAYOUT_STATE, action: Action) : LayoutState{
  switch (action.type){
    case UPDATE_SPLIT_CONFIG_DIMENSION :
      return updateSplitConfigDimension(state, action);
    case DISABLE_SPLIT_CONFIGURATION:
      return state;
    case UPDATE_SPLIT_AREA_VISIBILITY :
      return state;
    case RESTORE_DEFAULT_CONFIG_LAYOUT :
      return state;
  }
}

export function eventTabReducer(state: EventTabState = EVENT_TAB_INITIAL_STATE, action: CSAction): EventTabState {
  switch (action.type) {
    case LOAD_SUPPORTED_REPORT_FIELDS:
          return state;
    default:
      return state;
  }
}
</code>```

答:
I found it, if it was JAVA instead of Typescript the code will not compile at all !!!!!!!!

I am missing the default statement inside the switch case, When Angular is dealing with the action @ngrx/store/init the layoutReducer will ignore this action and it seems that Angular will return undefined if it doesn't find the default statement.

```<code>export function layoutReducer(state: LayoutState = INITIAL_LAYOUT_STATE, action: Action) : LayoutState{
  switch (action.type){
    case UPDATE_SPLIT_CONFIG_DIMENSION :
      return updateSplitConfigDimension(state, action);
    case DISABLE_SPLIT_CONFIGURATION:
      return state;
    case UPDATE_SPLIT_AREA_VISIBILITY :
      return state;
    case RESTORE_DEFAULT_CONFIG_LAYOUT :
      return state;
    default:
      return state;// with this Angular can perform the ngrx init action
  }
}
</code>```

Body:
My store contains the following reducers :

export const centralStampState = {
  layoutState : layoutReducer, //this one is not initialized
  eventTabState : eventTabReducer,
  eventTimelineState: eventTimelineReducer,
  eventWorkflowState : eventWorkflowReducer,
  displayLayerState : displayLayerReducer,
  treeState : TreeReducer
}

The problem is that Angular initilize all the reducers , only one 'layoutState' is initilized after firing the first action(Which cause an access to an undefined Object).

I am following the same implementation for all the reducers and states, and I didn't figure out the cause of this strange behavior.

The following is  the state of the Store after the initialization and after the first action

My implementation is the same for all the reducers.

export function layoutReducer(state: LayoutState = INITIAL_LAYOUT_STATE, action: Action) : LayoutState{
  switch (action.type){
    case UPDATE_SPLIT_CONFIG_DIMENSION :
      return updateSplitConfigDimension(state, action);
    case DISABLE_SPLIT_CONFIGURATION:
      return state;
    case UPDATE_SPLIT_AREA_VISIBILITY :
      return state;
    case RESTORE_DEFAULT_CONFIG_LAYOUT :
      return state;
  }
}

export function eventTabReducer(state: EventTabState = EVENT_TAB_INITIAL_STATE, action: CSAction): EventTabState {
  switch (action.type) {
    case LOAD_SUPPORTED_REPORT_FIELDS:
          return state;
    default:
      return state;
  }
}

Body:
I found it, if it was JAVA instead of Typescript the code will not compile at all !!!!!!!!

I am missing the default statement inside the switch case, When Angular is dealing with the action @ngrx/store/init the layoutReducer will ignore this action and it seems that Angular will return undefined if it doesn't find the default statement.

export function layoutReducer(state: LayoutState = INITIAL_LAYOUT_STATE, action: Action) : LayoutState{
  switch (action.type){
    case UPDATE_SPLIT_CONFIG_DIMENSION :
      return updateSplitConfigDimension(state, action);
    case DISABLE_SPLIT_CONFIGURATION:
      return state;
    case UPDATE_SPLIT_AREA_VISIBILITY :
      return state;
    case RESTORE_DEFAULT_CONFIG_LAYOUT :
      return state;
    default:
      return state;// with this Angular can perform the ngrx init action
  }
}


问:
Adding line breaks when using interpolation
I have some html for an alert message box. Using interpolation, I can re-use the same html to show multiple different alert messages. It looks like this:
{{ myAlertMessage }}

Now I want to show a longer alert message containing line breaks. However, I cannot seem to modify the interpolated component property (which is a string) in any way which will introduce line breaks.

For example, using
, or spacing the text across several lines in the component code (contained in either parentheses or back ticks), or the new line code (
). None of these work to produce a line break in the text when the alert message is shown.

I would prefer not to have to add further property bindings just to cater for this particular use case.

Thanks in advance.

答:
Just use

```<code><span [innerHTML]="myAlertMessage"></span>
</code>```

the innerHTML property will interpret your html code.

Body:
Just use

<span [innerHTML]="myAlertMessage"></span>

the innerHTML property will interpret your html code.


问:
A query that uses a view as a relation
Can someone give me an example of a query that uses a view as a relation? or how can I turn this query as a view as a relation?</p>

```<code>SELECT COUNT(Y.custorderID) AS NoOfOrders, x.city ||' '||
       EXTRACT(YEAR FROM TO_DATE(Y.dateorderplaced, 'DD-MON-RR'))
FROM (SELECT custorderid, custID, customerorder.dateorderplaced
      FROM CustomerOrder
      WHERE EXTRACT(MONTH FROM
            TO_DATE(CustomerOrder.dateorderplaced, 'DD-MON-RR')) =1 AND  EXTRACT(YEAR FROM
      TO_DATE(CustomerOrder.dateorderplaced, 'DD-MON-RR')) = 2017
     )  Y
     INNER JOIN Customer x
         ON Y.custID = x.custID
GROUP BY x.city, y.dateOrderplaced
</code>```

答:
```<code>Create view getProducts_v as (
  SELECT *
  FROM  Product
  WHERE Active = 'Y' and OnHandQty>0);

SELECT *
FROM  GetProducts_v P
INNER JOIN  ProductCategory PC
 on PC.ProductID = P.ID
WHERE PC.Name in ('Houseware','Kitchen')
</code>```

The view getProducts_v only provides a list of items that are active and which availability exists.

The query then uses the view to get a list of only those products in housewares kitchen.  Since the view already filtered out the inactive and those with 0 onHandQty, we only show users things we have instock and active.

Taking what you have:

```<code>CREATE view GetOrderHeader_v as (
      SELECT custorderid, custID, customerorder.dateorderplaced
      FROM CustomerOrder
     );

SELECT COUNT(gOH.custorderID) AS NoOfOrders
     , x.city ||' '||  EXTRACT(YEAR FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR'))
FROM  GetOrderHeader_v gOH
INNER JOIN Customer x
   ON gOH.custID = x.custID
WHERE EXTRACT(MONTH FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR')) =1
  AND EXTRACT(YEAR FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR')) = 2017
GROUP BY x.city ||' '||  EXTRACT(YEAR FROM TO_DATE(Y.dateorderplaced, 'DD-MON-RR'))
       , gOH.dateOrderplaced;
</code>```

Note I wouldn't use the to_date above if the field is already a date datatype as it adds unnecessary overhead.  If  dateorderplaced isn't already a date, I would have some concerns with the table structures.

Normally I would only use such a view on a complex query or if I wanted to encase a table in logic to eliminate redundant checks; such as we only ever show active products; but we do not delete products from our product table so we have the developers reference the GetProducts_v which never shows deleted products or ones that are out of stock.

Title: A query that uses a view as a relation

Body:
Can someone give me an example of a query that uses a view as a relation? or how can I turn this query as a view as a relation?

SELECT COUNT(Y.custorderID) AS NoOfOrders, x.city ||' '||
       EXTRACT(YEAR FROM TO_DATE(Y.dateorderplaced, 'DD-MON-RR'))
FROM (SELECT custorderid, custID, customerorder.dateorderplaced
      FROM CustomerOrder
      WHERE EXTRACT(MONTH FROM
            TO_DATE(CustomerOrder.dateorderplaced, 'DD-MON-RR')) =1 AND  EXTRACT(YEAR FROM
      TO_DATE(CustomerOrder.dateorderplaced, 'DD-MON-RR')) = 2017
     )  Y
     INNER JOIN Customer x
         ON Y.custID = x.custID
GROUP BY x.city, y.dateOrderplaced

Body:
Create view getProducts_v as (
  SELECT *
  FROM  Product
  WHERE Active = 'Y' and OnHandQty>0);

SELECT *
FROM  GetProducts_v P
INNER JOIN  ProductCategory PC
 on PC.ProductID = P.ID
WHERE PC.Name in ('Houseware','Kitchen')

The view getProducts_v only provides a list of items that are active and which availability exists.

The query then uses the view to get a list of only those products in housewares kitchen.  Since the view already filtered out the inactive and those with 0 onHandQty, we only show users things we have instock and active.

Taking what you have:

CREATE view GetOrderHeader_v as (
      SELECT custorderid, custID, customerorder.dateorderplaced
      FROM CustomerOrder
     );

SELECT COUNT(gOH.custorderID) AS NoOfOrders
     , x.city ||' '||  EXTRACT(YEAR FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR'))
FROM  GetOrderHeader_v gOH
INNER JOIN Customer x
   ON gOH.custID = x.custID
WHERE EXTRACT(MONTH FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR')) =1
  AND EXTRACT(YEAR FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR')) = 2017
GROUP BY x.city ||' '||  EXTRACT(YEAR FROM TO_DATE(Y.dateorderplaced, 'DD-MON-RR'))
       , gOH.dateOrderplaced;

Note I wouldn't use the to_date above if the field is already a date datatype as it adds unnecessary overhead.  If  dateorderplaced isn't already a date, I would have some concerns with the table structures.

Normally I would only use such a view on a complex query or if I wanted to encase a table in logic to eliminate redundant checks; such as we only ever show active products; but we do not delete products from our product table so we have the developers reference the GetProducts_v which never shows deleted products or ones that are out of stock.


问:
Function that takes string as Input, evaluate it like a calculator and return the Integer answer
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

```<code>d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i
</code>```

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

答:
pythonic way is to use eval

```<code>eval("-2+2")
eval("1+2-3")
</code>```

If you want to implement with your way then

```<code>def f(s):
   s = s.replace('-', ' -')
   s = s.replace('+', ' +')
   l = s.split(" ")
   sum = 0
   for num in l:
       sum = sum + float(num)
   return sum
s = "4747-74+484-44"
print (f(s))
# output: 5113.0
</code>```

Body:
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

Body:
pythonic way is to use eval

eval("-2+2")
eval("1+2-3")

If you want to implement with your way then

def f(s):
   s = s.replace('-', ' -')
   s = s.replace('+', ' +')
   l = s.split(" ")
   sum = 0
   for num in l:
       sum = sum + float(num)
   return sum
s = "4747-74+484-44"
print (f(s))
# output: 5113.0


问:
MySQL - How to set to NOW() and NULL while inserting a row into a table?
```<code>INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.
</code>```

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

答:
You can refer to the answer from this link https://stackoverflow.com/a/4852095/1712016

You can update rental_date and last_update field with null value or you can query like this.

```<code>INSERT INTO rental (rental_date, last_update, return_date)
VALUES(NOW(),NOW(),NULL)

or

INSERT INTO rental (rental_date, last_update, return_date)
VALUES(NULL,NULL,NULL)
</code>```

Body:
INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

Body:
You can refer to the answer from this link https://stackoverflow.com/a/4852095/1712016

You can update rental_date and last_update field with null value or you can query like this.

INSERT INTO rental (rental_date, last_update, return_date)
VALUES(NOW(),NOW(),NULL)

or

INSERT INTO rental (rental_date, last_update, return_date)
VALUES(NULL,NULL,NULL)


问:
RandomForest() to return probabilities of positive result as well as classification
I'm building a Random Forrest Classifier and I would like to return classification and associated probabilities. My result variable is either 1 or 0, 1 being the positive class that I want to track.

```<code>no_of_trees <- 50
rf.under <- randomForest(as.factor(result) ~ . ,
                         data=data_balanced_under,
                         importance=TRUE,
                         ntree=no_of_trees)

prediction <- predict(rf.under, df.test)
probability <- predict(rf.under, df.test, type="prob")
submit <- data.frame( predicted = prediction, actual = df.test$result)
</code>```

I wanted probability to return the probability of positive results, however I get:

```<code>> probability
           0    1
242339  1.00 0.00
3356431 1.00 0.00
138327  1.00 0.00
111327  1.00 0.00
3307151 1.00 0.00
222414  1.00 0.00
1817297 1.00 0.00
3860922 1.00 0.00
1710532 1.00 0.00
</code>```

in my output. What are these numbers on the left? I'm not sure what they are? I thought they are row numbers, but then, why aren't they indexed from 1,2,3..?
I tied to get probability[,2] which I'm assuming gives me probability of the result, but also doesn't work.

Ideally, I would like to include the probabilities in the submit data frame, but currently unable to do so.

Also, confusion matrix gives me:

```<code>confusionMatrix(data = submit$predicted, reference = df.test$result , positive="1")

#Reference
Prediction      0      1
         0 913730    160
         1  50872   8219
</code>```

Is it possible to switch this around? So that it shows positive class "1" first?

答:
probability returns the probability by class (here you have two classes so two columns).
This as been built this way to alow multiclass classification.

If you want probability of result == 1 just take the second column of probability

Since you have highly unbalanced classes (0.8% of ones) your classifier tends to predict that it is always 0... So your probability of result==1 is close to 0 for most exemples. This is why your probabilities doesn't look like probabilities.

Regarding the index of probability, it is rownames(df.test) the index of df.test. I guess you randomly splitted  df.test from df. So index doesn't start by 1.

Body:
I'm building a Random Forrest Classifier and I would like to return classification and associated probabilities. My result variable is either 1 or 0, 1 being the positive class that I want to track.

no_of_trees <- 50
rf.under <- randomForest(as.factor(result) ~ . ,
                         data=data_balanced_under,
                         importance=TRUE,
                         ntree=no_of_trees)

prediction <- predict(rf.under, df.test)
probability <- predict(rf.under, df.test, type="prob")
submit <- data.frame( predicted = prediction, actual = df.test$result)

I wanted probability to return the probability of positive results, however I get:

> probability
           0    1
242339  1.00 0.00
3356431 1.00 0.00
138327  1.00 0.00
111327  1.00 0.00
3307151 1.00 0.00
222414  1.00 0.00
1817297 1.00 0.00
3860922 1.00 0.00
1710532 1.00 0.00

in my output. What are these numbers on the left? I'm not sure what they are? I thought they are row numbers, but then, why aren't they indexed from 1,2,3..?
I tied to get probability[,2] which I'm assuming gives me probability of the result, but also doesn't work.

Ideally, I would like to include the probabilities in the submit data frame, but currently unable to do so.

Also, confusion matrix gives me:

confusionMatrix(data = submit$predicted, reference = df.test$result , positive="1")

#Reference
Prediction      0      1
         0 913730    160
         1  50872   8219

Is it possible to switch this around? So that it shows positive class "1" first?


问:
MVC Razor build onclick event dynamically to show modal
I am currently trying to attach a click handler to my  tag which will pop up my modal which has a dynamic id. I am having trouble figuring out the syntax to accomplish this- my current attempt can be found below and has a syntax error on onclick="$('#"+ @modalId + "')" (which is the part im struggling a bit with). How can I accomplish this?

```<code>var modalId = string.Format("docusign{0}", doc.Id)
<a href="#" onclick="$('#"+ @modalId + "').modal('toggle')">@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))</a>

<div id="@modalId" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background-color:#337ab7;color:#ffffff">
         <button type="button" class="close" data-dismiss="modal">×</button>
         <h4 class="modal-title">DocuSign Notice</h4>
      </div>
      <div class="modal-body form-group">
      <h5>Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below</h5>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      <a class="btn btn-default pull-left" href=@doc.DocuSignPowerFormLink>Fill Form</a>
      </div>
    </div>
  </div>
</div>
</code>```

答:
You concatenated in onclick event which is not correct you can use directly your variable inside like this $('#@modalId').modal('toggle') just this simple mistake is the issue of this error also when you are writting any c# statement inside razor must use @ before you start because there is no @ before var modalId

```<code>    @var modalId = string.Format("docusign{0}", doc.Id)
<a href="#" onclick="$('#"+ @modalId + "').modal('toggle')">@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))</a>

<div id="@modalId" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background-color:#337ab7;color:#ffffff">
         <button type="button" class="close" data-dismiss="modal">×</button>
         <h4 class="modal-title">DocuSign Notice</h4>
      </div>
      <div class="modal-body form-group">
      <h5>Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below</h5>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      <a class="btn btn-default pull-left" href=@doc.DocuSignPowerFormLink>Fill Form</a>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
I am currently trying to attach a click handler to my  tag which will pop up my modal which has a dynamic id. I am having trouble figuring out the syntax to accomplish this- my current attempt can be found below and has a syntax error on onclick="$('#"+ @modalId + "')" (which is the part im struggling a bit with). How can I accomplish this?

var modalId = string.Format("docusign{0}", doc.Id)
@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))

         <button type="button" class="close" data-dismiss="modal">×</button>

DocuSign Notice

Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below

      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      Fill Form

Body:
You concatenated in onclick event which is not correct you can use directly your variable inside like this $('#@modalId').modal('toggle') just this simple mistake is the issue of this error also when you are writting any c# statement inside razor must use @ before you start because there is no @ before var modalId

    @var modalId = string.Format("docusign{0}", doc.Id)
<a href="#" onclick="$('#"+ @modalId + "').modal('toggle')">@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))</a>

<div id="@modalId" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background-color:#337ab7;color:#ffffff">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
         <h4 class="modal-title">DocuSign Notice</h4>
      </div>
      <div class="modal-body form-group">
      <h5>Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below</h5>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      <a class="btn btn-default pull-left" href=@doc.DocuSignPowerFormLink>Fill Form</a>
      </div>
    </div>
  </div>
</div>


问:
Avoid processing same file twice in Spring Batch
I have to write a Spring Batch job as follows:

Step 1: Load an XML file from the file system and write its contents to a database staging table

Step 2: Call Oracle PL/SQL procedure to process the staging table.

(Comments on that job structure are welcome, but not the question).

In Step 1, I want to move the XML file to another directory after I have loaded it.  I want this, as much as possible, to be "transactional" with the write to the staging table.  That is, either both the writes to staging and the file move succeed, or neither does.

I feel this necessary because if (A) the staging writes happen but the file does not move, the next run will pick up the file again and process it again and (B) if the file gets moved but the staging writes do not happen, then we will have missed that file's processing.

This interface's requirements are all about robustness.  I know I could just put a step execution listener to move all the files at the end, but I want the approach that is going to guarantee that we never miss processing data and never process the same file twice.

Part of the difficulty is that I am using a MultiResourceItemReader.  I read that ChunkListener.beforeChunk() happens as part of the chunk transaction, so I tried to make a custom chunk CompletionPolicy to force chunks to complete after each change of resource (file) name, but I could not get it to work.  In any case, I would have needed an afterChunk() listener, which is not part of the transaction anyway.

I'll take any guidance on my specific questions or an expert explanation of how to robustly process files in Spring Batch (which I am only just learning).  Thanks!

答:
I have pretty similar spring batch process right now.

Spring batch fits good to your requirement.

I would recommend to start using here spring integration.
In spring integration you can configure to monitor your folder and then make it trigger batch job. There is good example in official documentation.

Then you should use powerful concept of spring batch - identifying parameters. Spring batch job runs with unique parameters, and if you put this parameter as identifying, then no other job could be spawned with same parameter (though you can restart your original job).

```<code>/**
 * Add a new String parameter for the given key.
 *
 * @param key - parameter accessor.
 * @param parameter - runtime parameter
 * @param identifying - indicates if the parameter is used as part of identifying a job instance
 * @return a reference to this object.
 */
public JobParametersBuilder addString(String key, String parameter, boolean identifying) {
    parameterMap.put(key, new JobParameter(parameter, identifying));
    return this;
}
</code>```

So here you need to ask yourself what is your uniquely identifying constraint for batch job? I would suggest it's full file path. But then you need to be sure that nobody provides different files with same filename.
Also spring integration can see if file was already seen by application and ignore it. Please check documentation on AcceptOnceFileListFilter.

If you want to have guaranteed 'transactional-like' logic in batch - then don't put it into Listeners, create a specific step which will move file. Listeners are good for suplimental logic.
In this way if this step will fail for any reason, you will still be able fix issue and to retry job.

Body:
I have pretty similar spring batch process right now.

Spring batch fits good to your requirement.

I would recommend to start using here spring integration.
In spring integration you can configure to monitor your folder and then make it trigger batch job. There is good example in official documentation.

Then you should use powerful concept of spring batch - identifying parameters. Spring batch job runs with unique parameters, and if you put this parameter as identifying, then no other job could be spawned with same parameter (though you can restart your original job).

/**
 * Add a new String parameter for the given key.
 *
 * @param key - parameter accessor.
 * @param parameter - runtime parameter
 * @param identifying - indicates if the parameter is used as part of identifying a job instance
 * @return a reference to this object.
 */
public JobParametersBuilder addString(String key, String parameter, boolean identifying) {
    parameterMap.put(key, new JobParameter(parameter, identifying));
    return this;
}

So here you need to ask yourself what is your uniquely identifying constraint for batch job? I would suggest it's full file path. But then you need to be sure that nobody provides different files with same filename.
Also spring integration can see if file was already seen by application and ignore it. Please check documentation on AcceptOnceFileListFilter.

If you want to have guaranteed 'transactional-like' logic in batch - then don't put it into Listeners, create a specific step which will move file. Listeners are good for suplimental logic.
In this way if this step will fail for any reason, you will still be able fix issue and to retry job.


问:
Unable to make Retrofit2 interface generic for all Models
I'm using Retrofit2 in my app and it works really fine, but i am trying to use a single interface for all kind of GET method requests by passing a dynamic model. When i try it using following code, it gives error at runtime

```<code>public interface LoadDataServiceTest<T> {
        @GET
        Call<T> getModel(@Url String url, @QueryMap Map<String, String> options);
    }
</code>```

Model:

```<code>public class ModelTest<T> {
    @SerializedName("status")
    private String status;
    @SerializedName("message")
    private String message;
    @SerializedName("users")
    private T data;

    public String getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
</code>```

But when i create service as following, then i get error. How can i resolve it and what is the best approach to achieve this goal.

```<code>LoadDataServiceTest<ModelTest<JsonArray>> service = retrofit.create((Class<LoadDataServiceTest<ModelTest<JsonArray>>>) (Class<?>) APIs.LoadDataServiceTest.class);
        Map<String, String> parameters = new HashMap<>();
        parameters.put("user_id",userId);
        Call<ModelTest<JsonArray>> call = service.getModel(APIs.GET_USERS, parameters);
</code>```

Error:

FATAL EXCEPTION: main
                                                                           Process: com.iu.colgatepalmolive, PID: 16808
                                                                           java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.iu.colgatepalmolive/com.iu.hfl_ccp.LoginActivity}:
  java.lang.IllegalArgumentException: Method return type must not
  include a type variable or wildcard: retrofit2.Call
                                                                               for method LoadDataServiceTest.getModel
                                                                               at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2666)
                                                                               at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
                                                                               at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                               at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                                            Caused by: java.lang.IllegalArgumentException: Method return type must
  not include a type variable or wildcard: retrofit2.Call
                                                                               for method LoadDataServiceTest.getModel
                                                                               at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:720)
                                                                               at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:711)
                                                                               at
  retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:224)
                                                                               at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:160)
                                                                               at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
                                                                               at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
                                                                               at java.lang.reflect.Proxy.invoke(Proxy.java:813)
                                                                               at $Proxy5.getModel(Unknown Source)

答:
I use following approach.
At first I have implemented custom Call

```<code>public class ProxyConvertCall<Tin,Tout> implements Call<Tout> {
    Converter<Tin,Tout> converter;
    Call<Tin> innerCall;

    public ProxyConvertCall(Call<Tin> jcall, Converter<Tin,Tout> converter){
        this.innerCall = jcall;
        this.converter = converter;
        }

    @Override
    public Response<Tout> execute() throws IOException {
        Response<Tin> response = innerCall.execute();
        if (response.isSuccessful()){
            return Response.success(converter.Convert(response.body()),response.raw());
        }
        else return Response.error(response.code(), response.errorBody());
    }

    @Override
    public void enqueue(final Callback<Tout> callback) {
        final Call<Tout> self = this;
        this.innerCall.enqueue(new Callback<Tin>() {
            @Override
            public void onResponse(Call<Tin> call, Response<Tin> response) {
                if (response.isSuccessful()){
                    callback.onResponse(self, Response.success(converter.Convert(response.body()), response.raw()));
                }
                else callback.onResponse(self, Response.error(response.code(), response.errorBody()));
            }
            @Override
            public void onFailure(Call<Tin> call, Throwable t) {
                callback.onFailure(self,t);
            }
        });

    }

    @Override
    public boolean isExecuted() {
        return innerCall.isExecuted();
    }

    @Override
    public void cancel() {
        innerCall.cancel();

    }

    @Override
    public boolean isCanceled() {
        return innerCall.isCanceled();
    }

    @Override
    public Call<Tout> clone() {
        return new ProxyConvertCall<>(innerCall,converter);
    }

    @Override
    public Request request() {
        return innerCall.request();
    }
}
</code>```

It adapts Call<Tin> to Call<Tou> using a converter.

```<code>@FunctionalInterface
public interface Converter<Tin, Tout> {
    public Tout Convert(Tin in);
}
</code>```

For your service you must create service interface, that return JsonObject for single object and JsonArray for arrays

```<code>  public interface LoadDataServiceTest {
     @GET
     public Call<JsonObject> getModelTest(@Url String url, @QueryMap Map<String, String> options);

     @GET
     public Call<JsonObject> getModel(@Url String url, @QueryMap Map<String, String> options);

     @GET
     public Call<JsonArray> getModels(@Url String url, @QueryMap Map<String, String> options);

}
</code>```

Then wrap it with generic class, with converters from JsonElement to any Type <T> and ModelTest<T>:

```<code>   public class LoadDataServiceTestGeneric<T> {
     Converter<JsonObject,ModelTest<T>> fromJsonObjectToModelTest;
     Converter<JsonObject,T> fromJsonObject;
     Converter<JsonArray,List<T>> fromJsonArray;
     LoadDataServiceTest service;

    public LoadDataServiceTestGeneric(Class<T> classOfT, LoadDataServiceTest service){
        this.service = service;
        Gson gson  = new GsonBuilder().create();
        GenericListType<T> genericListTypeOfT = new GenericListType<T>(classOfT);
        fromJsonObject = (t)->gson.fromJson(t,classOfT);
        fromJsonArray =(t)->gson.fromJson(t,genericListTypeOfT);
    }
    public Call<ModelTest<T>> getModelTest(String url, Map<String, String> options){
        return new ProxyConvertCall<>(service.getModelTest(url, options), fromJsonObjectToModelTest);
    }

    public Call<T> getModel(String url, Map<String, String> options){
        return new ProxyConvertCall<>(service.getModel(url, options), fromJsonObject);
    }

    Call<List<T>> getModels(String url, Map<String, String> options){
        return new ProxyConvertCall<>(service.getModels(url, options), fromJsonArray);
    }

}
</code>```

GenericListType is ParameterizedType. It is used for passing type parameter to gson for List<T>

```<code>import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class GenericListType<T> implements ParameterizedType {

    private Type wrapped;

    public GenericListType(Type wrapped) {
        this.wrapped = wrapped;
    }

    public Type[] getActualTypeArguments() {
        return new Type[] {wrapped};
    }

    public Type getRawType() {
        return  List.class;
    }

    public Type getOwnerType() {
        return null;
    }

}
</code>```

ModelTestType is ParameterizedType. It is used for passing type parameter to gson for ModelTestType<T>

```<code>public class ModelTestType  implements ParameterizedType {

        private Type wrapped;

        public ModelTestType(Type wrapped) {
            this.wrapped = wrapped;
        }

        public Type[] getActualTypeArguments() {
            return new Type[] {wrapped};
        }

        public Type getRawType() {
            return  ModelTest.class;
        }

        public Type getOwnerType() {
            return null;
        }

    }
</code>```

Then you can instantiate LoadDataServiceTestGeneric with type you want.

Body:
I'm using Retrofit2 in my app and it works really fine, but i am trying to use a single interface for all kind of GET method requests by passing a dynamic model. When i try it using following code, it gives error at runtime

public interface LoadDataServiceTest<T> {
        @GET
        Call<T> getModel(@Url String url, @QueryMap Map<String, String> options);
    }

Model:

public class ModelTest<T> {
    @SerializedName("status")
    private String status;
    @SerializedName("message")
    private String message;
    @SerializedName("users")
    private T data;

    public String getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}

But when i create service as following, then i get error. How can i resolve it and what is the best approach to achieve this goal.

LoadDataServiceTest<ModelTest<JsonArray>> service = retrofit.create((Class<LoadDataServiceTest<ModelTest<JsonArray>>>) (Class<?>) APIs.LoadDataServiceTest.class);
        Map<String, String> parameters = new HashMap<>();
        parameters.put("user_id",userId);
        Call<ModelTest<JsonArray>> call = service.getModel(APIs.GET_USERS, parameters);

Error:

FATAL EXCEPTION: main
                                                                           Process: com.iu.colgatepalmolive, PID: 16808
                                                                           java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.iu.colgatepalmolive/com.iu.hfl_ccp.LoginActivity}:
  java.lang.IllegalArgumentException: Method return type must not
  include a type variable or wildcard: retrofit2.Call
                                                                               for method LoadDataServiceTest.getModel
                                                                               at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2666)
                                                                               at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
                                                                               at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                               at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                                            Caused by: java.lang.IllegalArgumentException: Method return type must
  not include a type variable or wildcard: retrofit2.Call
                                                                               for method LoadDataServiceTest.getModel
                                                                               at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:720)
                                                                               at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:711)
                                                                               at
  retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:224)
                                                                               at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:160)
                                                                               at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
                                                                               at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
                                                                               at java.lang.reflect.Proxy.invoke(Proxy.java:813)
                                                                               at $Proxy5.getModel(Unknown Source)

Body:
I use following approach.
At first I have implemented custom Call

public class ProxyConvertCall<Tin,Tout> implements Call<Tout> {
    Converter<Tin,Tout> converter;
    Call<Tin> innerCall;

    public ProxyConvertCall(Call<Tin> jcall, Converter<Tin,Tout> converter){
        this.innerCall = jcall;
        this.converter = converter;
        }

    @Override
    public Response<Tout> execute() throws IOException {
        Response<Tin> response = innerCall.execute();
        if (response.isSuccessful()){
            return Response.success(converter.Convert(response.body()),response.raw());
        }
        else return Response.error(response.code(), response.errorBody());
    }

    @Override
    public void enqueue(final Callback<Tout> callback) {
        final Call<Tout> self = this;
        this.innerCall.enqueue(new Callback<Tin>() {
            @Override
            public void onResponse(Call<Tin> call, Response<Tin> response) {
                if (response.isSuccessful()){
                    callback.onResponse(self, Response.success(converter.Convert(response.body()), response.raw()));
                }
                else callback.onResponse(self, Response.error(response.code(), response.errorBody()));
            }
            @Override
            public void onFailure(Call<Tin> call, Throwable t) {
                callback.onFailure(self,t);
            }
        });

    }

    @Override
    public boolean isExecuted() {
        return innerCall.isExecuted();
    }

    @Override
    public void cancel() {
        innerCall.cancel();

    }

    @Override
    public boolean isCanceled() {
        return innerCall.isCanceled();
    }

    @Override
    public Call<Tout> clone() {
        return new ProxyConvertCall<>(innerCall,converter);
    }

    @Override
    public Request request() {
        return innerCall.request();
    }
}

It adapts Call<Tin> to Call<Tou> using a converter.

@FunctionalInterface
public interface Converter<Tin, Tout> {
    public Tout Convert(Tin in);
}

For your service you must create service interface, that return JsonObject for single object and JsonArray for arrays

  public interface LoadDataServiceTest {
     @GET
     public Call<JsonObject> getModelTest(@Url String url, @QueryMap Map<String, String> options);

     @GET
     public Call<JsonObject> getModel(@Url String url, @QueryMap Map<String, String> options);

     @GET
     public Call<JsonArray> getModels(@Url String url, @QueryMap Map<String, String> options);

}

Then wrap it with generic class, with converters from JsonElement to any Type <T> and ModelTest<T>:

   public class LoadDataServiceTestGeneric<T> {
     Converter<JsonObject,ModelTest<T>> fromJsonObjectToModelTest;
     Converter<JsonObject,T> fromJsonObject;
     Converter<JsonArray,List<T>> fromJsonArray;
     LoadDataServiceTest service;

    public LoadDataServiceTestGeneric(Class<T> classOfT, LoadDataServiceTest service){
        this.service = service;
        Gson gson  = new GsonBuilder().create();
        GenericListType<T> genericListTypeOfT = new GenericListType<T>(classOfT);
        fromJsonObject = (t)->gson.fromJson(t,classOfT);
        fromJsonArray =(t)->gson.fromJson(t,genericListTypeOfT);
    }
    public Call<ModelTest<T>> getModelTest(String url, Map<String, String> options){
        return new ProxyConvertCall<>(service.getModelTest(url, options), fromJsonObjectToModelTest);
    }

    public Call<T> getModel(String url, Map<String, String> options){
        return new ProxyConvertCall<>(service.getModel(url, options), fromJsonObject);
    }

    Call<List<T>> getModels(String url, Map<String, String> options){
        return new ProxyConvertCall<>(service.getModels(url, options), fromJsonArray);
    }

}

GenericListType is ParameterizedType. It is used for passing type parameter to gson for List<T>

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class GenericListType<T> implements ParameterizedType {

    private Type wrapped;

    public GenericListType(Type wrapped) {
        this.wrapped = wrapped;
    }

    public Type[] getActualTypeArguments() {
        return new Type[] {wrapped};
    }

    public Type getRawType() {
        return  List.class;
    }

    public Type getOwnerType() {
        return null;
    }

}

ModelTestType is ParameterizedType. It is used for passing type parameter to gson for ModelTestType<T>

public class ModelTestType  implements ParameterizedType {

        private Type wrapped;

        public ModelTestType(Type wrapped) {
            this.wrapped = wrapped;
        }

        public Type[] getActualTypeArguments() {
            return new Type[] {wrapped};
        }

        public Type getRawType() {
            return  ModelTest.class;
        }

        public Type getOwnerType() {
            return null;
        }

    }

Then you can instantiate LoadDataServiceTestGeneric with type you want.


问:
how to solve a TypeError error in rails 4 in the form?
I have a form to create vehicals and define the route corresponding to it, But it consistently gives a TypeError error, I think I am doing it wrong, please correct following is the code:

```<code><%= form_for @vehical, url_for(:action => :create, :controller => 'vehicals') do |vehical| %>
<div>
<%= vehical.label 'house power'%>
  <%= vehical.text_field 'horse_power'%>
</div>
    <div>
      <%= vehical.label 'brand' %>
      <%= vehical.text_field 'brand' %>
    </div>
    <div>
      <%= vehical.label 'model' %>
      <%= vehical.text_field 'model' %>
    </div>

    <%= vehical.submit 'create' %>
<% end %>
</code>```

routes for it:

```<code> match '/vehicals/create', :to => 'vehicals#create', :as => 'vehicals_create', :via => :post
</code>```

Error:

```<code>ActionView::Template::Error (no implicit conversion of Symbol into Integer):
    1:
    2: <%= form_for @vehical, url_for(:action => :create, :controller => 'vehicals') do |vehical| %>
    3: <div>
    4: <%= vehical.label 'house power'%>
    5:   <%= vehical.text_field 'horse_power'%>
</code>```

thanks in advance

答:
You're passing a symbol for the action value. You need a string:

```<code>url_for(action: 'create', controller: 'vehicals')
</code>```

You could also do this, but you may have to tweak the route helper if you don't have that route set up:

```<code>form_for @vehical, create_vehicle_path, method: :post
</code>```

Body:
I have a form to create vehicals and define the route corresponding to it, But it consistently gives a TypeError error, I think I am doing it wrong, please correct following is the code:

<%= form_for @vehical, url_for(:action => :create, :controller => 'vehicals') do |vehical| %>

<%= vehical.label 'house power'%>
  <%= vehical.text_field 'horse_power'%>

      <%= vehical.label 'brand' %>
      <%= vehical.text_field 'brand' %>

      <%= vehical.label 'model' %>
      <%= vehical.text_field 'model' %>

    <%= vehical.submit 'create' %>
<% end %>

routes for it:

 match '/vehicals/create', :to => 'vehicals#create', :as => 'vehicals_create', :via => :post

Error:

ActionView::Template::Error (no implicit conversion of Symbol into Integer):
    1:
    2: <%= form_for @vehical, url_for(:action => :create, :controller => 'vehicals') do |vehical| %>
    3:

    4: <%= vehical.label 'house power'%>
    5:   <%= vehical.text_field 'horse_power'%>

thanks in advance

Body:
You're passing a symbol for the action value. You need a string:

url_for(action: 'create', controller: 'vehicals')

You could also do this, but you may have to tweak the route helper if you don't have that route set up:

form_for @vehical, create_vehicle_path, method: :post


问:
Is there a Git command for adding a notice/warning before pushing to master
I have a use case where others depend on me not having a flag enabled when they pull down from master, but I need to have it enabled while working on the repo locally.

I'm hoping/wishing? that Git has a way to add a notice or warning that triggers when a push to master is requested...as a "reminder" of sorts.

So maybe my workflow could look like this:

Develop, develop, develop.

git add -A

git status

git commit -m "Added feature for..."

git checkout master

git merge that-branch

git push origin master

WARN "This is a custom message to remind you to disable the flag."

git push origin master

--> Files pushed to master after second push attempt

答:
You can force the right setting when you push, with a pre-push hook.

All you need to do is to write a script (in any language you prefer) to test whether you have the flag set to the correct setting, and if not, to fail with an error message.

You could also make a pre-commit hook that disallows commits to a certain branch (e.g. master) when the flag is set incorrectly.

However, there is one big problem with this strategy: you're encoding part of your workflow into the history of the project, every time you commit with the flag in the unpublishable state. (A similar example would be to commit temporary files generated by your IDE, and then to delete them before publishing. They would still be a part of your history (unless you rebase) and this is obviously bad.)

A better strategy would be to modify your project or tools to turn on the developer setting when a certain file is present (maybe an empty file called .development), and to ignore that file, so that it never shows up in your history, and you still get the right setting locally simply by creating that file. How difficult this is to do depends on what other technologies you're working with. I haven't figured out how to do this with cabal for example.

Another strategy which would work in every case, but be less convenient, would be to add a pre-commit hook which would always reject the developer setting. So, when you're working locally with the developer setting turned on, you'll get an error message when you commit. To commit at all, you'd have to avoid adding the unpublishable state, which might require using git add --patch, and definitely means you can't use git commit --all.


问:
Combining objects together in a one to many relationship
I have a piece of code which outputs multiple arrays of objects. How do I merge those objects together so I can get a combined object with a one to many relationship?

Plunkr link

```<code>var newGender = { gender: "Male" };
var newFruit = [{ fruits: "Apple" }, { fruits: "Orange" }, { fruits: "Kiwi" } ];
var newName = "My name";
</code>```

How do I write a function to combine these data together so I get a array like this?

```<code>[
    {
        gender: "Male",
        name: "My name",
        fruits: "Apple"
    },
    {
        gender: "Male",
        name: "My name",
        fruits: "Orange"
    },
    {
        gender: "Male",
        name: "My name",
        fruits: "Kiwi"
    }
]
</code>```

Each entry in fruits I select should be a separate object.

答:
Since fruits are the only item for which multiple values can be selected, this is pretty simple:

function combineSelections(name, gender, fruits) {
  if (!(name && gender && fruits)) {
    return [];
  }

  return fruits.map(function(fruit) {
    return {
      name: name,
      gender: gender.gender,
      fruit: fruit.fruits
    };
  });
}

var newName = 'Arun';
var newGender = {
  gender: 'male'
};
var newFruits = [
  { fruits: 'kiwi' },
  { fruits: 'dragonfruit' },
  { fruits: 'mango' }
];

console.log(combineSelections(newName, newGender, newFruits));```

Body:
I have a piece of code which outputs multiple arrays of objects. How do I merge those objects together so I can get a combined object with a one to many relationship?

Plunkr link

var newGender = { gender: "Male" };
var newFruit = [{ fruits: "Apple" }, { fruits: "Orange" }, { fruits: "Kiwi" } ];
var newName = "My name";

How do I write a function to combine these data together so I get a array like this?

[
    {
        gender: "Male",
        name: "My name",
        fruits: "Apple"
    },
    {
        gender: "Male",
        name: "My name",
        fruits: "Orange"
    },
    {
        gender: "Male",
        name: "My name",
        fruits: "Kiwi"
    }
]

Each entry in fruits I select should be a separate object.