问:
Angular 2 - Form element value set by JQuery code is not being submitted with other manually entered form data
I have designed an angular 2 app that allows a user to create a new recipe by filling in a html form. If the user manually enters values into the form, then when clicking the submit button all these values are passed to my service code. The problem is that I have a form element that is updated by a JQuery script before the submit button is pressed, but when clicking the submit button and then viewing the content of the submitted form data this form element has no value. I really do not understand why because I can physically see the value in the form on my screen. If I manually enter a value into this form element then the data is correctly submitted in the form data.

Below is my HTML (The element that has its value set by JQuery is the  element id="image_id""):-

```<code><div class="row">
  <div class="col-md-12">
    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
      <table class="table table-hover table-responsive table-bordered">
        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name" formControlName="name" type="text" class="form-control" required />
            <div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
              class="alert alert-danger">Name is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Image
          </td>
          <td>
            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input name="image_id" formControlName="image_id" type="text" class="form-control" id="image_id" />
          </td>
          <td>
        </tr>

        <tr>
          <td></td>
          <td>
            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                <span class="glyphicon glyphicon-plus"></span> Create
            </button>
          </td>
        </tr>
      </table>
    </form>
  </div>
</div>
</code>```

My Angular 2 component file looks like this:-

```<code>import { Component, Input, Output, EventEmitter, OnInit, ElementRef } from

'@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { CategoryService } from '../category.service';
import { RecipeService } from '../recipe.service';
import { DifficultyService } from '../difficulty.service';
import { IngredientService } from '../ingredient.service';
import { ImageService } from '../image.service';

import { Recipe } from '../recipe';
import { Category } from '../category';
import { Difficulty } from '../difficulty';
import { Ingredient } from '../ingredient';

import $ from "jquery";

@Component({
  selector: 'app-create-recipe',
  templateUrl: './create-recipe.component.html',
  styleUrls: ['./create-recipe.component.css'],
  providers: [RecipeService, ImageService]
})

export class CreateRecipeComponent implements OnInit {

  create_recipe_form: FormGroup;

  @Output() show_read_recipes_event = new EventEmitter();

  imageId: number;

  constructor(
    private _recipeService: RecipeService,
    private _imageService: ImageService,
    formBuilder: FormBuilder,
    private elem: ElementRef
  ) {
    this.create_recipe_form = formBuilder.group({
      name: ["", Validators.required],
      description: ["", Validators.required],
      image_id: ''

    });
  }

  ngOnInit() {

  }

  createRecipe(): void {
    this._recipeService.createRecipe(this.create_recipe_form.value)
      .subscribe(
        recipe => {
          console.log(recipe);
          this.readRecipes();
        },
        error => console.log(error)
      );
  }

  readRecipes(): void {
    this.show_read_recipes_event.emit({ title: "Read Recipes" });
  }

  uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)

          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }

  addImageIdToHtml(image){
    this.imageId = image[0];
    $("#image_id").val(this.imageId);
    $("#image_id").text(this.imageId);
  }

}
</code>```

答:
jQuery manipulates the DOM directly, but in the case of an Angular form, you create and destroy form instances, and modifying the DOM does not necessarily mean changing the form instance values. I suggest you use Angular's own function to manage form value changes. Try change your addImageIdToHtml to the following:</p>

```<code>addImageIdToHtml(image){
    this.imageId = image[0];
    this.create_recipe_form.patchValue( {
        "image_id" : this.imageId
    } );
}
</code>```

Body:
I have designed an angular 2 app that allows a user to create a new recipe by filling in a html form. If the user manually enters values into the form, then when clicking the submit button all these values are passed to my service code. The problem is that I have a form element that is updated by a JQuery script before the submit button is pressed, but when clicking the submit button and then viewing the content of the submitted form data this form element has no value. I really do not understand why because I can physically see the value in the form on my screen. If I manually enter a value into this form element then the data is correctly submitted in the form data.

Below is my HTML (The element that has its value set by JQuery is the  element id="image_id""):-

    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">

            Name

            <input name="name" formControlName="name" type="text" class="form-control" required />

Name is required

            Image

            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input name="image_id" formControlName="image_id" type="text" class="form-control" id="image_id" />

            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                 Create
            </button>

    </form>

My Angular 2 component file looks like this:-

import { Component, Input, Output, EventEmitter, OnInit, ElementRef } from

'@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { CategoryService } from '../category.service';
import { RecipeService } from '../recipe.service';
import { DifficultyService } from '../difficulty.service';
import { IngredientService } from '../ingredient.service';
import { ImageService } from '../image.service';

import { Recipe } from '../recipe';
import { Category } from '../category';
import { Difficulty } from '../difficulty';
import { Ingredient } from '../ingredient';

import $ from "jquery";

@Component({
  selector: 'app-create-recipe',
  templateUrl: './create-recipe.component.html',
  styleUrls: ['./create-recipe.component.css'],
  providers: [RecipeService, ImageService]
})

export class CreateRecipeComponent implements OnInit {

  create_recipe_form: FormGroup;

  @Output() show_read_recipes_event = new EventEmitter();

  imageId: number;

  constructor(
    private _recipeService: RecipeService,
    private _imageService: ImageService,
    formBuilder: FormBuilder,
    private elem: ElementRef
  ) {
    this.create_recipe_form = formBuilder.group({
      name: ["", Validators.required],
      description: ["", Validators.required],
      image_id: ''

    });
  }

  ngOnInit() {

  }

  createRecipe(): void {
    this._recipeService.createRecipe(this.create_recipe_form.value)
      .subscribe(
        recipe => {
          console.log(recipe);
          this.readRecipes();
        },
        error => console.log(error)
      );
  }

  readRecipes(): void {
    this.show_read_recipes_event.emit({ title: "Read Recipes" });
  }

  uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)

          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }

  addImageIdToHtml(image){
    this.imageId = image[0];
    $("#image_id").val(this.imageId);
    $("#image_id").text(this.imageId);
  }

}

Body:
jQuery manipulates the DOM directly, but in the case of an Angular form, you create and destroy form instances, and modifying the DOM does not necessarily mean changing the form instance values. I suggest you use Angular's own function to manage form value changes. Try change your addImageIdToHtml to the following:

addImageIdToHtml(image){
    this.imageId = image[0];
    this.create_recipe_form.patchValue( {
        "image_id" : this.imageId
    } );
}


来源: stackexchange

问:
Recursive function returning bool
I can't understand the following recursive function returning a  bool.

```<code> bool p(int a[], int inf, int sup) {
    if(sup==inf)
        if(a[inf]>0)
            return true;
        else
            return false;
    int m=(inf+sup)/2;
    bool left=p(a,inf,m);
    bool right=p(a,m+1,sup);
    return left && right;
}
</code>```

It should return true if all the elements in (inf, sup) are positive or else false, but I can't see how the elements that are not at the two extrema of the array are considered, since the condition that is tested is that a[inf]>0 and inf is not changed during recursion for left, while it gets values only in the right part of the array for right.

So basically, since it is different from easier recursions (like the factorial or Fibonacci) I can't understand how recursion works here: I tried to start from the base case and go on to the second step but it is unclear how to proceed.

Can anyone suggest me how to follow the recursion in this case to understand how this function returns true iff all the elements in (inf, sup) are positive?

答:
If we consider the following array

```<code>int a[5] = [2, 1, -3, 7, 4];
p(a, 0, 4)
</code>```

the call to p is divided into 2 calls as m = (0 + 4) / 2 = 2 :

bool left=p(a,inf,m); calls p(a, 0, 2)

and

bool right=p(a,m+1, sup); triggers p(a, 3, 4)

Note that the same array is being passed as argument in the subsequent calls and only the arguments inf and sup and changed.

Since in both cases inf and sup are still not equal we call calculate m :

```<code>p(a, 0, 2)       |||   p(a, 3, 4)
m = (0+2)/2 = 1  |||   m' = (3+4)/2 = 3
</code>```

2 new calls are issued in each branches:

```<code>p(a, 0, 1)  ||  p(a, 2, 2)  |||  p(a, 3, 3)  ||  p(a, 4, 4)
</code>```

When inf and sup are equal, it returns whether the element in the array is strictly positive. When it is not, it continues splitting:

```<code>p(a, 0, 0) | p(a, 1, 1) || false ||| true || true
true       | true       || false ||| true || true
</code>```

In the end, the result is a boolean AND operation on every one of them:

```<code>true && true && false && true && true = false
</code>```

I hope you could follow this.

ContentLicense: CC BY-SA 3.0

Title: Recursive function returning bool

Body:
I can't understand the following recursive function returning a  bool.

 bool p(int a[], int inf, int sup) {
    if(sup==inf)
        if(a[inf]>0)
            return true;
        else
            return false;
    int m=(inf+sup)/2;
    bool left=p(a,inf,m);
    bool right=p(a,m+1,sup);
    return left && right;
}

It should return true if all the elements in (inf, sup) are positive or else false, but I can't see how the elements that are not at the two extrema of the array are considered, since the condition that is tested is that a[inf]>0 and inf is not changed during recursion for left, while it gets values only in the right part of the array for right.

So basically, since it is different from easier recursions (like the factorial or Fibonacci) I can't understand how recursion works here: I tried to start from the base case and go on to the second step but it is unclear how to proceed.

Can anyone suggest me how to follow the recursion in this case to understand how this function returns true iff all the elements in (inf, sup) are positive?

Body:
If we consider the following array

int a[5] = [2, 1, -3, 7, 4];
p(a, 0, 4)

the call to p is divided into 2 calls as m = (0 + 4) / 2 = 2 :

bool left=p(a,inf,m); calls p(a, 0, 2)

and

bool right=p(a,m+1, sup); triggers p(a, 3, 4)

Note that the same array is being passed as argument in the subsequent calls and only the arguments inf and sup and changed.

Since in both cases inf and sup are still not equal we call calculate m :

p(a, 0, 2)       |||   p(a, 3, 4)
m = (0+2)/2 = 1  |||   m' = (3+4)/2 = 3

2 new calls are issued in each branches:

p(a, 0, 1)  ||  p(a, 2, 2)  |||  p(a, 3, 3)  ||  p(a, 4, 4)

When inf and sup are equal, it returns whether the element in the array is strictly positive. When it is not, it continues splitting:

p(a, 0, 0) | p(a, 1, 1) || false ||| true || true
true       | true       || false ||| true || true

In the end, the result is a boolean AND operation on every one of them:

true && true && false && true && true = false

I hope you could follow this.


问:
Greater Than with multiple conditions in Linq Join
I have the following SQL Server query:

```<code>SELECT *
FROM Stock s
LEFT JOIN StockOrderItem soi
    ON s.ItemNumber >= soi.StartNumber
    AND s.ItemNumber < soi.StartNumber + soi.QuantityOrdered
</code>```

Snippet of what I got so far

```<code>join l1 in _context.StockOrderItems
   on stock.ItemNumber equals l1.StartNumber into StockOrderItemGroup
from StockOrderItem in StockOrderItemGroup.DefaultIfEmpty()
</code>```

Problem here is: I cannot use "equals", it must be within a range.

How can I add multiple conditions to my "ON" clause to match my SQL query?

Thanks

答:
All joins performed by the join clause are equijoins. In other words, you can only base matches on the equality of two keys.

use a compound from clause as such instead:

```<code>var query = from s in Stock
            from l1 in _context.StockOrderItems
            where s.ItemNumber >= l1.StartNumber
            && s.ItemNumber < l1.StartNumber + l1.QuantityOrdered;
</code>```

Body:
I have the following SQL Server query:

SELECT *
FROM Stock s
LEFT JOIN StockOrderItem soi
    ON s.ItemNumber >= soi.StartNumber
    AND s.ItemNumber < soi.StartNumber + soi.QuantityOrdered

Snippet of what I got so far

join l1 in _context.StockOrderItems
   on stock.ItemNumber equals l1.StartNumber into StockOrderItemGroup
from StockOrderItem in StockOrderItemGroup.DefaultIfEmpty()

Problem here is: I cannot use "equals", it must be within a range.

How can I add multiple conditions to my "ON" clause to match my SQL query?

Thanks

Body:
All joins performed by the join clause are equijoins. In other words, you can only base matches on the equality of two keys.

use a compound from clause as such instead:

var query = from s in Stock
            from l1 in _context.StockOrderItems
            where s.ItemNumber >= l1.StartNumber
            && s.ItemNumber < l1.StartNumber + l1.QuantityOrdered;


问:
How do I write a recursive function that multiplies each character in a string by 2?
I'm trying to complete a recursive function which given a number, returns a string where the returned value has duplicate of each digit

Example: if 507, returns 550077

if the number is only 0 then just return 0

also if it is a negative number, return the negative sign only once

Example: -507 returns -550077

I haven't yet implemented anything to recognize a negative number, I was just trying to get my function to work first

so far I have:

```<code>def double(x):
    if x == 0:
        return x
    else:
        x = str(x)
        return x[0]*2 + double(x[1: ])

print(double(527))
</code>```

however this returns IndexError: string index out of range
I had it working by printing the result instead of returning the result, but the problem I am trying to solve strictly wants the result returned, not printed. What am I doing wrong?

答:
This works recursively, fixes the x==0 termination error, checks whether a character is a digit before doubling, and returns the final answer as an int (instead of a str).</p>

```<code>def double(x):
    x = str(x)
    if len(x) == 0:
        return ''
    else:
        first_char = x[0]

        # only double if it's an integer
        if first_char in map(str, range(10)):
            first_char *= 2
        return int(first_char + str(double(x[1: ])))

print(double(-527))

>>> -552277
</code>```

Body:
I'm trying to complete a recursive function which given a number, returns a string where the returned value has duplicate of each digit

Example: if 507, returns 550077

if the number is only 0 then just return 0

also if it is a negative number, return the negative sign only once

Example: -507 returns -550077

I haven't yet implemented anything to recognize a negative number, I was just trying to get my function to work first

so far I have:

def double(x):
    if x == 0:
        return x
    else:
        x = str(x)
        return x[0]*2 + double(x[1: ])

print(double(527))

however this returns IndexError: string index out of range
I had it working by printing the result instead of returning the result, but the problem I am trying to solve strictly wants the result returned, not printed. What am I doing wrong?

Body:
This works recursively, fixes the x==0 termination error, checks whether a character is a digit before doubling, and returns the final answer as an int (instead of a str).

def double(x):
    x = str(x)
    if len(x) == 0:
        return ''
    else:
        first_char = x[0]

        # only double if it's an integer
        if first_char in map(str, range(10)):
            first_char *= 2
        return int(first_char + str(double(x[1: ])))

print(double(-527))

>>> -552277


问:
index usage in mongodb when index key is repetitive
I have a collection that has repetitive value as below

```<code>{ "_id" : ObjectId("59f42f500790826aae869517"), "student_id" : 1, "type" : "exam", "score" : 38.09994424551998 }
{ "_id" : ObjectId("59f42f500790826aae869518"), "student_id" : 1, "type" : "homework", "score" : 91.98453327244025 }
{ "_id" : ObjectId("59f42f500790826aae869519"), "student_id" : 1, "type" : "quiz", "score" : 51.50397276737756 }
</code>```

Now i have made 'student_id' as an index and there are indexes with

'student_id,type' , 'student_id,score' & 'student_id,type,score'

.
When i run below query on this

```<code>db.scores.explain("executionStats").find({'student_id':{$gte:10}},{_id:0,type:0,score:0})
</code>```

I expect that only 'student_id' index should have been used as all other fields are projected 0 so i do not need them. However it tells me that the used index is 'student_id,type'. One guess i could take it that mongodb would scan each doc for a particular student_id to know the document differentiation and the best possible way would be to use "student_id,type" INDEX. However i could be wrong. So please help me to know the reason. Thanks.

答:
I just experimented with your scenario and can confirm that the order of the index creation seems to be the key here.

The explanation for that is probably that the query optimizer just looks for an index that covers the required fields (only student_id in your case). So this "find the right" index algorithm goes through the list of available indexes in the order of creation. And since the first index that it encounters (apart from the default one on the _id field...) already fits your query the optimizer decides to use it and doesn't bother looking any further.

The documentation on indexes states:

MongoDB indexes use a B-tree data structure.

and for compound indexes:

The order of fields listed in a compound index has significance. For
  instance, if a compound index consists of { userid: 1, score: -1 },
  the index sorts first by userid and then, within each userid value,
  sorts by score.

So since all your indexes have student_id as their first field, all indexes will look identical in the top part of the tree ("right below the root") and serve your query equally well.

Body:
I have a collection that has repetitive value as below

{ "_id" : ObjectId("59f42f500790826aae869517"), "student_id" : 1, "type" : "exam", "score" : 38.09994424551998 }
{ "_id" : ObjectId("59f42f500790826aae869518"), "student_id" : 1, "type" : "homework", "score" : 91.98453327244025 }
{ "_id" : ObjectId("59f42f500790826aae869519"), "student_id" : 1, "type" : "quiz", "score" : 51.50397276737756 }

Now i have made 'student_id' as an index and there are indexes with

'student_id,type' , 'student_id,score' & 'student_id,type,score'

.
When i run below query on this

db.scores.explain("executionStats").find({'student_id':{$gte:10}},{_id:0,type:0,score:0})

I expect that only 'student_id' index should have been used as all other fields are projected 0 so i do not need them. However it tells me that the used index is 'student_id,type'. One guess i could take it that mongodb would scan each doc for a particular student_id to know the document differentiation and the best possible way would be to use "student_id,type" INDEX. However i could be wrong. So please help me to know the reason. Thanks.


问:
how can create a prediction interval based on a linear model in SAS
I am trying to create a prediction interval in SAS. My SAS code is

```<code>Data M;
input y x;
datalines;
100 20
120 40
125 32
..
;
proc reg;
model y = x / clb clm alpha =0.05;
Output out=want p=Ypredicted;
run;
data want;
set want;
y1= Ypredicted;
proc reg data= want;
   model y1 = x / clm cli;
run;
</code>```

but when I run the code I could find the new Y1 how can I predict the new Y?

答:
What you're trying to do is score your model, which takes the results from the regression and uses them to estimate new values.

The most common way to do this in SAS is simply to use PROC SCORE.  This allows you to take the output of PROC REG and apply it to your data.

To use PROC SCORE, you need the OUTEST= option (think 'output estimates') on your PROC REG statement.  The dataset that you assign there will be the input to PROC SCORE, along with the new data you want to score.

As Reeza notes in comments, this is covered, along with a bunch of other ways to do this that might work better for you, in Rick Wicklin's blog post, Scoring a regression model in SAS.

Body:
I am trying to create a prediction interval in SAS. My SAS code is

Data M;
input y x;
datalines;
100 20
120 40
125 32
..
;
proc reg;
model y = x / clb clm alpha =0.05;
Output out=want p=Ypredicted;
run;
data want;
set want;
y1= Ypredicted;
proc reg data= want;
   model y1 = x / clm cli;
run;

but when I run the code I could find the new Y1 how can I predict the new Y?


问:
SQL Server : SELECT * FROM [dbo].[Table] WHERE
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

```<code>SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'
</code>```

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

答:
Here's a way that doesn't change the column. It does, however, convert it for the comparison. As you'll see, I create a computed column from your varchar column to be used with your between clause.</p>

```<code>declare @lowerDate datetime = '20170401'
declare @maxDate datetime = getdate()

if object_id('tempdb..#myTable') is not null drop table #myTable

create table #myTable(VarColumn varchar(64))
insert into #myTable
values
('12.02.2017 08:14:22'),
('30.05.2017 08:14:22')

;with cte as(
select
    VarColumn
    ,NewColumn = cast(substring(convert(varchar(20),replace(VarColumn,'.','/'),113),4,2) + '/' + substring(convert(varchar(20),replace(VarColumn,'.','/'),113),1,2) + right(convert(varchar(20),replace(VarColumn,'.','/'),113),14) as datetime)
from
    #myTable)

select *
from cte
where NewColumn between @lowerDate and @maxDate
</code>```

Body:
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

Body:
Here's a way that doesn't change the column. It does, however, convert it for the comparison. As you'll see, I create a computed column from your varchar column to be used with your between clause.

declare @lowerDate datetime = '20170401'
declare @maxDate datetime = getdate()

if object_id('tempdb..#myTable') is not null drop table #myTable

create table #myTable(VarColumn varchar(64))
insert into #myTable
values
('12.02.2017 08:14:22'),
('30.05.2017 08:14:22')

;with cte as(
select
    VarColumn
    ,NewColumn = cast(substring(convert(varchar(20),replace(VarColumn,'.','/'),113),4,2) + '/' + substring(convert(varchar(20),replace(VarColumn,'.','/'),113),1,2) + right(convert(varchar(20),replace(VarColumn,'.','/'),113),14) as datetime)
from
    #myTable)

select *
from cte
where NewColumn between @lowerDate and @maxDate


问:
Interface, abstract class and inheriting subclass with same Method, that gets different type arguments, which is used?
I have these interface and classes:

```<code>public interface AlternateLight {

     public String change(long time);
}

public abstract class AbstractLight {

    public String change(int time) {
        return "AbstractLight Method was used";
    }
}

public class DistinctAlternateLight extends AbstractLight implements AlternateLight {

    public String change(long time) {
        return "DistinctAlternateLight Method was used";
    }
}
</code>```

Now I call the method change() with following main-method:

```<code>public class WhatUsedTest {

    public static void main(String[] args) {
        AlternateLight al = new DistinctAlternateLight();
        System.out.println(al.change(100));
    }
}
</code>```

It prints "DistinctAlternateLight Method was used", but why? I thought since I didn't put a "L" behind the 100 as argument, it would call the method of the abstract class, because its method takes integers. With missing out on the "L", I guessed the compiler wouldn't handle the 100 as a long value and call the method taking longs, but it does. Why is that so?

答:
The method with the closest match to your type arguments will be used.
But for compatible numerical, the deepest declared one.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have these interface and classes:

public interface AlternateLight {

     public String change(long time);
}

public abstract class AbstractLight {

    public String change(int time) {
        return "AbstractLight Method was used";
    }
}

public class DistinctAlternateLight extends AbstractLight implements AlternateLight {

    public String change(long time) {
        return "DistinctAlternateLight Method was used";
    }
}

Now I call the method change() with following main-method:

public class WhatUsedTest {

    public static void main(String[] args) {
        AlternateLight al = new DistinctAlternateLight();
        System.out.println(al.change(100));
    }
}

It prints "DistinctAlternateLight Method was used", but why? I thought since I didn't put a "L" behind the 100 as argument, it would call the method of the abstract class, because its method takes integers. With missing out on the "L", I guessed the compiler wouldn't handle the 100 as a long value and call the method taking longs, but it does. Why is that so?


问:
Non-initialized vs null values of reference types
Is there a difference between reference type variable being non initialized or having null value?
I read somewhere that non-init means null but on other place I read something else. Thanks!</p>

答:
Note that fields are implicitly initialized to null, so this only affects variables. In pure c# you can't query the value of an uninitialized field (you need "definite assignment"), so it is a non-question.

You can do this by abusing IL though - by declaring an out parameter, and using DynamicMethod to write a method that doesn't assign it (valid in IL, but not in C#). And then you find that you will see nulls.

This in turn is due to an IL flag (.locals init) that says "clear the stack for me before entering this method" on the calling (C#) code. The C# compiler always sets this flag. If you again abuse IL to write a method that doesn't set this flag, you can probably see garbage. It could be anything. But by this point, you deserve the exceptions you get :)

Here's an example of the first (not the second, which is more complex):

```<code>delegate void AbuseMe(out object foo);
static void Main() {
    DynamicMethod dyn = new DynamicMethod("Foo",
        typeof(void), new[] { typeof(object).MakeByRefType() });
    dyn.GetILGenerator().Emit(OpCodes.Ret);
    AbuseMe method = (AbuseMe) dyn.CreateDelegate(typeof(AbuseMe));
    object obj; // this **never** gets assigned, by **any** code
    method(out obj);
    Console.WriteLine(obj == null);
}
</code>```

For clarification, the DynamicMethod code is simply writing the equivalent of this code, not legal in C#:

```<code>static void Foo(out object whatever) { } // note, whatever is not assigned
</code>```

This works because as far as the CLR is concerned out doesn't exist - there is only ref. So this isn't invalid IL - it is only the language (C#) that puts meaning to out and demands that it be assigned a value.

The problem is that Main() still has the .locals init flag; so behind the scenes obj is cleared to null (well, the entire stack space is simply wiped). If I compiled from IL without that flag (and had some other code in place to make the stack space dirty) I could see garbage. You can see more about .locals init on Liran Chen's blog.

But to answer the question:

for fields: uninitialized reference-type fields are null - guaranteed by the spec

for variables: you can't ask, but as an implementation detail (that should not be depended on): yes, it will be null even though you can't ask ;p

ContentLicense: CC BY-SA 2.5

Body:
Note that fields are implicitly initialized to null, so this only affects variables. In pure c# you can't query the value of an uninitialized field (you need "definite assignment"), so it is a non-question.

You can do this by abusing IL though - by declaring an out parameter, and using DynamicMethod to write a method that doesn't assign it (valid in IL, but not in C#). And then you find that you will see nulls.

This in turn is due to an IL flag (.locals init) that says "clear the stack for me before entering this method" on the calling (C#) code. The C# compiler always sets this flag. If you again abuse IL to write a method that doesn't set this flag, you can probably see garbage. It could be anything. But by this point, you deserve the exceptions you get :)

Here's an example of the first (not the second, which is more complex):

delegate void AbuseMe(out object foo);
static void Main() {
    DynamicMethod dyn = new DynamicMethod("Foo",
        typeof(void), new[] { typeof(object).MakeByRefType() });
    dyn.GetILGenerator().Emit(OpCodes.Ret);
    AbuseMe method = (AbuseMe) dyn.CreateDelegate(typeof(AbuseMe));
    object obj; // this **never** gets assigned, by **any** code
    method(out obj);
    Console.WriteLine(obj == null);
}

For clarification, the DynamicMethod code is simply writing the equivalent of this code, not legal in C#:

static void Foo(out object whatever) { } // note, whatever is not assigned

This works because as far as the CLR is concerned out doesn't exist - there is only ref. So this isn't invalid IL - it is only the language (C#) that puts meaning to out and demands that it be assigned a value.

The problem is that Main() still has the .locals init flag; so behind the scenes obj is cleared to null (well, the entire stack space is simply wiped). If I compiled from IL without that flag (and had some other code in place to make the stack space dirty) I could see garbage. You can see more about .locals init on Liran Chen's blog.

But to answer the question:

for fields: uninitialized reference-type fields are null - guaranteed by the spec

for variables: you can't ask, but as an implementation detail (that should not be depended on): yes, it will be null even though you can't ask ;p


问:
CDN or download into directory?
Haven't found many resources for this - If I wanted to use jQuery in my app, for example, would it be more beneficial to download jQuery into my project's directory, or to link the google CDN for use? </p>

答:
CDN -
Less Latency

Using a CDN: Using a CDN helps bring resources closer to the user by
  caching them in multiple locations around the world. Once those
  resources are cached, a user’s request only needs to travel to the
  closest Point of Presence to retrieve that data instead of going back
  to the origin server each time.

Without CDN - Offline test localhost

You can test your website on your local machine without network
  connectivity if you serve your libraries locally while in development.

Without CDN Monkey Patching

You can modify and fix certain issues in a library that create
  breaking issues in your software and host these. If you use a CDN you
  will have to use the original library's code instead thus losing these
  fixes.

Title: CDN or download into directory?


问:
Pandas Resample on Date Columns
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

```<code>import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])
</code>```

Desired Output:

```<code>   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5
</code>```

Title: Pandas Resample on Date Columns

Body:
I have a dataframe with dates as columns. I'd like to average the values from daily to a monthly level. I've tried with Time Grouper and Resample, but it doesn't like the columns names are strings and I can seem to figure out how to make columns into something like a DatetimeIndex.

My starting dataframe:

import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'],
                  index=['A', 'B'])

Desired Output:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5

Body:
Try converting the column names to date first:

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]], columns=pd.to_datetime(['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04']), index=['A', 'B'])

Hope it helps!


问:
Git: Make one branch exactly like another
I am relatively new to Git, and I'm still not very comfortable with it.  Right now, I'm looking for the command/options/magic that can make the current branch look like another branch; that is, to merge them, but when a conflict arises, to always choose the difference in the branch that is being merged into the current one.

My situation is thus; I have an stable(ish) application on the "master" branch.  I also have another branch, called "feature".  I basically want to make changes/additions/deletions to feature until I like the new feature I'm working on.  Once I feel it is ready, I want to make the master branch look identical to the feature branch.

I know this probably isn't a best practice, but as I said, I'm new to Git.  I plan on learning how to do more complicated things in the future, but for now, this is all I need.

Thanks, SO!

答:
The accepted answer ("Branches are just pointers ...") is no good for me, because not only do I need my branch to look like another branch - I need to do so by only adding commits (not losing any of the commits in the current history of my branch).

I liked this approach for making branch A look like branch B:

```<code>git checkout B
git diff A > patch_to_make_A_like_B
git checkout A
git apply patch_to_make_A_like_B
</code>```

(And rm patch_to_make_A_like_B at the end.)

Body:
The accepted answer ("Branches are just pointers ...") is no good for me, because not only do I need my branch to look like another branch - I need to do so by only adding commits (not losing any of the commits in the current history of my branch).

I liked this approach for making branch A look like branch B:

git checkout B
git diff A > patch_to_make_A_like_B
git checkout A
git apply patch_to_make_A_like_B

(And rm patch_to_make_A_like_B at the end.)


问:
What is correct method to encrypt and decrypt data in magento 2?
I am creating magento 2 custom module, where I am getting some data using API call. I need to store that data in my custom table. Before storage I need to encrypt that data. I think there is default encrypt function for that. I have used Mage::helper('Mage_Core_Helper_Data')->encrypt($value). But no success.

答:
You can use it this way:

```<code>use Magento\Framework\Encryption\EncryptorInterface as Encryptor;
</code>```

in the construct function :

```<code>$this->encryptor = $encryptor;
</code>```

then call encrypt function to encrypt:

```<code>$encrypt = $this->encryptor->encrypt($data);
</code>```

and to decrypt:

```<code>$decrypt = $this->encryptor->decrypt($data);
</code>```

Body:
You can use it this way:

use Magento\Framework\Encryption\EncryptorInterface as Encryptor;

in the construct function :

$this->encryptor = $encryptor;

then call encrypt function to encrypt:

$encrypt = $this->encryptor->encrypt($data);

and to decrypt:

$decrypt = $this->encryptor->decrypt($data);


问:
Does the order of declaration matter in Java/C#?
In C++ I can't use a method if I declare it after the calling method.

Does this order matter in other languages like Java or C#?

答:
These answers are conflicting which makes things difficult to understand. The best practice is to declare your methods, variables, etc. in a common sense chronological order so that there is no confusion and this is across all programming languages. Your main will always be first so that CAN be at the beginning or end, but still, you should start with main, and when you call a method in main it should be the next method after main and so on. This, at least to me, makes the most sense and makes the code the most readable (comments help a lot too, because let's face it, code is really gibberish). I'm not a coding expert, but I understand that the best practice with any algorithm is to break it down into as many simple steps as needed (please with comments). This doesn't make sense:

```<code>   final List<int[]> intArrays = Arrays.stream(testarray).collect(Collectors.toList());
   final List<Integer> integers = intArrays.stream().flatMap(z ->
                  Arrays.stream(z).boxed()).collect(Collectors.toList());

unless you add comments like:
final List<int[]> intArrays = Arrays.stream(testarray).collect(Collectors.toList());
// this makes a List (of ints) variable type that cannot be changed based on the stream of
//(the testarray in this case) and uses the Collector method to add the ints
//to intArrays (our variable name)
final List<Integer> integers = intArrays.stream().flatMap(z ->
                  Arrays.stream(z).boxed()).collect(Collectors.toList());
// I would have to look this up, because I honestly have no clue what it does exactly.
</code>```

Like I said, code is basically gibberish. Help yourself and anyone else that might look at your code and write it in a logical order no matter what language you use. (And again, please use comments! You'll thank me later.)

OwnerDisplayName: ThePony

LastEditorDisplayName: shoosh

Body:
These answers are conflicting which makes things difficult to understand. The best practice is to declare your methods, variables, etc. in a common sense chronological order so that there is no confusion and this is across all programming languages. Your main will always be first so that CAN be at the beginning or end, but still, you should start with main, and when you call a method in main it should be the next method after main and so on. This, at least to me, makes the most sense and makes the code the most readable (comments help a lot too, because let's face it, code is really gibberish). I'm not a coding expert, but I understand that the best practice with any algorithm is to break it down into as many simple steps as needed (please with comments). This doesn't make sense:

   final List<int[]> intArrays = Arrays.stream(testarray).collect(Collectors.toList());
   final List<Integer> integers = intArrays.stream().flatMap(z ->
                  Arrays.stream(z).boxed()).collect(Collectors.toList());

unless you add comments like:
final List<int[]> intArrays = Arrays.stream(testarray).collect(Collectors.toList());
// this makes a List (of ints) variable type that cannot be changed based on the stream of
//(the testarray in this case) and uses the Collector method to add the ints
//to intArrays (our variable name)
final List<Integer> integers = intArrays.stream().flatMap(z ->
                  Arrays.stream(z).boxed()).collect(Collectors.toList());
// I would have to look this up, because I honestly have no clue what it does exactly.

Like I said, code is basically gibberish. Help yourself and anyone else that might look at your code and write it in a logical order no matter what language you use. (And again, please use comments! You'll thank me later.)


问:
Xcode 7 Cannot load underlying module for AlamoFire 3.x (CocoaPods)
I use Alamofire 3.3 with Xcode 7.1.1, installed with Cocoapods
and I have this problem a couple of time :

Cannot load underlying module for Alamofire

here it's my Podfile :

```<code>source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.0'
use_frameworks!

target 'MyProject' do
pod 'Alamofire', '~> 3.0'
end
</code>```

I heard about the same problem with Xcode 6.3 and it helped me to
solve the problem once by cleaning project, but this time, I tryed to

Clean Project

Clean Xcode derived data and cache

update with version 3.1 3.2 and 3.3 of Alamofire

List item

... and nothing seams to work

does someone have the same troubles ? or any solution ?

答: Kill Xcode and do pod update. Open Xcode, clean and build. This should fix it.

Body:
I use Alamofire 3.3 with Xcode 7.1.1, installed with Cocoapods
and I have this problem a couple of time :

Cannot load underlying module for Alamofire

here it's my Podfile :

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.0'
use_frameworks!

target 'MyProject' do
pod 'Alamofire', '~> 3.0'
end

I heard about the same problem with Xcode 6.3 and it helped me to
solve the problem once by cleaning project, but this time, I tryed to

Clean Project

Clean Xcode derived data and cache

update with version 3.1 3.2 and 3.3 of Alamofire

List item

... and nothing seams to work

does someone have the same troubles ? or any solution ?


问:
For Loops, Application Hanging
Well I'm creating an application, I'm using for loops to basically read every pixel of an image looking for patterns in pixel color (simple stuff) Anyway for some reason my application simply locks up and never reverts back to normal. I've loop through the code time and time again without seeing any real problems.

The only thing I've noticed, is the for loop in ScanPixelsLater may be exiting early. I've commented the code as much as possible,

```<code>private Point topLeftc, bottomLeftc, topRightc, bottomRightc;

/// <summary>
/// Starts the initial looping process, designed only to loop through ONCE, ScanPixelsLater takes over
/// </summary>
/// <param name="img">Image to scan</param>
public void ScanPixels(Bitmap img)
{
    int whitePixel = 0;

    for (int y = 100; y < img.Height; y++)
    {

        for (int x = 100; x < img.Width; x++)
        {

            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                // img.SetPixel(x, y, Color.Green);
                whitePixel++;

            }
            else { whitePixel = 0; }

            if (whitePixel == 18)
            {
                whitePixel = 0;
                topLeftc = new Point(x - 18, y);
                DetectNextWhiteLine(topLeftc, img);

            }
        }
    }

}

/// <summary>
/// First creates the TopRight value via using the last pixel in x range, and using the current Y value
/// Then a Y loop is started 10 pixels down, within this loop is another X loop which scans the X range
/// If 10 consecutive white pixels are found, the TopLeft X value and the current Y value are used to map the
/// BottomLeft and BottomRight coordinates. Finally a new Point is created which starts (x = 1) and (y = currentYValue + 2)
/// The ScanPixelsLater method is then called, passing the new Point (newLocation).
///
/// </summary>
/// <param name="p">The x and y value of where the pixels were found</param>
/// <param name="img">Image being used</param>
private void DetectNextWhiteLine(Point p, Bitmap img)
{

    int whitePixel = 0;
    topRightc = new Point(img.Width, topLeftc.Y);

    for (int y = p.Y + 10; y < img.Height; y++)
    {

        for (int x = p.X - 5; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 10)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                bottomRightc = new Point(img.Width, y);
                Cords.Add(new Coordinates(topLeftc, topRightc, bottomLeftc, bottomRightc));

                Point newLocation = new Point(1, y + 2);
                calls++;
                ScanPixelsLater(newLocation, img); //rescan the image from new y axis
            }
        }
    }

}

/// <summary>
/// Loops through the pixels based on the p parameter, if 15 white pixels are found, the location (x & y) is
/// passed to the DetectNextWhiteLine method which fixes the next line with a similar number of white pixels.
/// </summary>
/// <param name="p">The Point(x,y) at which to start scanning</param>
/// <param name="img"></param>
private void ScanPixelsLater(Point p, Bitmap img)
{

    int whitePixel = 0;

    for (int y = p.Y; y < img.Height; y++)
    {

        for (int x = p.X; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 15)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                topLeftc = new Point(x - 15, y);
                calls++;
                DetectNextWhiteLine(topLeftc, img);
            }

        }
    }

    // only want this to execute after all the pixels within the entire img have been read
    // possibly executing early.

    DrawWhiteLines(img);
    AppArgs aa = new AppArgs(true);
    Change(this, aa); // custom event handler, fired behind form to update GUI

}
</code>```

答:
migrated from my comments (now deleted)

It is properly not this which causes you trouble since it never comes to normal but you should never call GetPixel in a loop. It is incredible slow to use that. Instead you can use pointers or an pixel array Search for "getpixel slow" with google or stackoverflow and a large number of solutions come up.

Updated: I have looked a little bit on the code now... In the main code (ScanPixels) which is a nested for-loop, you call DetectNextWhiteLine which is also a nested for-loop and finally this calls ScanPixelsLater which is ALSO a nested for-loop. Now you potentially got a 6-level-deep nested for loop O(n^6) which calls an relatively expensive method (GetPixel). You should only iterate over the pixels a few times. This may be why it never stops because this is potential something like 1000^6*~100 instructions :)

Title: For Loops, Application Hanging

Body:
Well I'm creating an application, I'm using for loops to basically read every pixel of an image looking for patterns in pixel color (simple stuff) Anyway for some reason my application simply locks up and never reverts back to normal. I've loop through the code time and time again without seeing any real problems.

The only thing I've noticed, is the for loop in ScanPixelsLater may be exiting early. I've commented the code as much as possible,

private Point topLeftc, bottomLeftc, topRightc, bottomRightc;

///
/// Starts the initial looping process, designed only to loop through ONCE, ScanPixelsLater takes over
///
/// <param name="img">Image to scan</param>
public void ScanPixels(Bitmap img)
{
    int whitePixel = 0;

    for (int y = 100; y < img.Height; y++)
    {

        for (int x = 100; x < img.Width; x++)
        {

            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                // img.SetPixel(x, y, Color.Green);
                whitePixel++;

            }
            else { whitePixel = 0; }

            if (whitePixel == 18)
            {
                whitePixel = 0;
                topLeftc = new Point(x - 18, y);
                DetectNextWhiteLine(topLeftc, img);

            }
        }
    }

}

///
/// First creates the TopRight value via using the last pixel in x range, and using the current Y value
/// Then a Y loop is started 10 pixels down, within this loop is another X loop which scans the X range
/// If 10 consecutive white pixels are found, the TopLeft X value and the current Y value are used to map the
/// BottomLeft and BottomRight coordinates. Finally a new Point is created which starts (x = 1) and (y = currentYValue + 2)
/// The ScanPixelsLater method is then called, passing the new Point (newLocation).
///
///
/// <param name="p">The x and y value of where the pixels were found</param>
/// <param name="img">Image being used</param>
private void DetectNextWhiteLine(Point p, Bitmap img)
{

    int whitePixel = 0;
    topRightc = new Point(img.Width, topLeftc.Y);

    for (int y = p.Y + 10; y < img.Height; y++)
    {

        for (int x = p.X - 5; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 10)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                bottomRightc = new Point(img.Width, y);
                Cords.Add(new Coordinates(topLeftc, topRightc, bottomLeftc, bottomRightc));

                Point newLocation = new Point(1, y + 2);
                calls++;
                ScanPixelsLater(newLocation, img); //rescan the image from new y axis
            }
        }
    }

}

///
/// Loops through the pixels based on the p parameter, if 15 white pixels are found, the location (x & y) is
/// passed to the DetectNextWhiteLine method which fixes the next line with a similar number of white pixels.
///
/// <param name="p">The Point(x,y) at which to start scanning</param>
/// <param name="img"></param>
private void ScanPixelsLater(Point p, Bitmap img)
{

    int whitePixel = 0;

    for (int y = p.Y; y < img.Height; y++)
    {

        for (int x = p.X; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 15)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                topLeftc = new Point(x - 15, y);
                calls++;
                DetectNextWhiteLine(topLeftc, img);
            }

        }
    }

    // only want this to execute after all the pixels within the entire img have been read
    // possibly executing early.

    DrawWhiteLines(img);
    AppArgs aa = new AppArgs(true);
    Change(this, aa); // custom event handler, fired behind form to update GUI

}


问:
Shapeless zipWithKeys: Could not find implicit parameter
I've been playing around with shapeless recently. There is this very basic thing I can't wrap my head around:

```<code>import shapeless._
import syntax.singleton._
import record._

object NotWorking {
  val result = ("value" :: HNil).zipWithKeys("key" :: HNil)
}
</code>```

I expect this snippet to output an extensible Record. But the compiler is not able to find an implicit for withKeys:

```<code>could not find implicit value for parameter withKeys: shapeless.ops.hlist.ZipWithKeys[shapeless.::[String,shapeless.HNil],shapeless.::[String,shapeless.HNil]]
[error]     ("value" :: HNil).zipWithKeys("key" :: HNil)
</code>```

It's even more confusing, as the example I took form Shapeless' test cases works perfectly:

```<code>import shapeless._
import syntax.singleton._
import record._

object ShamelesslyStolenFromTests {
  val orig =
    ("intField" ->> 1) ::
    ("boolField" ->> true) ::
    HNil

  val result = orig.values.zipWithKeys(orig.keys)
}
</code>```

What am I missing?

答:
The following code compiles:

```<code>  import shapeless._
  import syntax.singleton._
  import record._

  object FinallyWorking {
    val result = ("value" :: HNil).zipWithKeys[Witness.`"key"`.T :: HNil]("key".narrow :: HNil)
  }
</code>```

So it seems this was an issue with type inference for type parameter of the method.

Body:
I've been playing around with shapeless recently. There is this very basic thing I can't wrap my head around:

import shapeless._
import syntax.singleton._
import record._

object NotWorking {
  val result = ("value" :: HNil).zipWithKeys("key" :: HNil)
}

I expect this snippet to output an extensible Record. But the compiler is not able to find an implicit for withKeys:

could not find implicit value for parameter withKeys: shapeless.ops.hlist.ZipWithKeys[shapeless.::[String,shapeless.HNil],shapeless.::[String,shapeless.HNil]]
[error]     ("value" :: HNil).zipWithKeys("key" :: HNil)

It's even more confusing, as the example I took form Shapeless' test cases works perfectly:

import shapeless._
import syntax.singleton._
import record._

object ShamelesslyStolenFromTests {
  val orig =
    ("intField" ->> 1) ::
    ("boolField" ->> true) ::
    HNil

  val result = orig.values.zipWithKeys(orig.keys)
}

What am I missing?

Body:
The following code compiles:

  import shapeless._
  import syntax.singleton._
  import record._

  object FinallyWorking {
    val result = ("value" :: HNil).zipWithKeys[Witness.`"key"`.T :: HNil]("key".narrow :: HNil)
  }

So it seems this was an issue with type inference for type parameter of the method.


问:
Convert Column To Field Order
I am importing an excel spreadsheet into access, and requesting the user to input wchich column holds a userid and phone.  Now on the access form, they will be string values, like A & R

I am trying to then convert the alpha value to a number value, but when I use this syntax it is not giving appropriate results.  Such as the below produces @ when I would want it to produce 3 - what is the appropriate way in Access to convert Letters to Column Numbers

```<code>Sub Test()
Dim colletter As String
    colletter = "C"
    Debug.Print Chr(Val(colletter) + 64)
End Sub
</code>```

答: Sorry, but can't you simply use: =COLUMN()

Title: Convert Column To Field Order

Body:
I am importing an excel spreadsheet into access, and requesting the user to input wchich column holds a userid and phone.  Now on the access form, they will be string values, like A & R

I am trying to then convert the alpha value to a number value, but when I use this syntax it is not giving appropriate results.  Such as the below produces @ when I would want it to produce 3 - what is the appropriate way in Access to convert Letters to Column Numbers

Sub Test()
Dim colletter As String
    colletter = "C"
    Debug.Print Chr(Val(colletter) + 64)
End Sub


问:
Doesn't Linq to SQL miss the point? Aren't ORM-mappers (SubSonic, etc.) sub-optimal solutions?
I'd like the community's take on some thoughts I've had about Linq to Sql and other ORM mappers.

I like Linq to Sql and the idea of expressing data access logic (or CRUD operations in general) in your native development tongue rather than having to deal with the "impedance mismatch" between C# and SQL.  For example, to return an ObjectDataSource-compatible list of Event instances for a business layer, we use:

```<code>return db.Events.Select(c => new EventData() { EventID = c.EventID, Title = c.Title })
</code>```

If I were to implement this using old SQL-to-C# constructs, I'd have to create a Command class, add the EventID parameter (using a string to describe the "@EventID" argument), add the SQL query string to the Command class, execute the command, and then use (cast-type)nwReader["FieldName"] to pull each returned field value and assign it to a member of a newly created instance of my EventData class (yuck).

So, that is why people like Linq/SubSonic/etc. and I agree.

However, in the bigger picture I see a number of things that are wrong.  My sense is that Microsoft also sees something wrong and that is why they are killing Linq to SQL and trying to move people to Linq to Entities.  Only, I think that Microsoft is doubling-down on a bad bet.

So, what is wrong?

The problem is that there are architecture astronauts, especially at Microsoft, who look at Linq to Sql and realize that it is not a true data management tool: there are still many things you cannot do easily of comfortably in C# and they aim to fix it.  You see this manifested in the ambitions behind Linq to Entities, blog posts about the revolutionary nature of Linq and even the LinqPad challenge.

And the problem with that is that it assumes that SQL is the problem.  That is, in order to reduce a mild discomfort (impedance mismatch between SQL and C#), Microsoft has proposed the equivalent of a space suit (full isolation) when a band-aid (Linq to SQL or something similar) would do just fine.

As far as I can see, developers are quite smart enough to master the relational model and then apply it intelligently in their development efforts.  In fact, I would go one further and say that Linq to SQL, SubSonic, etc. are already too complex: the learning curve isn't that much different from mastering SQL itself.  Since, for the foreseeable future, developers must master SQL and the relational model, we're now faced with learning two query / CRUD languages.  Worse yet, Linq is often difficult to test (you don't have a query window), removes us one layer from the real work we are doing (it generates SQL), and has very clumsy support (at best) for SQL constructs like Date handling (e.g. DateDiff), "Having" and even "Group By".

What is the alternative? Personally, I don't need a different model for data access like Linq to Entities.  I'd prefer to simply pop up a window in Visual Studio, enter and validate my SQL, and then press a button to generate or supplement a C# class to encapsulate the call.   Since you already know SQL, wouldn't you prefer to just enter something like this:

```<code>Select EventID, Title From Events Where Location=@Location
</code>```

and end up with an EventData class that A) contains the EventID and Title fields as properties and B) has a factory method that takes a 'Location' string as an argument and that generates a List<EventData>?  You'd have to think carefully about the object model (the above example obviously doesn't deal with that) but the fundamental approach of still using SQL while eliminating the impedance mismatch appeals to me a great deal.

The question is: am I wrong?  Should Microsoft rewrite the SQL infrastructure so that you don't have to learn SQL / relational data management any more?  Can they rewrite the SQL infrastructure in this way? Or do you think that a very thin layer on top of SQL to eliminate the pain of setting up parameters and accessing data fields is quite sufficient?

Update I wanted to promote two links to the top because I think that they capture important aspects of what I am after.  First, CodeMonkey points out an article entitled "The Vietnam of Computer Science."  It takes a while to get started but is a very interesting read.  Second, AnSGri points to one of Joel Spolsky's more prominent pieces: The Law of Leaky Abstractions. It isn't exactly on topic but it is close and is a great read.

Update 2: I've given the "answer" to ocdecio although there are many great answers here and the choice of the "right" answer is purely subjective. In this case, his answer squared with what I think is truly the best practice given the current state of technology.  This is an area that I fully expect to evolve, however, so things may well change.  I'd like to thank everyone who contributed, I've upvoted everyone who I think gave a thoughtful answer.

答:
If you want a database to perform as it scales, it has to be designed and normalized according to database relational model best practices.

If you let the Object Model and the ORM dictate your data model, you will just end up with a poor data model which is not normalized and/or contains artifacts from the object model.

1 table = 1 class is a bad idea.

To start with you never, ever, have classes which represent many-to-many or many-to-one link tables.  These correspond to child collections in the object model - the links themselves are not objects.

If you treat your database as tables to simply hold your objects in rows (one common approach) and give the application direct access to tables, you are giving up all the benefits of defining an interface layer of database services that the database can use to protect its perimeter.

ORMs have their place, but if you use them to simply persist your objects as designed in your object model, your database will not be a relational database, and it will not be able to be used as one for the purposes of ETL, reporting, refactoring, etc.

OwnerDisplayName: Mark Brittingham

Body:
I'd like the community's take on some thoughts I've had about Linq to Sql and other ORM mappers.

I like Linq to Sql and the idea of expressing data access logic (or CRUD operations in general) in your native development tongue rather than having to deal with the "impedance mismatch" between C# and SQL.  For example, to return an ObjectDataSource-compatible list of Event instances for a business layer, we use:

return db.Events.Select(c => new EventData() { EventID = c.EventID, Title = c.Title })

If I were to implement this using old SQL-to-C# constructs, I'd have to create a Command class, add the EventID parameter (using a string to describe the "@EventID" argument), add the SQL query string to the Command class, execute the command, and then use (cast-type)nwReader["FieldName"] to pull each returned field value and assign it to a member of a newly created instance of my EventData class (yuck).

So, that is why people like Linq/SubSonic/etc. and I agree.

However, in the bigger picture I see a number of things that are wrong.  My sense is that Microsoft also sees something wrong and that is why they are killing Linq to SQL and trying to move people to Linq to Entities.  Only, I think that Microsoft is doubling-down on a bad bet.

So, what is wrong?

The problem is that there are architecture astronauts, especially at Microsoft, who look at Linq to Sql and realize that it is not a true data management tool: there are still many things you cannot do easily of comfortably in C# and they aim to fix it.  You see this manifested in the ambitions behind Linq to Entities, blog posts about the revolutionary nature of Linq and even the LinqPad challenge.

And the problem with that is that it assumes that SQL is the problem.  That is, in order to reduce a mild discomfort (impedance mismatch between SQL and C#), Microsoft has proposed the equivalent of a space suit (full isolation) when a band-aid (Linq to SQL or something similar) would do just fine.

As far as I can see, developers are quite smart enough to master the relational model and then apply it intelligently in their development efforts.  In fact, I would go one further and say that Linq to SQL, SubSonic, etc. are already too complex: the learning curve isn't that much different from mastering SQL itself.  Since, for the foreseeable future, developers must master SQL and the relational model, we're now faced with learning two query / CRUD languages.  Worse yet, Linq is often difficult to test (you don't have a query window), removes us one layer from the real work we are doing (it generates SQL), and has very clumsy support (at best) for SQL constructs like Date handling (e.g. DateDiff), "Having" and even "Group By".

What is the alternative? Personally, I don't need a different model for data access like Linq to Entities.  I'd prefer to simply pop up a window in Visual Studio, enter and validate my SQL, and then press a button to generate or supplement a C# class to encapsulate the call.   Since you already know SQL, wouldn't you prefer to just enter something like this:

Select EventID, Title From Events Where Location=@Location

and end up with an EventData class that A) contains the EventID and Title fields as properties and B) has a factory method that takes a 'Location' string as an argument and that generates a List<EventData>?  You'd have to think carefully about the object model (the above example obviously doesn't deal with that) but the fundamental approach of still using SQL while eliminating the impedance mismatch appeals to me a great deal.

The question is: am I wrong?  Should Microsoft rewrite the SQL infrastructure so that you don't have to learn SQL / relational data management any more?  Can they rewrite the SQL infrastructure in this way? Or do you think that a very thin layer on top of SQL to eliminate the pain of setting up parameters and accessing data fields is quite sufficient?

Update I wanted to promote two links to the top because I think that they capture important aspects of what I am after.  First, CodeMonkey points out an article entitled "The Vietnam of Computer Science."  It takes a while to get started but is a very interesting read.  Second, AnSGri points to one of Joel Spolsky's more prominent pieces: The Law of Leaky Abstractions. It isn't exactly on topic but it is close and is a great read.

Update 2: I've given the "answer" to ocdecio although there are many great answers here and the choice of the "right" answer is purely subjective. In this case, his answer squared with what I think is truly the best practice given the current state of technology.  This is an area that I fully expect to evolve, however, so things may well change.  I'd like to thank everyone who contributed, I've upvoted everyone who I think gave a thoughtful answer.

LastEditorDisplayName: Mark Brittingham

OwnerDisplayName: Cade Roux


问:
Why do c++ programmers use != instead of <
In c++ primer, pg 95 the author says that c++ programmers tend to use != in preference of < when writing loops.

```<code>for (vector<int>::size_type i = 0; i != 10; ++i) is preferred instead of
for (vector<int>::size_type i = 0; i < 10; ++i)
</code>```

I read the same thing in accelerated c++. Can someone explain the rationale behind this

答:
Maybe those who preffer this is because they got used to checking for null, etc... so preffer use the same != in everything.

```<code>if(x != null) { ... }

for(int i=0; i != 10; i++) { ... }
</code>```

so for those everyting tends to be !=  or ==

read !=  as  DIFFERENT/NOT EQUAL,
following the same principle as ==  is EQUAL,

Body:
In c++ primer, pg 95 the author says that c++ programmers tend to use != in preference of < when writing loops.

for (vector<int>::size_type i = 0; i != 10; ++i) is preferred instead of
for (vector<int>::size_type i = 0; i < 10; ++i)

I read the same thing in accelerated c++. Can someone explain the rationale behind this

Body:
Maybe those who preffer this is because they got used to checking for null, etc... so preffer use the same != in everything.

if(x != null) { ... }

for(int i=0; i != 10; i++) { ... }

so for those everyting tends to be !=  or ==

read !=  as  DIFFERENT/NOT EQUAL,
following the same principle as ==  is EQUAL,


问:
How to return a dictionary from a database?
I have written functions to access a database.

The table called Books has:

```<code>- a `book_id` TEXT column,
- a title TEXT column, and
- an author TEXT column.
</code>```

For the first one, run_query is a function that connects the database.

get_book_cnt_per_author is a function that returns a list of tuples in this form:

```<code>'author', number of books
</code>```

I don't know how to use the run_query function through the loop. I always got None for what I wrote.

I don't know where my problem is. I only get one book for each author.

Please tell me what is the problem.

def get_books(db, book_cnt_list, book_cnt):
    """ (str, list of tuple, int) -> list of str

```<code>Precondition: the elements in book_cnt_list are sorted
in ascending order by author name.

Return a list of all the book titles whose authors
each have book_cnt books in the database with name db
according to the book_cnt_list. The book titles should be in
ascending order for each author, but not for the entire list.
Follow ascending order across authors, that is, the order
authors appear in book_cnt_list that is already sorted by
author name.

>>> author_cnt_list = get_book_cnt_per_author("e7_database.db")
>>> books_list = get_books("e7_database.db", author_cnt_list, 10)
>>> books_list[0]
'A Christmas Carol'
>>> books_list[9]
'The Life and Adventures of Nicholas Nickleby'
>>> books_list[10]
'Disgrace'
>>> books_list[-1]
'Youth'
"""

# HINT: First figure out which authors have book_cnt books
# using the book_cnt_list.  Then, access the database db
# to retrieve the required information for those authors.

# Do not call any other of your E7 functions other than run_query.
list1 = []
for i in book_cnt_list:
    if i[1] == "book_cnt":
        list1.append(i[0])
for j in list1:
    return run_query(my_db, '''SELECT title FROM Books OREDER BY Books.title ASC WHERE Books.author = ? ''', (j))
</code>```

def create_author_dict(db):
    """ (str) -> dict of {str: list of str}

```<code>Return a dictionary that maps each author to the books they have written
according to the information in the Books table of the database
with name db.

>>> author_dict = create_author_dict('e7_database.db')
>>> author_dict['Isaac Asimov'].sort()
>>> author_dict['Isaac Asimov']
['Foundation', 'I Robot']
>>> author_dict['Maya Angelou']
['I Know Why the Caged Bird Sings']
"""
con = sqlite3.connect(db)
cur = con.cursor()

cur.execute('''SELECT author, title FROM Books WHERE Books.author = ?''')
new_list = cur.fetchall()
new_dict = {}
for i in new_list:
    key = i[0]
    value = i[1:]
    new_dict.update({key: list(value)})

con.commit()
cur.close()
con.close()

return new_dict
</code>```

答:
try changing the:

```<code>new_dict.update({key: list(value)})
</code>```

for a statement like:

```<code>new_dict[key] = new_dict.get(key, list()) + [value]
</code>```

Body:
I have written functions to access a database.

The table called Books has:

- a `book_id` TEXT column,
- a title TEXT column, and
- an author TEXT column.

For the first one, run_query is a function that connects the database.

get_book_cnt_per_author is a function that returns a list of tuples in this form:

'author', number of books

I don't know how to use the run_query function through the loop. I always got None for what I wrote.

I don't know where my problem is. I only get one book for each author.

Please tell me what is the problem.

def get_books(db, book_cnt_list, book_cnt):
    """ (str, list of tuple, int) -> list of str

Precondition: the elements in book_cnt_list are sorted
in ascending order by author name.

Return a list of all the book titles whose authors
each have book_cnt books in the database with name db
according to the book_cnt_list. The book titles should be in
ascending order for each author, but not for the entire list.
Follow ascending order across authors, that is, the order
authors appear in book_cnt_list that is already sorted by
author name.

>>> author_cnt_list = get_book_cnt_per_author("e7_database.db")
>>> books_list = get_books("e7_database.db", author_cnt_list, 10)
>>> books_list[0]
'A Christmas Carol'
>>> books_list[9]
'The Life and Adventures of Nicholas Nickleby'
>>> books_list[10]
'Disgrace'
>>> books_list[-1]
'Youth'
"""

# HINT: First figure out which authors have book_cnt books
# using the book_cnt_list.  Then, access the database db
# to retrieve the required information for those authors.

# Do not call any other of your E7 functions other than run_query.
list1 = []
for i in book_cnt_list:
    if i[1] == "book_cnt":
        list1.append(i[0])
for j in list1:
    return run_query(my_db, '''SELECT title FROM Books OREDER BY Books.title ASC WHERE Books.author = ? ''', (j))

def create_author_dict(db):
    """ (str) -> dict of {str: list of str}

Return a dictionary that maps each author to the books they have written
according to the information in the Books table of the database
with name db.

>>> author_dict = create_author_dict('e7_database.db')
>>> author_dict['Isaac Asimov'].sort()
>>> author_dict['Isaac Asimov']
['Foundation', 'I Robot']
>>> author_dict['Maya Angelou']
['I Know Why the Caged Bird Sings']
"""
con = sqlite3.connect(db)
cur = con.cursor()

cur.execute('''SELECT author, title FROM Books WHERE Books.author = ?''')
new_list = cur.fetchall()
new_dict = {}
for i in new_list:
    key = i[0]
    value = i[1:]
    new_dict.update({key: list(value)})

con.commit()
cur.close()
con.close()

return new_dict

Body:
try changing the:

new_dict.update({key: list(value)})

for a statement like:

new_dict[key] = new_dict.get(key, list()) + [value]


问:
Forward compatibility in storage size constrained protocol
I have a simple protocol consisting of lets say 4 fields:

```<code>Field-1 (4-bits)
Field-2 (6-bits)
Field-3 (4-bits)
Field-4 (2-bits)
</code>```

Currently, I organize them so they are byte-aligned as:

```<code>Field-1,Field-3,Field-2,Field-4
</code>```

In total, the message occupies 2 bytes with 0 bytes overhead.

To make this backwards compatible, so I can understand messages from a previous version I add a 1-byte version field at the beginning and it becomes:

```<code>Version-Field,Field-1,Field-3,Field-2,Field-4
</code>```

3 bytes in total with an overhead of 1 byte.

How do I add forwards compatibility such that I can add new fields in new versions of the protocol while ensuring old versions of the software can still understand the messages, with the lowest possible overhead?

答:
You'll have FC by ensuring strict BC with this rule:

New version must keep field layout known to previous versions.

If you can follow the rule, you'll automatically have both BC and FC.
Consequently, with the rule you can only add new fields by appending them to existing layout.

Let me explain with an example.
Say that you need to add these fields for version 2:

```<code>Field-5 (1-bit)
Field-6 (7-bits)
</code>```

Remember the rule, new fields can only be appended to existing layout.
So, this is version 2 message layout:

```<code>Version-Field,Field-1,Field-3,Field-2,Field-4,Field-5,Field-6
</code>```

Because the layout known to version 1 is intact, your version 1 code can read messages of any version with this (pseudocode):

function readMessageVersion1(byte[] input) {
    var msg = {};
    msg.version = input[0];

    msg.field1 = input[1] & 0x0f;
    msg.field3 = input[1] >> 4 & 0x0f;

    msg.field2 = input[2] & 0x3f;
    msg.field4 = input[2] >> 6 & 0x03;

    return msg;
}
```

<p>Version 1 doesn't need to check the version field because the known layout is unconditional.
However, version 2 and all other versions will need to check the version field.
Assuming that we use the value 2 to indicate version 2, this will do (pseudocode):</p>

<pre class="lang-js prettyprint-override"><code>function readMessageVersion2(byte[] input) {
    var msg = readMessageVersion1(input);

    //check version field
    if (msg.version < 2) return msg;

    msg.field5 = input[3] & 0x01;
    msg.field6 = input[3] >> 1 & 0x7f;

    return msg;
}
</code>```

The most important part of the code is the fact that it reuses code from the previous version and this check:

if (msg.version < 2) return msg;
```

<p>Version 3 of the code can simply follow version 2 like this:</p>

<pre class="lang-js prettyprint-override"><code>function readMessageVersion3(byte[] input) {
    var msg = readMessageVersion2(input);

    //check version field
    if (msg.version < 3) return msg;

    // read the input bytes here

    return msg;
}
</code>```

Think of it as a template for future versions.
By following the rule and the examples, any version of the protocol can read messages from any version with just 1 byte overhead.

Body:
I have a simple protocol consisting of lets say 4 fields:

Field-1 (4-bits)
Field-2 (6-bits)
Field-3 (4-bits)
Field-4 (2-bits)

Currently, I organize them so they are byte-aligned as:

Field-1,Field-3,Field-2,Field-4

In total, the message occupies 2 bytes with 0 bytes overhead.

To make this backwards compatible, so I can understand messages from a previous version I add a 1-byte version field at the beginning and it becomes:

Version-Field,Field-1,Field-3,Field-2,Field-4

3 bytes in total with an overhead of 1 byte.

How do I add forwards compatibility such that I can add new fields in new versions of the protocol while ensuring old versions of the software can still understand the messages, with the lowest possible overhead?

Body:
You'll have FC by ensuring strict BC with this rule:

New version must keep field layout known to previous versions.

If you can follow the rule, you'll automatically have both BC and FC.
Consequently, with the rule you can only add new fields by appending them to existing layout.

Let me explain with an example.
Say that you need to add these fields for version 2:

Field-5 (1-bit)
Field-6 (7-bits)

Remember the rule, new fields can only be appended to existing layout.
So, this is version 2 message layout:

Version-Field,Field-1,Field-3,Field-2,Field-4,Field-5,Field-6

Because the layout known to version 1 is intact, your version 1 code can read messages of any version with this (pseudocode):

function readMessageVersion1(byte[] input) {
    var msg = {};
    msg.version = input[0];

    msg.field1 = input[1] & 0x0f;
    msg.field3 = input[1] >> 4 & 0x0f;

    msg.field2 = input[2] & 0x3f;
    msg.field4 = input[2] >> 6 & 0x03;

    return msg;
}

Version 1 doesn't need to check the version field because the known layout is unconditional.
However, version 2 and all other versions will need to check the version field.
Assuming that we use the value 2 to indicate version 2, this will do (pseudocode):

function readMessageVersion2(byte[] input) {
    var msg = readMessageVersion1(input);

    //check version field
    if (msg.version < 2) return msg;

    msg.field5 = input[3] & 0x01;
    msg.field6 = input[3] >> 1 & 0x7f;

    return msg;
}

The most important part of the code is the fact that it reuses code from the previous version and this check:

if (msg.version < 2) return msg;

Version 3 of the code can simply follow version 2 like this:

function readMessageVersion3(byte[] input) {
    var msg = readMessageVersion2(input);

    //check version field
    if (msg.version < 3) return msg;

    // read the input bytes here

    return msg;
}

Think of it as a template for future versions.
By following the rule and the examples, any version of the protocol can read messages from any version with just 1 byte overhead.


问:
heading not extending to the end of the div
I have a heading banner that overlays across a background image for a tile. To make it responsive, I set the width to auto and it looks great on a collapsed screen (see capture below). Also, I'm using Bootstrap 4.

However, on full screen resolution, the heading background doesn't extend to the end of the div. I've tried to eliminate any padding, but I can't seem to get it to go to the end. See image.

Here's my HTML:

```<code><!--browse by category section-->
    <section id="category">
        <div class="card-header text-center">
            <h4 class="card-title">Browse Workouts by Category</h1>
        </div>
        <div class="row btn-warning">
            <div class="col-sm-2 bg-primary" id="cardio">
                <h1 class="text-center">Cardio</h1>
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
        </div>
    </section>
</code>```

and my CSS:

```<code>/*--------------*/
/*---CATEGORIES-----*/
/*--------------*/

#cardio {
    background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('../img/users/pexels-photo-460520.jpeg') no-repeat;
    background-size: cover;
    height: 300px;
}

#cardio h1 {
    margin-top: 100px;
    height: 100px;
    width: auto;
    padding-top: 25px;
    color: #fff;
    background: linear-gradient(rgba(93,139,229,0.7), rgba(93,139,229,0.7));
}
</code>```

答:
First you are missing the container div before the row. then, to force the title to be full width you need to add negative margin in order to override the padding of the outer class col-sm-2.

Avoid changing styles of bootstrap classes as I saw in other answers, this can break some of your other layout.

/*--------------*/

/*---CATEGORIES-----*/

/*--------------*/

#cardio {
  background: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('../img/users/pexels-photo-460520.jpeg') no-repeat;
  background-size: cover;
  height: 300px;
}

#cardio h1 {
  margin-top: 100px;
  height: 100px;
  margin-left:-15px;
  margin-right:-15px;
  padding-top: 25px;
  color: #fff;
  background: linear-gradient(rgba(93, 139, 229, 0.7), rgba(93, 139, 229, 0.7));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<!--browse by category section-->
<section id="category">
  <div class="card-header text-center">
    <h4 class="card-title">Browse Workouts by Category</h1>
  </div>
  <div class="container">
    <div class="row btn-warning">
      <div class="col-sm-2 bg-primary" id="cardio">
        <h1 class="text-center">Cardio</h1>
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
    </div>
  </div>
</section></code>```

Body:
I have a heading banner that overlays across a background image for a tile. To make it responsive, I set the width to auto and it looks great on a collapsed screen (see capture below). Also, I'm using Bootstrap 4.

However, on full screen resolution, the heading background doesn't extend to the end of the div. I've tried to eliminate any padding, but I can't seem to get it to go to the end. See image.

Here's my HTML:

Browse Workouts by Category

Cardio

                Hi

                Hi

                Hi

                Hi

                Hi

and my CSS:

/*--------------*/
/*---CATEGORIES-----*/
/*--------------*/

#cardio {
    background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('../img/users/pexels-photo-460520.jpeg') no-repeat;
    background-size: cover;
    height: 300px;
}

#cardio h1 {
    margin-top: 100px;
    height: 100px;
    width: auto;
    padding-top: 25px;
    color: #fff;
    background: linear-gradient(rgba(93,139,229,0.7), rgba(93,139,229,0.7));
}

Body:
First you are missing the container div before the row. then, to force the title to be full width you need to add negative margin in order to override the padding of the outer class col-sm-2.

Avoid changing styles of bootstrap classes as I saw in other answers, this can break some of your other layout.

/*--------------*/

/*---CATEGORIES-----*/

/*--------------*/

#cardio {
  background: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('../img/users/pexels-photo-460520.jpeg') no-repeat;
  background-size: cover;
  height: 300px;
}

#cardio h1 {
  margin-top: 100px;
  height: 100px;
  margin-left:-15px;
  margin-right:-15px;
  padding-top: 25px;
  color: #fff;
  background: linear-gradient(rgba(93, 139, 229, 0.7), rgba(93, 139, 229, 0.7));
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<!--browse by category section-->
<section id="category">
  <div class="card-header text-center">
    <h4 class="card-title">Browse Workouts by Category</h1>
  </div>
  <div class="container">
    <div class="row btn-warning">
      <div class="col-sm-2 bg-primary" id="cardio">
        <h1 class="text-center">Cardio</h1>
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
      <div class="col-sm-2 bg-primary">
        Hi
      </div>
    </div>
  </div>
</section>


问:
Greater Than with multiple conditions in Linq Join
I have the following SQL Server query:

```<code>SELECT *
FROM Stock s
LEFT JOIN StockOrderItem soi
    ON s.ItemNumber >= soi.StartNumber
    AND s.ItemNumber < soi.StartNumber + soi.QuantityOrdered
</code>```

Snippet of what I got so far

```<code>join l1 in _context.StockOrderItems
   on stock.ItemNumber equals l1.StartNumber into StockOrderItemGroup
from StockOrderItem in StockOrderItemGroup.DefaultIfEmpty()
</code>```

Problem here is: I cannot use "equals", it must be within a range.

How can I add multiple conditions to my "ON" clause to match my SQL query?

Thanks

答:
```<code>var query = from s in Stock
            from l1 in _context.StockOrderItems
            where s.ItemNumber >= l1.StartNumber
               && s.ItemNumber < l1.StartNumber + l1.QuantityOrdered
            [...]
</code>```

Body:
I have the following SQL Server query:

SELECT *
FROM Stock s
LEFT JOIN StockOrderItem soi
    ON s.ItemNumber >= soi.StartNumber
    AND s.ItemNumber < soi.StartNumber + soi.QuantityOrdered

Snippet of what I got so far

join l1 in _context.StockOrderItems
   on stock.ItemNumber equals l1.StartNumber into StockOrderItemGroup
from StockOrderItem in StockOrderItemGroup.DefaultIfEmpty()

Problem here is: I cannot use "equals", it must be within a range.

How can I add multiple conditions to my "ON" clause to match my SQL query?

Thanks


问:
How to get ImageView scale to fill the layout as much as the width permits
What I want is for the ImageView to scale with the same ratio to fill the layout without being cropped. Since the width is going to match first, effectively, this means scaling until the width is maximized.

My code is:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
</code>```

My layout is:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg" />

</android.support.constraint.ConstraintLayout>
</code>```

As per Android ImageView ScaleType: A Visual Guide CENTER_INSIDE should

Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

The black image is what I'm currently, and I've drawn what I believe I should be seeing instead (as you can tell, I'm the modern-day Michelangelo).

答:
I think you use wrong value. Try android:scaleType="fitXY" on xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg"
        android:scaleType="fitXY" />

</android.support.constraint.ConstraintLayout>
</code>```

You don't need set again scaleType on activity.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    //img.setScaleType(ImageView.ScaleType.ImageView.ScaleType.FIT_XY); You don't need this
}
</code>```

Body:
What I want is for the ImageView to scale with the same ratio to fill the layout without being cropped. Since the width is going to match first, effectively, this means scaling until the width is maximized.

My code is:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}

My layout is:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg" />

</android.support.constraint.ConstraintLayout>

As per Android ImageView ScaleType: A Visual Guide CENTER_INSIDE should

Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

The black image is what I'm currently, and I've drawn what I believe I should be seeing instead (as you can tell, I'm the modern-day Michelangelo).

Body:
I think you use wrong value. Try android:scaleType="fitXY" on xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg"
        android:scaleType="fitXY" />

</android.support.constraint.ConstraintLayout>

You don't need set again scaleType on activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    //img.setScaleType(ImageView.ScaleType.ImageView.ScaleType.FIT_XY); You don't need this
}