问:
How can I remove and add element on Array by index in RxJS way?
So, I have a array of "events":

let events = Rx.Observable.from([1,2,3,4,5,6,7,8,9]);
```

<p>I can add(push):</p>

<pre class="lang-js prettyprint-override"><code>let add = function(number){
  events = events.concat([number]);
}
</code>```

I can remove:

let remove = function(){
  events = events.filter(event => {
  return event != 3;
})
}
```

<p>My first question:
How can I remove and add a element by index in "RxJS" way?</p>

<pre class="lang-js prettyprint-override"><code>let removeByIndex = function(index){
  //remove by index
}

let addByIndex = function(index){
  //add by index
}
</code>```

My second question:
I need "reinvent the wheel" for all basic methods of Array on RxJS from and of?

答:
What's your purpose? Your Observable is just a publisher which is listen somewhere in your application?

In this case, you can just have a method publish where push your new array:

class EventStream {
    private numbers$: Subject<number[]> = new Subject();
    //or BehaviorSubject if you want a default value

    publish(arrayNumberToPublish: number[]): void {
        this.numbers$.next(arrayNumberToPublish);
    }

    listen(): Observable<number[]> {
        return this.numbers$;
    }
}
```
<p>In your code you listen the stream: <code>new EventStream().listen().(...)</code></p>
<p>The second possibility is you want keep the array. I use it when I want stub a CRUD API:</p>
<pre class="lang-js prettyprint-override"><code>class EventManager {
    private events: number[] = [];
    private events$: Subject<number[]> = new Subject();
    //or BehaviorSubject if you want a default value

    getAllEvents(): Observable<number[]> {
        return this.events$;
    }

    addEvent(index: number): void {
        this.events = this.events.concat(index);
        this.events$.next(this.events);
    }

    removeEvent(index: number): void {
        this.events = this.events.filter((event) => event !== index);
        this.events$.next(this.events);
    }
}

</code>```

Body:
So, I have a array of "events":

let events = Rx.Observable.from([1,2,3,4,5,6,7,8,9]);

I can add(push):

let add = function(number){
  events = events.concat([number]);
}

I can remove:

let remove = function(){
  events = events.filter(event => {
  return event != 3;
})
}

My first question:
How can I remove and add a element by index in "RxJS" way?

let removeByIndex = function(index){
  //remove by index
}

let addByIndex = function(index){
  //add by index
}

My second question:
I need "reinvent the wheel" for all basic methods of Array on RxJS from and of?

Body:
What's your purpose? Your Observable is just a publisher which is listen somewhere in your application?

In this case, you can just have a method publish where push your new array:

class EventStream {
    private numbers$: Subject<number[]> = new Subject();
    //or BehaviorSubject if you want a default value

    publish(arrayNumberToPublish: number[]): void {
        this.numbers$.next(arrayNumberToPublish);
    }

    listen(): Observable<number[]> {
        return this.numbers$;
    }
}

In your code you listen the stream: new EventStream().listen().(...)

The second possibility is you want keep the array. I use it when I want stub a CRUD API:

class EventManager {
    private events: number[] = [];
    private events$: Subject<number[]> = new Subject();
    //or BehaviorSubject if you want a default value

    getAllEvents(): Observable<number[]> {
        return this.events$;
    }

    addEvent(index: number): void {
        this.events = this.events.concat(index);
        this.events$.next(this.events);
    }

    removeEvent(index: number): void {
        this.events = this.events.filter((event) => event !== index);
        this.events$.next(this.events);
    }
}


来源: stackexchange

问:
Scenarios where automated testing is unhelpful
What are some situations where unit testing and TDD and the like are more trouble than they're worth?

Some things I've come up with are:

When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When the only practical way of verifying correctness of the code is to run it.

When you're testing visual elements of the design.

What are some other cases?

答:
```<code>* When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.
</code>```

When you need the system to be "in context" with "full data set" then what you are doing is not unit testing.  It's testing, but you strain the "unit" bit quite a lot.  You need to have smaller tests for that.  The hard thing with TDD is getting your code in such a shape that you can test it in the small.  It is valuable, but not easy.  If you do test-after (which is NOT TDD) then it's almost impossible to avoid your situation.

So when you want to test something larger than a unit (ie a method on a class) then you will want to use something like UATs or the like.  But in that scenario, you still want tests on individual functions as you would have if you practice TDD.

```<code>* When the only practical way of verifying correctness of the code is to run it.
</code>```

But the code is running in the unit test.  Do you mean when it's running in context or something else?

```<code>* When you're testing visual elements of the design.
</code>```

I thought this is what your second bullet point was getting at, but I guess not. It is hard and often unrewarding to try to test layout in UTs.  Such tests are fragile.

So it may not be valuable to use UT to do large subsystem tests or to verify screen layout in some circumstances. But even if so, it is incredibly valuable for the 90% of your work that remains.

OwnerDisplayName: Shalmanese

ContentLicense: CC BY-SA 2.5

Body:
* When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When you need the system to be "in context" with "full data set" then what you are doing is not unit testing.  It's testing, but you strain the "unit" bit quite a lot.  You need to have smaller tests for that.  The hard thing with TDD is getting your code in such a shape that you can test it in the small.  It is valuable, but not easy.  If you do test-after (which is NOT TDD) then it's almost impossible to avoid your situation.

So when you want to test something larger than a unit (ie a method on a class) then you will want to use something like UATs or the like.  But in that scenario, you still want tests on individual functions as you would have if you practice TDD.

* When the only practical way of verifying correctness of the code is to run it.

But the code is running in the unit test.  Do you mean when it's running in context or something else?

* When you're testing visual elements of the design.

I thought this is what your second bullet point was getting at, but I guess not. It is hard and often unrewarding to try to test layout in UTs.  Such tests are fragile.

So it may not be valuable to use UT to do large subsystem tests or to verify screen layout in some circumstances. But even if so, it is incredibly valuable for the 90% of your work that remains.


问:
How do you remove the cell borders in Vaadin 8 Grid?
I would like to remove the border around all the cells in Vaadin 8's Grid. I don't believe it's possible to do with code, and the css for Table doesn't apply to Grid, therefore how do you do this for Grid?</p>

答:
Please try this. Im not sure if it has to be nested, but it should work this way.</p>

```<code>.v-grid {
        .v-grid-cell {
            border: 0px;
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please try this. Im not sure if it has to be nested, but it should work this way.

.v-grid {
        .v-grid-cell {
            border: 0px;
        }
    }


问:
Why is the result of code snippt is not true according the define about classmethod in python(2.7)?
```<code>class Pizza(object):
   radius = 2
   @classmethod
   def get_radius(self):
      return self.radius
>>>print Pizza.get_radius is Pizza().get_radius
   False
</code>```

<p>I think the result is True,because the classmedthod belongs to the class object.  </p>

答:
When you instanciate Pizza you get a get_radius function which has a different id but points to the same code:

```<code>>>> id(Pizza().get_radius)
50027464
>>> id(Pizza.get_radius)
41275656
</code>```

ok the refs are different but the contents are the same:

```<code>>>> Pizza.get_radius.__func__ is Pizza().get_radius.__func__
True
</code>```

the function objects are the same and using == also yields True:

```<code>>>> Pizza().get_radius == Pizza.get_radius
True
</code>```

So, like when comparing strings or integers, or whatever, it's better to avoid is because it's too much implementation dependent, with minimal benefits (except for the singletons like None)

Body:
class Pizza(object):
   radius = 2
   @classmethod
   def get_radius(self):
      return self.radius
>>>print Pizza.get_radius is Pizza().get_radius
   False

I think the result is True,because the classmedthod belongs to the class object.

Body:
When you instanciate Pizza you get a get_radius function which has a different id but points to the same code:

>>> id(Pizza().get_radius)
50027464
>>> id(Pizza.get_radius)
41275656

ok the refs are different but the contents are the same:

>>> Pizza.get_radius.__func__ is Pizza().get_radius.__func__
True

the function objects are the same and using == also yields True:

>>> Pizza().get_radius == Pizza.get_radius
True

So, like when comparing strings or integers, or whatever, it's better to avoid is because it's too much implementation dependent, with minimal benefits (except for the singletons like None)


问:
highcharts col width and border-top
Hello I have highcharts diagram and some problem.

1) How can I set the width of my column to the width of the area of the month? (I try change "width" in CSS it's no working)

2)How to remove all borders, but the top border save? (I try change "stroke-width" in CSS it's no working)

Maybe some js config solution have for it?

I updated post using answers, it's work! Thank all.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 54.4, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

.highcharts-series rect {
    stroke-dasharray: 45, 1000;
    stroke-width: 3;
    stroke: #00ff00;
}

.highcharts-grid path {
display: none;
}</code>```

```

答:
The width can be solved with pointPadding: 0 and groupPadding: 0.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
min-width: 300px;
max-width: 800px;
height: 300px;
margin: 1em auto;
}</code>```

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

<p>Then you can add:</p>

```yAxis: [{
   gridLineWidth: 0,
   minorGridLineWidth: 0
}],
```

As @Alex did in his answer to remove the borders and lines.

Title: highcharts col width and border-top

Body:
Hello I have highcharts diagram and some problem.

1) How can I set the width of my column to the width of the area of the month? (I try change "width" in CSS it's no working)

2)How to remove all borders, but the top border save? (I try change "stroke-width" in CSS it's no working)

Maybe some js config solution have for it?

I updated post using answers, it's work! Thank all.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 54.4, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

.highcharts-series rect {
    stroke-dasharray: 45, 1000;
    stroke-width: 3;
    stroke: #00ff00;
}

.highcharts-grid path {
display: none;
}

Body:
The width can be solved with pointPadding: 0 and groupPadding: 0.

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        type: 'column'
    }],

    plotOptions: {
      column: {
      pointPadding: 0,
      groupPadding: 0,
      borderWidth: 0
      }
 }

});

#container {
min-width: 300px;
max-width: 800px;
height: 300px;
margin: 1em auto;
}

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container"></div>

Then you can add:

yAxis: [{
   gridLineWidth: 0,
   minorGridLineWidth: 0
}],

As @Alex did in his answer to remove the borders and lines.


问:
how to add default option value from dropdown using mvc?
In dropdown am fetching the value from the database i't is working fine ..i need to add <option value='-1'>Root</option> by manually which is not present in the database.

```<code><div class="col-lg-4">
   <fieldset class="form-group">
    <label class="form-label" for="exampleInput">Domain Name</label>
      @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
       @Html.ValidationMessageFor(model => Model.DomainID, null, new { @style = "color: red" })
    </fieldset>
   </div>
 <div class="col-lg-4">
     <fieldset class="form-group">
       <label class="form-label" for="exampleInput">Parent Module</label>
          <select id="ParentModuleID" class="select2-arrow" name="ParentModuleID"></select>
           @Html.ValidationMessageFor(model => Model.ParentModuleID, null, new { @style = "color: red" })
     </fieldset>
 </div>
</code>```

Jquery:

```<code>$("#DomainID").change(function () {
        var id = $(this).val();
        $("#ParentModuleID").empty();
        $.get("ParentModule_Bind", { DomainID: id }, function (data) {
            var v = "<option>--- Select Domain Name ---</option>";
            $.each(data, function (i, v1) {
                v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
            });
            $("#ParentModuleID").html(v);

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

in above jquery <option>--- Select Domain Name ---</option> i need to add root with value of -1

```<code>public JsonResult ParentModule_Bind(string DomainID)
        {
            userType type = new userType();
            DataSet ds = type.ParentModule_Bind(DomainID);
            List<SelectListItem> statelist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                statelist.Add(new SelectListItem { Text = dr["ModuleName"].ToString(), Value = dr["ModuleID"].ToString() });
            }
            return Json(statelist, JsonRequestBehavior.AllowGet);
        }
</code>```

答:
Why do any of this in the UI with jQuery?

One big problem I see is that your are mixing business logic of your list data with UI manipulation.

If this value is always needed for the ParentModel list regardless of DomainID, then I'd modify you method that returns you the list

```<code>public JsonResult ParentModule_Bind(string DomainID)
{
    userType type = new userType();
    DataSet ds = type.ParentModule_Bind(DomainID);

    //change the following line

    var statelist = new List<SelectListItem> { new SelectListItem { Text = "Root", Value = "-1" };
    foreach (DataRow dr in ds.Tables[0].Rows)
    {
       statelist.Add(new SelectListItem { Text = dr["ModuleName"].ToString(), Value = dr["ModuleID"].ToString() });
    }

    return Json(statelist, JsonRequestBehavior.AllowGet);
}
</code>```

Body:
In dropdown am fetching the value from the database i't is working fine ..i need to add <option value='-1'>Root</option> by manually which is not present in the database.

   <fieldset class="form-group">
    Domain Name
      @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
       @Html.ValidationMessageFor(model => Model.DomainID, null, new { @style = "color: red" })
    </fieldset>

     <fieldset class="form-group">
       Parent Module
          <select id="ParentModuleID" class="select2-arrow" name="ParentModuleID"></select>
           @Html.ValidationMessageFor(model => Model.ParentModuleID, null, new { @style = "color: red" })
     </fieldset>

Jquery:

$("#DomainID").change(function () {
        var id = $(this).val();
        $("#ParentModuleID").empty();
        $.get("ParentModule_Bind", { DomainID: id }, function (data) {
            var v = "<option>--- Select Domain Name ---</option>";
            $.each(data, function (i, v1) {
                v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
            });
            $("#ParentModuleID").html(v);

        });
    });

in above jquery <option>--- Select Domain Name ---</option> i need to add root with value of -1

public JsonResult ParentModule_Bind(string DomainID)
        {
            userType type = new userType();
            DataSet ds = type.ParentModule_Bind(DomainID);
            List<SelectListItem> statelist = new List<SelectListItem>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                statelist.Add(new SelectListItem { Text = dr["ModuleName"].ToString(), Value = dr["ModuleID"].ToString() });
            }
            return Json(statelist, JsonRequestBehavior.AllowGet);
        }

Body:
Why do any of this in the UI with jQuery?

One big problem I see is that your are mixing business logic of your list data with UI manipulation.

If this value is always needed for the ParentModel list regardless of DomainID, then I'd modify you method that returns you the list

public JsonResult ParentModule_Bind(string DomainID)
{
    userType type = new userType();
    DataSet ds = type.ParentModule_Bind(DomainID);

    //change the following line

    var statelist = new List<SelectListItem> { new SelectListItem { Text = "Root", Value = "-1" };
    foreach (DataRow dr in ds.Tables[0].Rows)
    {
       statelist.Add(new SelectListItem { Text = dr["ModuleName"].ToString(), Value = dr["ModuleID"].ToString() });
    }

    return Json(statelist, JsonRequestBehavior.AllowGet);
}


问:
Python: If any value(Y) from a list is smaller than a constant, remove Y's corresponding index from another list
My question is: If any value from my aList is smaller than a constant variable, I want to take index of that lower value and delete sth from a bList corresponding to that index. Shortly, I want to compare all the values in aList to a constant and if there is a lower value in aList than constant. I will get the index of these and using that index making bList[index]= 0.

Example:

Lets say

```<code>constantToCompare=8
aList=[13, 12, 11, 9, 7]
bList=[100, 200, 300, 400, 500]
</code>```

So 5th element of aList is smaller than constantToCompare

I want to make bList = [100, 200, 300, 400, 0]

By the way this constantToCompare will increase by +1 up to some  so that a loop required to do this process.

Thank you.
I hope I am clear.

答:
You can use a list comprehension to achieve this task.

```<code>constant_to_compare = 8
a_list = [13, 12, 11, 9, 7]
b_list = [100, 200, 300, 400, 500]
b_list = [element[1] if element[0] > constant_to_compare else 0 for element in zip(a_list, b_list)]
</code>```

zip together the data that belongs together and then decide whether you want to keep the original value or set it to 0.

In the question you said that the value used for the comparison will change by +1 during the processing. You can't work with this approach if constant_to_compare should change during the processing of one loop. I'm not sure if this is the case or if you want to do the whole process multiple times. Whatever it is, the "constant" part of the variable name is misleading and should be changed.

Body:
My question is: If any value from my aList is smaller than a constant variable, I want to take index of that lower value and delete sth from a bList corresponding to that index. Shortly, I want to compare all the values in aList to a constant and if there is a lower value in aList than constant. I will get the index of these and using that index making bList[index]= 0.

Example:

Lets say

constantToCompare=8
aList=[13, 12, 11, 9, 7]
bList=[100, 200, 300, 400, 500]

So 5th element of aList is smaller than constantToCompare

I want to make bList = [100, 200, 300, 400, 0]

By the way this constantToCompare will increase by +1 up to some  so that a loop required to do this process.

Thank you.
I hope I am clear.

Body:
You can use a list comprehension to achieve this task.

constant_to_compare = 8
a_list = [13, 12, 11, 9, 7]
b_list = [100, 200, 300, 400, 500]
b_list = [element[1] if element[0] > constant_to_compare else 0 for element in zip(a_list, b_list)]

zip together the data that belongs together and then decide whether you want to keep the original value or set it to 0.

In the question you said that the value used for the comparison will change by +1 during the processing. You can't work with this approach if constant_to_compare should change during the processing of one loop. I'm not sure if this is the case or if you want to do the whole process multiple times. Whatever it is, the "constant" part of the variable name is misleading and should be changed.


问:
Can't resolve all parameters for File
I am trying to implement https://ionicframework.com/docs/native/file-transfer/

Therefor I need to install https://ionicframework.com/docs/native/file/

When I use "File" in my service I get the error:

Can't resolve all parameters for File: (?, ?, ?, ?, ?).

I know that the question marks can resemble a circular reference tough I've never user my service anywhere else, nor did i use "File" before.

```<code>import {Injectable} from '@angular/core';
import {File} from "@ionic-native/file";
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';

@Injectable()
export class ImageService {

  constructor(private file: File, private transfer: FileTransfer) {

  }

  public getImagesOfSchedule() {
    const fileTransfer: FileTransferObject = this.transfer.create();
    const url = 'http://techbooster.be/wp-content/uploads/2017/11/logo-long-white.png';
    fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
      console.log('download complete: ' + entry.toURL());
    }, (error) => {
      // handle error
    });
  }

}
</code>```

app.module.ts

```<code>providers: [
    StatusBar,
    AuthenticationService,
    ScheduleService,
    ToastService,
    StorageService,
    FacebookService,
    GoogleService,
    ImageService,
    Facebook,
    GooglePlus,
    PushService,
    File, <----------------
    FileTransfer, <--------------
    Push,
    ScreenOrientation,
    {
      provide: HttpService,
      useFactory: HttpFactory,
      deps: [XHRBackend, RequestOptions]
    },
    {
      provide: HttpNoAuthService,
      useFactory: HttpFactory,
      deps: [XHRBackend, RequestOptions]
    },
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
</code>```

答:
Ok I found out that the File class automatically imported in app.module.ts was not:

```<code>import { File } from '@ionic-native/file';
</code>```

Instead it was some standard "lib.es6.d.ts" automatically imported.

So make sure you import the correct "File" class!

Title: Can't resolve all parameters for File

Body:
I am trying to implement https://ionicframework.com/docs/native/file-transfer/

Therefor I need to install https://ionicframework.com/docs/native/file/

When I use "File" in my service I get the error:

Can't resolve all parameters for File: (?, ?, ?, ?, ?).

I know that the question marks can resemble a circular reference tough I've never user my service anywhere else, nor did i use "File" before.

import {Injectable} from '@angular/core';
import {File} from "@ionic-native/file";
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';

@Injectable()
export class ImageService {

  constructor(private file: File, private transfer: FileTransfer) {

  }

  public getImagesOfSchedule() {
    const fileTransfer: FileTransferObject = this.transfer.create();
    const url = 'http://techbooster.be/wp-content/uploads/2017/11/logo-long-white.png';
    fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
      console.log('download complete: ' + entry.toURL());
    }, (error) => {
      // handle error
    });
  }

}

app.module.ts

providers: [
    StatusBar,
    AuthenticationService,
    ScheduleService,
    ToastService,
    StorageService,
    FacebookService,
    GoogleService,
    ImageService,
    Facebook,
    GooglePlus,
    PushService,
    File, <----------------
    FileTransfer, <--------------
    Push,
    ScreenOrientation,
    {
      provide: HttpService,
      useFactory: HttpFactory,
      deps: [XHRBackend, RequestOptions]
    },
    {
      provide: HttpNoAuthService,
      useFactory: HttpFactory,
      deps: [XHRBackend, RequestOptions]
    },
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}

Body:
Ok I found out that the File class automatically imported in app.module.ts was not:

import { File } from '@ionic-native/file';

Instead it was some standard "lib.es6.d.ts" automatically imported.

So make sure you import the correct "File" class!


问:
Does using tokens break REST principles
Does using tokens for authentication break REST principles, which is supposed to be stateless.

I have an application which is required to be REST and I stored some tokens in a database. Each time a user wants to do an action, they should get a token (by sending a username and a password) and send it to the server with every request.

答:
No they, don't.

A key aspect of something like the authentication header is the fact that it's orthogonal to the request itself. It's a property of the request in the same way that a Content-Type header is.

How Authentication is implemented on the back end is not germane to the discussion as long as results of the requests that submit the header are consistent. There's no reason the process of validating an authentication header can't be a stateless process in and of itself.

The presence and content of the Authentication can certainly impact what a client receives from a request, from a 403 Unauthorized response, to a limited amount of content based on whether the client is, perhaps, using an "admin" token vs. a non-privileged user.

It's also in contrast to a Cookie, which represent Session state (which is not RESTful). This is because the two headers serve different purposes and offer up different application semantics.

Title: Does using tokens break REST principles


问:
Creating an array of digits in base 10, starting from an array of words
So, starting from an array of words, I have to create an array to include the digits of each given word, written in base 10.

So if I have

```<code>s DW 12345, 20778, 4596
</code>```

the result should be this BYTE array

```<code>t DB 1, 2, 3, 4, 5, 2, 0, 7, 7, 8, 4, 5, 9, 6
</code>```

I've been suggested how to do it, I've tried implementing it, but I get the following errors

Argument to operation or instruction has illegal size"

(regarding the "push al" and "pop al" lines)

Here's the code I've tried implementing:

```<code>ASSUME cs:text_,ds:data_

data_ SEGMENT

s dw 12345, 20778, 4596
l equ $-sir
d db (l/2)*5 dup (?)

data_ ENDS

text_ SEGMENT
start:
    mov ax, data_
    mov ds, ax
    mov es, ax
    mov si, offset s
    mov di, offset d
    mov cx, l    ;storing the length of s
    mov dl, 10
    mov ax, [si] ;storing the data of si into ax so that the division can be made
    cld          ;setting the direction flag
    jmp loop1
    cloop1:
        div dl   ;divide by 10 so we can get the remainder
        push al  ;ERROR LINE ;my plan was to store the value of al into the stack, so I can store the remainder into al
        mov al, ah
        stosb    ;we add the remainder to the final line
        pop al   ;ERROR LINE ;my plan was to get the value of al from the stack and do the instruction once againq
    loop cloop1
    loop1:        ;the role of this loop is to repeat the instruction as long as there are words left (similar to while instruction in C++)
        cmp ax, 0
        jg cloop1  ;if there are words left, the code keeps on being executed
    loop loop1
    mov ax, 4c00h
    int 21h
    text_ ENDS
    end start
</code>```

And here's the idea it's based on (represented in C++):

```<code>nr=0;
while(x>0)
 {c=x%10;
  nr=nr+x*10;
  x=x/10;
 }
cout<<nr;
</code>```

Thanks in advance and sorry for any mistakes. Any advice regarding my problem would be much appreciated

答:
Your C loop is sane except for nr=nr+x*10;  I think you're converting back into an integer with reversed order of decimal digits?  That's not a useful way to think about it in asm, because you don't have a cout << nr library function available.

The usual strategy (especially if you just need to print as a string) is to start with a pointer to the end of a buffer and work towards the front.  (e.g. dec di / ... / div / add dl, '0' / mov [di], dl / test ax,ax / jnz).  See for example How do I print an integer in Assembly Level Programming without printf from the c library? for an x86-64 version.  Porting the digit-conversion loop to x86-16 with 16-bit integers is straightforward; I didn't use any x86-64 specific stuff.

So you exit the loop once your quotient becomes 0; you're done and you have your digits in printing order.  The digits are from wherever your current pointer is (di) to the end of the buffer.  Feed that to a print-string function (I think int 21h has one of those).

If you want the result in an array with fixed start position, you could just copy.  But if you only require all the digits as integers in a contiguous buffer, you can get that.  Start with the last word at the end of your allocated space for your buffer.  When you get all the digits from a word, move to the next word (sub si,2) but don't move di, so the digits from the next word are stored right before the digits from the higher-address word.  Or if you're optimizing for code-size, use lodsw and stosb.

When you're done the final word of your source array, di is pointing to the start of an array of digits.

Push as you generate and then pop in a loop is another way to deal with the div/mod algorithm generating digits in least-significant-first order.  But it needs a separate loop to pop.  And as @Fuz points out, you have to push/pop a whole 16-bit register.

Body:
So, starting from an array of words, I have to create an array to include the digits of each given word, written in base 10.

So if I have

s DW 12345, 20778, 4596

the result should be this BYTE array

t DB 1, 2, 3, 4, 5, 2, 0, 7, 7, 8, 4, 5, 9, 6

I've been suggested how to do it, I've tried implementing it, but I get the following errors

Argument to operation or instruction has illegal size"

(regarding the "push al" and "pop al" lines)

Here's the code I've tried implementing:

ASSUME cs:text_,ds:data_

data_ SEGMENT

s dw 12345, 20778, 4596
l equ $-sir
d db (l/2)*5 dup (?)

data_ ENDS

text_ SEGMENT
start:
    mov ax, data_
    mov ds, ax
    mov es, ax
    mov si, offset s
    mov di, offset d
    mov cx, l    ;storing the length of s
    mov dl, 10
    mov ax, [si] ;storing the data of si into ax so that the division can be made
    cld          ;setting the direction flag
    jmp loop1
    cloop1:
        div dl   ;divide by 10 so we can get the remainder
        push al  ;ERROR LINE ;my plan was to store the value of al into the stack, so I can store the remainder into al
        mov al, ah
        stosb    ;we add the remainder to the final line
        pop al   ;ERROR LINE ;my plan was to get the value of al from the stack and do the instruction once againq
    loop cloop1
    loop1:        ;the role of this loop is to repeat the instruction as long as there are words left (similar to while instruction in C++)
        cmp ax, 0
        jg cloop1  ;if there are words left, the code keeps on being executed
    loop loop1
    mov ax, 4c00h
    int 21h
    text_ ENDS
    end start

And here's the idea it's based on (represented in C++):

nr=0;
while(x>0)
 {c=x%10;
  nr=nr+x*10;
  x=x/10;
 }
cout<<nr;

Thanks in advance and sorry for any mistakes. Any advice regarding my problem would be much appreciated


问:
read array from plist through shell script plist buddy
I have written shell script which reads array from plist.

```<code>PLIST_PATH="./../Documentation/documentation.plist"
echo "PATH = $PLIST_PATH"
FILE_ARRAY=`/usr/libexec/PlistBuddy -c "print :'public-headers'" $PLIST_PATH`
</code>```

Now I want to retrieve all the strings from this array but i am not able to get count from this array.

please help.

答:
Any array from your command will return an array of the form -

```<code>Array {
    1
    2
}
</code>```

sed will remove first and last line, so with this -

```<code>declare -a FILE_ARRAY =($(/usr/libexec/PlistBuddy -c "print :'public-headers'" $PLIST_PATH | sed -e 1d -e '$d'))
</code>```

you will get 1 2, which you are declaring as an array in FILE_ARRAY

which you can access as - ${FILE_ARRAY[1]}

Length of such array will be - echo ${#FILE_ARRAY[@]}

Source of the answer

Body:
I have written shell script which reads array from plist.

PLIST_PATH="./../Documentation/documentation.plist"
echo "PATH = $PLIST_PATH"
FILE_ARRAY=`/usr/libexec/PlistBuddy -c "print :'public-headers'" $PLIST_PATH`

Now I want to retrieve all the strings from this array but i am not able to get count from this array.

please help.

Body:
Any array from your command will return an array of the form -

Array {
    1
    2
}

sed will remove first and last line, so with this -

declare -a FILE_ARRAY =($(/usr/libexec/PlistBuddy -c "print :'public-headers'" $PLIST_PATH | sed -e 1d -e '$d'))

you will get 1 2, which you are declaring as an array in FILE_ARRAY

which you can access as - ${FILE_ARRAY[1]}

Length of such array will be - echo ${#FILE_ARRAY[@]}

Source of the answer


问:
Regex - find text surrounded by double curly brackets ( `{{text}}` ) but not triple brackets ( '{{{text}}}' )
I am parsing email content for Handlebars.Net. Use case is like so:

```<code>string template = "{{I should be found}} but {{{I shouldn't}}}";
</code>```

I think I need to use some combination of lookaheads and lookbehinds to find these tags but I cannot get this to work. I've created a regex which is close to what I need but is not matching exactly like how I need to - [^{]({{.*}})(!?})

Any ideas?

答:
You can use this regex with a negative lookaround assertions:

```<code>(?<!{){{[^{}]+}}(?!})
</code>```

RegEx Demo

(?!}) is a negative lookahead assertion that fails the match if next character is }

(?<!{) is a negative lookbehind assertion that fails the match if previous character is {

Body:
I am parsing email content for Handlebars.Net. Use case is like so:

string template = "{{I should be found}} but {{{I shouldn't}}}";

I think I need to use some combination of lookaheads and lookbehinds to find these tags but I cannot get this to work. I've created a regex which is close to what I need but is not matching exactly like how I need to - [^{]({{.*}})(!?})

Any ideas?

Body:
You can use this regex with a negative lookaround assertions:

(?<!{){{[^{}]+}}(?!})

RegEx Demo

(?!}) is a negative lookahead assertion that fails the match if next character is }

(?<!{) is a negative lookbehind assertion that fails the match if previous character is {


问:
Build containers for dev and production environment
How do you build images for development and for production(swarm):

I am trying to have one Dockerfile for both to keep "Dockerfile implementation in one place" like inheritance:

```<code>FROM golang AS gobase
ENV APP_ENV "pro"
COPY ./app /go/src/github.com/user/myProject/app
WORKDIR /go/src/github.com/user/myProject/app

RUN go get ./
RUN go build
EXPOSE 8080

FROM gobase AS godev

ENV APP_ENV "dev"

RUN go get github.com/pilu/fresh
RUN go-wrapper download
RUN go-wrapper install

CMD [ "fresh" ]
</code>```

And then use docker-compose.dev.yml & docker-compose.pro.yml

Like for docker-compose.dev.yml:

```<code>version: '2'

services:
  godev:
    environment:
      - APP_ENV="dev"
    image: godev
</code>```

So first of all, the naming is not working.

Bonus question: how to you build an image for production - do you just compile in one container(docker run) and then copy the binary to a new container?

答:
Basically you should take one of these options:

As Munchkin stated in his answer use tags to distinguish between prod und dev. This should be your options if you really, really, really need different things in the containers. BUT this should usually not be the case. You typically always want to run the containers locally, in dev and in prod in the same way - this is the nice thing about containers! If it works locally, it will work in dev and in prod :)

Try to use the exact same build in every stage. Of course there might be differences. For example if you have a database, you probably do not want to take the production DB. Instead make your images configurable with environment-variables to fit the different configurations of your stages. This is the way you minimize the risks of different stage-builds!

If you want to read further on how to configure a docker image, you might want to read this: https://dantehranian.wordpress.com/2015/03/25/how-should-i-get-application-configuration-into-my-docker-containers/

Body:
How do you build images for development and for production(swarm):

I am trying to have one Dockerfile for both to keep "Dockerfile implementation in one place" like inheritance:

FROM golang AS gobase
ENV APP_ENV "pro"
COPY ./app /go/src/github.com/user/myProject/app
WORKDIR /go/src/github.com/user/myProject/app

RUN go get ./
RUN go build
EXPOSE 8080

FROM gobase AS godev

ENV APP_ENV "dev"

RUN go get github.com/pilu/fresh
RUN go-wrapper download
RUN go-wrapper install

CMD [ "fresh" ]

And then use docker-compose.dev.yml & docker-compose.pro.yml

Like for docker-compose.dev.yml:

version: '2'

services:
  godev:
    environment:
      - APP_ENV="dev"
    image: godev

So first of all, the naming is not working.

Bonus question: how to you build an image for production - do you just compile in one container(docker run) and then copy the binary to a new container?


问:
Dropdown not showing category of an article
I'm building a website with symfony. I'm trying to get a page to show a form with nested objects. An Artikel can have just one category. There are many artikels and many categories.

```<code>/**
 * Artikel
 *
 * @ORM\Table(name="artikel", indexes=
    {@ORM\Index(name="IDX_A4375C338C9B60D8", columns={"idartikeltype"})})
 * @ORM\Entity
 */
class Artikel
{
....
/**
 * @ORM\Column(type="integer")
 *
 */
private $idartikeltype;

/**
 * @var ArtikelCategory
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\ArtikelCategory"
   ,inversedBy="type")
 * @ORM\JoinColumn(name="idartikeltype",
   referencedColumnName="idartikeltype")
 */
private $category;

/**
 * @var integer
 *
 * @ORM\Column(name="idArtikel", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $idartikel;

......
</code>```

My class ArtikelCategory

```<code>class ArtikelCategory
{
/**
 * @var string
 * /**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Artikel",
mappedBy="category",cascade={ALL})
 *
 * @ORM\Column(name="type", type="string", length=45, nullable=false)
 */
private $type;

/**
 * @var integer
 *
 * @ORM\Column(name="idartikeltype", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $idartikeltype;

/**
 * @return string
 */
public function getType()
{
    return $this->type;
}

/**
 * @param string $type
 */
public function setType($type)
{
    $this->type = $type;
}

/**
 * @return int
 */
public function getIdartikeltype()
{
    return $this->idartikeltype;
}

/**
 * @param int $idartikeltype
 */
public function setIdartikeltype($idartikeltype)
{
    $this->idartikeltype = $idartikeltype;
}

public function __toString() {

    return $this->getType()
        ;

}

public function __construct(){
    $this->type = new ArrayCollection();
}
}
</code>```

ArtikelType

```<code>public function buildForm
( FormBuilderInterface $builder , array
    $options
        )
        {
           $builder
        ->add ('titel', TextType::class,array('label'=>'Titel'))

        ->add('datum',DateType::class,array('label'=>'Date'))

        ->add('category' ,

  EntityType::class,array
('class'=>\AppBundle\Entity\ArtikelCategory::class,'label'=>'Page',
            'query_builder'=>function(EntityRepository $er){ return $er-
>createQueryBuilder('t')->orderBy('t.type','ASC');}

        ))

        ->add('tekst',CKEditorType::class,array('label'=>'Text'))

        ->add('save',SubmitType::class,array('label'=>'Save item'))
        ;

}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array('data_class'=>'AppBundle\Entity\Artikel',));
}
</code>```

InputController

```<code>$item = $this-> getDoctrine()->getRepository(Artikel::class)->find($id);

    $form = $this->createForm(ArtikelType::class, $item);

    $form->handleRequest($request);

    if($form->isSubmitted() && $form -> isValid())
    {

        $em= $this->getDoctrine()->getManager();

        $em->persist($item);
        $em->flush();
       return $this->redirectToRoute('input');

    }

    return $this->render('input/input.html.twig', array('form'=>$form->createView(),));
</code>```

Normally the dropdown should show the category of the artikel as in the database but ...

... In my form, the dropdownlist is not showing the category of an artikel and when i persist the artikel, the new category is not saved.

Icant figure this one out! Help.

答:
Mea Culpa,  when i read Association Mapping  , It got me thinking. Now i know i'm using a Many-to-One Unidirectional association.
The rest was a piece of cake....

Thx.

Body:
I'm building a website with symfony. I'm trying to get a page to show a form with nested objects. An Artikel can have just one category. There are many artikels and many categories.

/**
 * Artikel
 *
 * @ORM\Table(name="artikel", indexes=
    {@ORM\Index(name="IDX_A4375C338C9B60D8", columns={"idartikeltype"})})
 * @ORM\Entity
 */
class Artikel
{
....
/**
 * @ORM\Column(type="integer")
 *
 */
private $idartikeltype;

/**
 * @var ArtikelCategory
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\ArtikelCategory"
   ,inversedBy="type")
 * @ORM\JoinColumn(name="idartikeltype",
   referencedColumnName="idartikeltype")
 */
private $category;

/**
 * @var integer
 *
 * @ORM\Column(name="idArtikel", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $idartikel;

......

My class ArtikelCategory

class ArtikelCategory
{
/**
 * @var string
 * /**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Artikel",
mappedBy="category",cascade={ALL})
 *
 * @ORM\Column(name="type", type="string", length=45, nullable=false)
 */
private $type;

/**
 * @var integer
 *
 * @ORM\Column(name="idartikeltype", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $idartikeltype;

/**
 * @return string
 */
public function getType()
{
    return $this->type;
}

/**
 * @param string $type
 */
public function setType($type)
{
    $this->type = $type;
}

/**
 * @return int
 */
public function getIdartikeltype()
{
    return $this->idartikeltype;
}

/**
 * @param int $idartikeltype
 */
public function setIdartikeltype($idartikeltype)
{
    $this->idartikeltype = $idartikeltype;
}

public function __toString() {

    return $this->getType()
        ;

}

public function __construct(){
    $this->type = new ArrayCollection();
}
}

ArtikelType

public function buildForm
( FormBuilderInterface $builder , array
    $options
        )
        {
           $builder
        ->add ('titel', TextType::class,array('label'=>'Titel'))

        ->add('datum',DateType::class,array('label'=>'Date'))

        ->add('category' ,

  EntityType::class,array
('class'=>\AppBundle\Entity\ArtikelCategory::class,'label'=>'Page',
            'query_builder'=>function(EntityRepository $er){ return $er-
>createQueryBuilder('t')->orderBy('t.type','ASC');}

        ))

        ->add('tekst',CKEditorType::class,array('label'=>'Text'))

        ->add('save',SubmitType::class,array('label'=>'Save item'))
        ;

}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array('data_class'=>'AppBundle\Entity\Artikel',));
}

InputController

$item = $this-> getDoctrine()->getRepository(Artikel::class)->find($id);

    $form = $this->createForm(ArtikelType::class, $item);

    $form->handleRequest($request);

    if($form->isSubmitted() && $form -> isValid())
    {

        $em= $this->getDoctrine()->getManager();

        $em->persist($item);
        $em->flush();
       return $this->redirectToRoute('input');

    }

    return $this->render('input/input.html.twig', array('form'=>$form->createView(),));

Normally the dropdown should show the category of the artikel as in the database but ...

... In my form, the dropdownlist is not showing the category of an artikel and when i persist the artikel, the new category is not saved.

Icant figure this one out! Help.


问:
Git push and commiter
when I make a push to GIT (Gitlab) repo in the commits I see that commit has been made by user set in 'user.email' and 'user.name'.

Why does it happen? I think that information about user, should be taken from Gitlab profile.
Now it's possible to spoof our identification.

答:
The answer by cdhowie (especially the 2nd point) addresses why it isn't done differently.  I would add for clarity that committer and author information are created by git - not by gitlab or any other hosting environment - when the commit is initially created in someone's local repository.  So gitlab-verified information wouldn't be available unless the developer happens to sync their local config with it, and if your concern is someone "spoofing" identities then obviously you don't trust the developer to do that.

But that leads to the real reason I decided to add an answer:  What I haven't seen anyone address is your concern about identity.  The committer and author name and email are not, and were never designed to be, a secure way of linking work to its creator.  If you need someone to vouch for a commit in a secure way, then you need to use signed commits.

Title: Git push and commiter


答:
Since you're a beginner, I'll try to break down the steps clearly. You want to iterate through aList. Since you care about the index of each element as well as the element itself, you'll want to use enumerate:

```<code>for idx, val in enumerate(aList):
</code>```

Inside this loop, you'll be able to use idx to get the value of the current index and val to get the value of the element you're currently looking at. Then you want to check if val is less than a constant:

```<code>for idx, val in enumerate(aList):
   if val < constantToCompare:
</code>```

And if it is, set the corresponding element in bList to zero:

```<code>for idx, val in enumerate(aList):
   if val < constantToCompare:
      bList[idx] = 0
</code>```

For a more concise look, you can instead use a list comprehension (a fast way to create a list):

```<code>bList = [bList[idx] for idx, val in enumerate(aList) if val >= constantToCompare else 0]
</code>```

I'm not sure what you mean about constantToCompare increasing. If you want to do this several times, you can wrap it all in another loop:

```<code>for constantToCompare in range(start_val, end_val+1):
   bList = [bList[idx] for idx, val in enumerate(aList) if val >= constantToCompare else 0]
</code>```

If you want it to increase as you go through the list, you can add another line to the loop:

```<code>for idx, val in enumerate(aList):
   if val < constantToCompare:
      bList[idx] = 0
   constantToCompare += 1
</code>```

I used the list comprehension for conciseness, but in actual code I might prefer the longer version for readability.

Hope this helps!

Title: Python: If any value(Y) from a list is smaller than a constant, remove Y's corresponding index from another list

Body:
Since you're a beginner, I'll try to break down the steps clearly. You want to iterate through aList. Since you care about the index of each element as well as the element itself, you'll want to use enumerate:

for idx, val in enumerate(aList):

Inside this loop, you'll be able to use idx to get the value of the current index and val to get the value of the element you're currently looking at. Then you want to check if val is less than a constant:

for idx, val in enumerate(aList):
   if val < constantToCompare:

And if it is, set the corresponding element in bList to zero:

for idx, val in enumerate(aList):
   if val < constantToCompare:
      bList[idx] = 0

For a more concise look, you can instead use a list comprehension (a fast way to create a list):

bList = [bList[idx] for idx, val in enumerate(aList) if val >= constantToCompare else 0]

I'm not sure what you mean about constantToCompare increasing. If you want to do this several times, you can wrap it all in another loop:

for constantToCompare in range(start_val, end_val+1):
   bList = [bList[idx] for idx, val in enumerate(aList) if val >= constantToCompare else 0]

If you want it to increase as you go through the list, you can add another line to the loop:

for idx, val in enumerate(aList):
   if val < constantToCompare:
      bList[idx] = 0
   constantToCompare += 1

I used the list comprehension for conciseness, but in actual code I might prefer the longer version for readability.

Hope this helps!


问:
Replace cache path on selected objects (Maya+Python)

Hi, I need to repath a lot of cache files in Maya but I'm not being able to access the cache attributes to select cache path base directory and set it to the final cache folder. Please, help!
</p>

答:
here is a solution to get path for abc cache :

```<code>shape = cmds.ls(sl=True, dag=True, type="mesh", ni=True) # just to get the mesh shape under selection
abc = cmds.listConnections(shape, type='AlembicNode') # find the alembic node
cache_path = cmds.getAttr('{0}.{1}'.format(abc[0],'abc_File') ) # get the path
</code>```

for geo cache, attributes are both :

.cacheName
.cachePath

Body:
here is a solution to get path for abc cache :

shape = cmds.ls(sl=True, dag=True, type="mesh", ni=True) # just to get the mesh shape under selection
abc = cmds.listConnections(shape, type='AlembicNode') # find the alembic node
cache_path = cmds.getAttr('{0}.{1}'.format(abc[0],'abc_File') ) # get the path

for geo cache, attributes are both :

.cacheName
.cachePath


问:
Need help with some real estate math in java
Need help with some real estate math in java this blows up each time</p>

```<code>public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // This app total real estate fees for a client selling a house

        Button button = (Button) findViewById(R.id.Button01);

         //  Sample data for priceText 360000
        final EditText priceText = (EditText) findViewById(R.id.EditText01);
        // Sample data for rateText .04
        final EditText rateText = (EditText) findViewById(R.id.EditText02);

        button.setOnClickListener(new OnClickListener()
 {
 public void onClick(View v)
 {
 Toast.makeText(jsclosingcost.this, "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT)
                //  Sample data for priceText 360000
  float fPrice=Float.parseFloat(priceText.getText().toString() + "");
                 // Sample data for rateText .04
  float fRate=Float.parseFloat(rateText.getText().toString() + "");

  float fRealEsate = fPrice * fRate;
  Toast.makeText(jsclosingcost.this, "Real Estate Brokerage Fee: " + fRealEsate, Toast.LENGTH_SHORT).show();
 }
 });

    }
</code>```

答:
Like others have said, "This blows up every time" doesn't give us a lot to go on. That said, I tossed this into a test project and found that it doesn't compile - you're missing a semicolon at the end of this line:

```<code>
Toast.makeText(jsclosingcost.this, "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT)
</code>```

By adding a semicolon to that line, I was able to compile this and run it without issue.

A few things of note, however...

You don't need to append an empty string to your strings here:

```<code>
float fPrice=Float.parseFloat(priceText.getText().toString() + "");
float fRate=Float.parseFloat(rateText.getText().toString() + "");
</code>```

Appending an empty string in this way is an old trick to ensure things are cast as String objects, but by calling toString on the objects, you've already guaranteed that they're String objects.

I don't know what's considered "best practice", but the first parameter to the Toast.makeText method is a "Context" object. I'd feel more comfortable getting the Context from the view object passed to your onClick handler, like this:

```<code>
Toast.makeText(v.getContext(), "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT);
</code>```

You don't have any sorts of checks on your edit fields in case someone fails to fill them in. For example, if someone fails to enter a value into EditText01 and they press your button, you're going to end up with a NullPointerException right here:

```<code>
float fPrice=Float.parseFloat(priceText.getText().toString() + "");
</code>```

You could easily guard against this by doing something like this, instead:

```<code>
public void onClick(View v)
{
   Toast.makeText(v.getContext(), "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT);

   float fPrice, fRate;

   try
   {
      fPrice = Float.parseFloat(priceText.getText().toString());
      fRate = Float.parseFloat(rateText.getText().toString());

      float fRealEsate = fPrice * fRate;
      Toast.makeText(v.getContext(), "Real Estate Brokerage Fee: "
         + fRealEsate, Toast.LENGTH_SHORT).show();
   }
   catch (NumberFormatException nfe)
   {
      Toast.makeText(v.getContext(),
         "Please enter numeric values for Price and Rate.",
         Toast.LENGTH_SHORT).show();
   }
}
</code>```

Please name your buttons and edittext boxes something better than Button01 and EditText02. Using good names will make your life (and everyone else's lives) easier.

Body:
Need help with some real estate math in java this blows up each time

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // This app total real estate fees for a client selling a house

        Button button = (Button) findViewById(R.id.Button01);

         //  Sample data for priceText 360000
        final EditText priceText = (EditText) findViewById(R.id.EditText01);
        // Sample data for rateText .04
        final EditText rateText = (EditText) findViewById(R.id.EditText02);

        button.setOnClickListener(new OnClickListener()
 {
 public void onClick(View v)
 {
 Toast.makeText(jsclosingcost.this, "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT)
                //  Sample data for priceText 360000
  float fPrice=Float.parseFloat(priceText.getText().toString() + "");
                 // Sample data for rateText .04
  float fRate=Float.parseFloat(rateText.getText().toString() + "");

  float fRealEsate = fPrice * fRate;
  Toast.makeText(jsclosingcost.this, "Real Estate Brokerage Fee: " + fRealEsate, Toast.LENGTH_SHORT).show();
 }
 });

    }

Body:
Like others have said, "This blows up every time" doesn't give us a lot to go on. That said, I tossed this into a test project and found that it doesn't compile - you're missing a semicolon at the end of this line:

Toast.makeText(jsclosingcost.this, "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT)

By adding a semicolon to that line, I was able to compile this and run it without issue.

A few things of note, however...

You don't need to append an empty string to your strings here:

float fPrice=Float.parseFloat(priceText.getText().toString() + "");
float fRate=Float.parseFloat(rateText.getText().toString() + "");

Appending an empty string in this way is an old trick to ensure things are cast as String objects, but by calling toString on the objects, you've already guaranteed that they're String objects.

I don't know what's considered "best practice", but the first parameter to the Toast.makeText method is a "Context" object. I'd feel more comfortable getting the Context from the view object passed to your onClick handler, like this:

Toast.makeText(v.getContext(), "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT);

You don't have any sorts of checks on your edit fields in case someone fails to fill them in. For example, if someone fails to enter a value into EditText01 and they press your button, you're going to end up with a NullPointerException right here:

float fPrice=Float.parseFloat(priceText.getText().toString() + "");

You could easily guard against this by doing something like this, instead:

public void onClick(View v)
{
   Toast.makeText(v.getContext(), "Doing Closing Cost Breakdown", Toast.LENGTH_SHORT);

   float fPrice, fRate;

   try
   {
      fPrice = Float.parseFloat(priceText.getText().toString());
      fRate = Float.parseFloat(rateText.getText().toString());

      float fRealEsate = fPrice * fRate;
      Toast.makeText(v.getContext(), "Real Estate Brokerage Fee: "
         + fRealEsate, Toast.LENGTH_SHORT).show();
   }
   catch (NumberFormatException nfe)
   {
      Toast.makeText(v.getContext(),
         "Please enter numeric values for Price and Rate.",
         Toast.LENGTH_SHORT).show();
   }
}

Please name your buttons and edittext boxes something better than Button01 and EditText02. Using good names will make your life (and everyone else's lives) easier.


问:
Why doesn't this code work? Javascript if statement, else if statement
This is a javascript code, and I wanted to make it like:
if the person answered yes, reply with "that's cool", if the person answered no, reply with "I'll make you happy", if the person answered a question that CONTAINS "yes" or "no", say "Type only yes or no, without any extra texts." Also, if the person doesn't reply that doesn't CONTAIN "yes" or "no", answer with "you didn't even answer the question."
But, this code is somehow weird. If I type something random like "hi", it says "Type only yes or no, without any extra texts.", not "you didn't even answer the question."
help!</p>

```<code>var id;
id = prompt("Are you happy?");
if(id == "yes"){
alert("That's cool.");
}else if(id == "no"){
alert("I'll make you happy.");
}else if(id || "yes" || "no"){
alert("Type only yes or no, without any extra texts.");
}else{
alert("you didn't even answer the question.");
}
</code>```

答:
This line:

```<code>else if(id || "yes" || "no")
</code>```

doesn't test whether id has the values "yes" or "no" in it. It tests if id is truthy*, or "yes" is truthy (it is), or "no" is truthy (it is). So the overall condition will always be true, regardless of the value of id.

Since you're using else if, you don't need to check for "yes" or "no" at all at that point — if you got there, you know id doesn't have either of them in it. So just

```<code>else if (id)
</code>```

...will tell you that id has something in it, but it wasn't "yes" or "no" (because you already handled them).

* "truthy" - Coerces to or is treated as true when coerced to boolean or used in a logical operation. It's the other side of "falsy," which coerces to or is treated as false in the same situations. The falsy values in JavaScript are 0, "", null, undefined, NaN, and of course, false. All other values are truthy (including " ", FWIW).

Body:
This is a javascript code, and I wanted to make it like:
if the person answered yes, reply with "that's cool", if the person answered no, reply with "I'll make you happy", if the person answered a question that CONTAINS "yes" or "no", say "Type only yes or no, without any extra texts." Also, if the person doesn't reply that doesn't CONTAIN "yes" or "no", answer with "you didn't even answer the question."
But, this code is somehow weird. If I type something random like "hi", it says "Type only yes or no, without any extra texts.", not "you didn't even answer the question."
help!

var id;
id = prompt("Are you happy?");
if(id == "yes"){
alert("That's cool.");
}else if(id == "no"){
alert("I'll make you happy.");
}else if(id || "yes" || "no"){
alert("Type only yes or no, without any extra texts.");
}else{
alert("you didn't even answer the question.");
}

Body:
This line:

else if(id || "yes" || "no")

doesn't test whether id has the values "yes" or "no" in it. It tests if id is truthy*, or "yes" is truthy (it is), or "no" is truthy (it is). So the overall condition will always be true, regardless of the value of id.

Since you're using else if, you don't need to check for "yes" or "no" at all at that point — if you got there, you know id doesn't have either of them in it. So just

else if (id)

...will tell you that id has something in it, but it wasn't "yes" or "no" (because you already handled them).

* "truthy" - Coerces to or is treated as true when coerced to boolean or used in a logical operation. It's the other side of "falsy," which coerces to or is treated as false in the same situations. The falsy values in JavaScript are 0, "", null, undefined, NaN, and of course, false. All other values are truthy (including " ", FWIW).


问:
PHP navigation bar include
I've been looking to make my navigation bar work on all my pages but it is not showing. I've been using php includes

This is my nav-bar in a "includes" folder:

```<code><!DOCTYPE html>
<html>
<head>
    <script src="jquery-3.2.1.min.js"></script>
</head>
<body>
    <div class="nav-bar">
        <div class='logo'>
            <h1>Va Jugar</h1>
        </div>
        <div class='nav-buttons'>
            <nav>
                <a href="index.php">Home</a>
                <a href="stuff.php">stuff</a>
                <a href="contact.php">Contact</a>
            </nav>
        </div>
        <div class="login">
            <a class="fa fa-sign-in" aria-hidden="true" href="login.html"
title="Login"></a>
        </div>
</div>
</body>
</html>
</code>```

And this is the index.php code:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset='UTF -8'>
    <meta name="description" content='...' />
<title>my page</title>
<link rel='stylesheet' type='text/css' href='css/style.css'>
</head>
<body>
    <div class="header">
        <?php include_once ("includes/header.php";) ?>
    </div>
</body>
</html>
</code>```

I can't find what I'm doing wrong but the result should be the navigation bar showing on the top and nothing shows up for me. Also, can I include the particular nav bar style page too? Or it has to be on the index.html and on one particular style.css file.

答:
Your included file should only contain the source code that you'd put at the place you include it.

You should not have doctype, html, head and body in your included file but only

```<code><div class="nav-bar">...</div>
</code>```

Title: PHP navigation bar include

Body:
I've been looking to make my navigation bar work on all my pages but it is not showing. I've been using php includes

This is my nav-bar in a "includes" folder:

<!DOCTYPE html>

Va Jugar

                Home
                stuff
                Contact

And this is the index.php code:

<!DOCTYPE html>

    <meta charset='UTF -8'>
    <meta name="description" content='...' />
<title>my page</title>
<link rel='stylesheet' type='text/css' href='css/style.css'>

        <?php include_once ("includes/header.php";) ?>

I can't find what I'm doing wrong but the result should be the navigation bar showing on the top and nothing shows up for me. Also, can I include the particular nav bar style page too? Or it has to be on the index.html and on one particular style.css file.

Body:
Your included file should only contain the source code that you'd put at the place you include it.

You should not have doctype, html, head and body in your included file but only

<div class="nav-bar">...</div>


问:
Java Generics - method which accept different generic interfaces
Say I have this code:

```<code>IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...
</code>```

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

```<code>void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}
</code>```

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

答: How about additionally passing the Class object that describes your type parameter? Then you have non-erased types, basically.</p>

Body:
Say I have this code:

IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.


问:
Selective redirect to new domain
I am using this for redirecting all my request through index.php except select few.

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|olddir|smestuff|assets|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

I want to shift few things (directories) to new domain, so I want to know how can I redirect olddir|smestuff (//from above example) to new domain and keep everything else safe

答:
You already don't redirect olddir and smestuff, so add:

```<code>RewriteCond $1 ^(olddir|smestuff)
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R,L]
</code>```

which will cause a browser redirect to the new domain.

Title: Selective redirect to new domain

Body:
I am using this for redirecting all my request through index.php except select few.

RewriteEngine on
RewriteCond $1 !^(index\.php|olddir|smestuff|assets|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

I want to shift few things (directories) to new domain, so I want to know how can I redirect olddir|smestuff (//from above example) to new domain and keep everything else safe

Body:
You already don't redirect olddir and smestuff, so add:

RewriteCond $1 ^(olddir|smestuff)
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R,L]

which will cause a browser redirect to the new domain.


问:
Printing an object type in ftl
I am new to ftl (freemarker template ). I have a .ftl file and I am trying to acess my own defined type, Foo consisting of just two int variables. For debugging purposes, is there a way I can print the type of the object I am using in ftl. Although I know that it's Foo for sure. But had there been too many user defined types and the name of the model used in ftl were not self suggesting, what would have been my approach?

Thanks

答: Assuming Foo is not a List, Map, etc., just a plain object, try ${foo.class}, or even ${foo} which will call Foo.toString().

Title: Printing an object type in ftl


问:
Reading string and int data into arrays?? C++
Roger 210

Mike 150

Wayne 500

Conner 240

Ford 456

Fire 160

Robert 320

Andrew 480

The above is my text file (ignore the extra lines between the words) and I would like to read the .txt file into a cpp file into one int array and one string array. How would I do this?

The arrays are int[vote] and string[name].

Currently I have this:

string name[ASIZE];
    int vote[ASIZE];

```<code>string s;
ifstream infile("input.txt");

for (int i=0; i<ASIZE; i++)
{
    infile >> vote[i];
    infile.ignore();
    getline(infile, name[i]);
    infile >> name[i] >> vote[i];
}
</code>```

Please help!! I am a beginner and having trouble understanding arrays and we are required to use two different ones.

答:
You will have to include:

```<code>#include<fstream>
</code>```

Then, declare a ifstream variable as follows:

```<code>ifstream myFile;
</code>```

From there you can explore all the methods contained in ifstream and build whatever you need.
You will need two arrays, and read whenever you encounter a string, and a integer, and then store it in the corresponding array.

Body:
Roger 210

Mike 150

Wayne 500

Conner 240

Ford 456

Fire 160

Robert 320

Andrew 480

The above is my text file (ignore the extra lines between the words) and I would like to read the .txt file into a cpp file into one int array and one string array. How would I do this?

The arrays are int[vote] and string[name].

Currently I have this:

string name[ASIZE];
    int vote[ASIZE];

string s;
ifstream infile("input.txt");

for (int i=0; i<ASIZE; i++)
{
    infile >> vote[i];
    infile.ignore();
    getline(infile, name[i]);
    infile >> name[i] >> vote[i];
}

Please help!! I am a beginner and having trouble understanding arrays and we are required to use two different ones.

Body:
You will have to include:

#include<fstream>

Then, declare a ifstream variable as follows:

ifstream myFile;

From there you can explore all the methods contained in ifstream and build whatever you need.
You will need two arrays, and read whenever you encounter a string, and a integer, and then store it in the corresponding array.


问:
Understanding Generics and Reflection in Java to Make Array Generic
I am trying to model a train with a Java program.

Currently I have four classes:

Train,

BoxCar,

Cargo,

Person.

The BoxCar class has an array of Person and an array of Cargo. A BoxCar can only hold one type so when that type is given from the constructor,

I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set.
They wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code.

How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time.
Can someone map out the right approach to take?

BoxCar:

```<code>class BoxCar {
    String boxType;
    int boxID;
    int count;
    boolean isEmpty;
    Cargo cargo[];
    Person people[];
    int capacity;

    BoxCar(String box_type, int ID, int cap) {
        boxType = box_type;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }
}
</code>```

Person:

```<code>class Person {
    String government_ID, name;
    int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }
}
</code>```

Cargo:

```<code>class Cargo {
    String cargo_ID;
    int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }
}
</code>```

答:
Maybe this helps you out     </p>

```<code>public class Train {

public static void main(String[] args) {
    new Train();
}

public Train() {
    List<Person> persons = new ArrayList<>();
    persons.add(new Person("foo", "bar"));
    BoxCar<Person> personBoxCar = new BoxCar<>(persons);

    List<Cargo> cargo = new ArrayList<>();
    cargo.add(new Cargo("test"));
    BoxCar<Cargo> cargoBoxCar = new BoxCar<>(cargo);
}}

public class Person {

private String name;
private String surname;

public Person(String name, String surname) {
    this.name = name;
    this.surname = surname;
}

public String getName() {
    return name;
}

public String getSurname() {
    return surname;
}}

public class Cargo {

private String cargoType;

public Cargo(String cargoType) {
    this.cargoType = cargoType;
}

public String getCargoType() {
    return cargoType;
}}
public class BoxCar<T> {

private List<T> myArray;

public BoxCar(List<T> myArray) {
    this.myArray = myArray;
}}
</code>```

Body:
I am trying to model a train with a Java program.

Currently I have four classes:

Train,

BoxCar,

Cargo,

Person.

The BoxCar class has an array of Person and an array of Cargo. A BoxCar can only hold one type so when that type is given from the constructor,

I decide which array to use (either the people array or the cargo array). The thing is, I'd like to make that array inside BoxCar "generic" so that if there is another "kind" of type the user wants to use, it can be easily set.
They wouldn't need to declare another array inside the BoxCar class for that type and change the rest of the code.

How would I do this? I looked up Generic and Reflection but the examples I saw weren't exactly for my scenario and I'm learning this for the first time.
Can someone map out the right approach to take?

BoxCar:

class BoxCar {
    String boxType;
    int boxID;
    int count;
    boolean isEmpty;
    Cargo cargo[];
    Person people[];
    int capacity;

    BoxCar(String box_type, int ID, int cap) {
        boxType = box_type;
        boxID = ID;
        isEmpty = true;
        count = 0;
        capacity = cap;
    }
}

Person:

class Person {
    String government_ID, name;
    int age;

    Person(String gov_ID, String Name, int Age) {
        government_ID = gov_ID;
        name = Name;
        age = Age;
    }
}

Cargo:

class Cargo {
    String cargo_ID;
    int height, weight;

    Cargo(String c_id, int w, int h) {
        cargo_ID = c_id;
        height = h;
        weight = w;
    }
}

Body:
Maybe this helps you out

public class Train {

public static void main(String[] args) {
    new Train();
}

public Train() {
    List<Person> persons = new ArrayList<>();
    persons.add(new Person("foo", "bar"));
    BoxCar<Person> personBoxCar = new BoxCar<>(persons);

    List<Cargo> cargo = new ArrayList<>();
    cargo.add(new Cargo("test"));
    BoxCar<Cargo> cargoBoxCar = new BoxCar<>(cargo);
}}

public class Person {

private String name;
private String surname;

public Person(String name, String surname) {
    this.name = name;
    this.surname = surname;
}

public String getName() {
    return name;
}

public String getSurname() {
    return surname;
}}

public class Cargo {

private String cargoType;

public Cargo(String cargoType) {
    this.cargoType = cargoType;
}

public String getCargoType() {
    return cargoType;
}}
public class BoxCar<T> {

private List<T> myArray;

public BoxCar(List<T> myArray) {
    this.myArray = myArray;
}}


问:
What is nextTick and what does it do in Vue.js?
I read the docs, but I still can't understand it.

I know what data, computed, watch, methods do, but what is nextTick() used for in Vue.js?

答:
It's all about Timing

nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page.

Normally, devs use the native JavaScript function setTimeout to achieve similar behavior, but using setTimeout relinquishes control over to the browser before it gives control back to you (via calling your callback).

Example

Let's say you changed some data; Vue then updates the vDOM based on that data change (the changes are not yet rendered to the screen by the browser).

If you used nextTick at this point, your callback would get called immediately, and the browser would update the page after that callback finished executing.

If you instead used setTimeout, then the browser would have a chance to update the page, and then your callback would get called.

You can visualize this behavior by creating a small component like the following:

(Check this fiddle to see it live)

<template>

    {{ msg }}

</template>

```
<p>Run your local server. You will see the message "Three" being displayed.</p>
<p>Now, replace <code>this.$nextTick</code> with <code>setTimeout</code>:</p>
<pre class="lang-js prettyprint-override"><code>setTimeout(() => {
    this.msg = 'Three';
}, 0);
</code>```

Reload the browser. You will see "Two" before you see "Three".

That's because, with setTimeout:

Vue updated the vDOM to say "Two"

Vue gave control to the browser

The browser displayed "Two"

Callback was called

Vue updated the vDOM to say "Three"

Vue gave control to the browser

The browser displayed "Three"

But with nextTick, we skip steps 2 and 3! Instead of passing over control after the first vDOM update, Vue calls the callback immediately, which prevents the browser from updating until the callback is finished. In this example, that means "Two" is never actually displayed.

To understand how Vue implements this, you need to understand the concept of  the JavaScript Event Loop and microtasks.

Once you have those concepts clear(er), check the source code for nextTick.

ContentLicense: CC BY-SA 4.0

Body:
It's all about Timing

nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page.

Normally, devs use the native JavaScript function setTimeout to achieve similar behavior, but using setTimeout relinquishes control over to the browser before it gives control back to you (via calling your callback).

Example

Let's say you changed some data; Vue then updates the vDOM based on that data change (the changes are not yet rendered to the screen by the browser).

If you used nextTick at this point, your callback would get called immediately, and the browser would update the page after that callback finished executing.

If you instead used setTimeout, then the browser would have a chance to update the page, and then your callback would get called.

You can visualize this behavior by creating a small component like the following:

(Check this fiddle to see it live)

<template>
  <div class="hello">
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
        msg: 'One'
    }
  },
  mounted() {
      this.msg = 'Two';

      this.$nextTick(() => {
          this.msg = 'Three';
      });
  }
}
</script>

Run your local server. You will see the message "Three" being displayed.

Now, replace this.$nextTick with setTimeout:

setTimeout(() => {
    this.msg = 'Three';
}, 0);

Reload the browser. You will see "Two" before you see "Three".

That's because, with setTimeout:

Vue updated the vDOM to say "Two"

Vue gave control to the browser

The browser displayed "Two"

Callback was called

Vue updated the vDOM to say "Three"

Vue gave control to the browser

The browser displayed "Three"

But with nextTick, we skip steps 2 and 3! Instead of passing over control after the first vDOM update, Vue calls the callback immediately, which prevents the browser from updating until the callback is finished. In this example, that means "Two" is never actually displayed.

To understand how Vue implements this, you need to understand the concept of  the JavaScript Event Loop and microtasks.

Once you have those concepts clear(er), check the source code for nextTick.


问:
Looping through elements not working
I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

Stripped down code below.

HTML

```<code><div class="list">
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="2"></div>
   <div class="target" data-post-id="1"></div>
   <div class="target" data-post-id="1"></div>
</div>
</code>```

JS (event is tied to the target class):

```<code>if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}
</code>```

Clearly, I don't know how to loop through it properly. What's the solution?

答:
Do you need something like this?

```<code>var arr1 = [];
var arr2 = [];
$(".target").each(function(){
        arr1.push($(this).data("post-id"));
});

$(".target").each(function(index){
        var newArray = arr1.slice();
    newArray.splice(index, 1); // remove index value from an array, so this index != match its own
            console.log(newArray);
    if ($.inArray($(this).data("post-id"), newArray ) !== -1){
            $(this).text("Has A Match!");
    }else{
            $(this).text("No Match!");
    }

});
</code>```

Jsfiddle Here : https://jsfiddle.net/synz/votuqyp0/1/

Title: Looping through elements not working

Body:
I want to check if this element has a matching data attribute value to all other elements, but the loop doesn't always work.

Stripped down code below.

HTML

JS (event is tied to the target class):

if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
   // do stuff
}

Clearly, I don't know how to loop through it properly. What's the solution?

Body:
Do you need something like this?

var arr1 = [];
var arr2 = [];
$(".target").each(function(){
        arr1.push($(this).data("post-id"));
});

$(".target").each(function(index){
        var newArray = arr1.slice();
    newArray.splice(index, 1); // remove index value from an array, so this index != match its own
            console.log(newArray);
    if ($.inArray($(this).data("post-id"), newArray ) !== -1){
            $(this).text("Has A Match!");
    }else{
            $(this).text("No Match!");
    }

});

Jsfiddle Here : https://jsfiddle.net/synz/votuqyp0/1/


问:
Automatically terminate class while children still reference it
I have created a class where its children hold a necessary reference to their parent. This means, when the parent class goes out of scope in the routine which calls it, its terminate code is not called, as the children still hold a reference to it.

Is there a way of terminating the parent without having to manually terminate the children first too?

Current work around is to make the parent's terminate code (which contains code to terminate the children) public and to call it from the routine, but this is not ideal as then the parent is terminated twice (once manually, once when it leaves the caller sub's scope). But mainly I don't like having to call it manually

```<code>'Caller code
Sub runTest()
    Dim testClass As parentClass
    Set testClass = New parentClass
    Set testClass = Nothing
End Sub

'parentClass
Private childrenGroup As New Collection

Private Sub Class_Initialize()
    Dim childA As New childClass
    Dim childB As New childClass
    childA.Setup "childA", Me 'give name and parent reference to child class
    childB.Setup "childB", Me
    childrenGroup.Add childA 'add children to collection
    childrenGroup.Add childB
End Sub

Public Sub Class_Terminate()
    Set childrenGroup = Nothing
    Debug.Print "Parent terminated"
End Sub

'childClass
Private className As String
Private parent As classParent

Public Sub Setup(itemName As String, parentObj As classParent)
    Set parent = parentObj 'set the reference
    className = itemName
End Sub

Public Property Get Name() As String
    Name = className
End Property

Private Sub Class_Terminate()
    Debug.Print Name;" was terminated" 'only called when parent terminates child
End Sub
</code>```

Calling runTest() prints

```<code>childA was terminated
childB was terminated
Parent terminated
Parent terminated 'to get around this, you could just make another sub in the parent class
                  'to terminate its children
                  'but that still requires a manual call
</code>```

答:
No, you can't automatically terminate the children by simply terminating the collection:

```<code>Public Sub Class_Terminate()
    Set childrenGroup = Nothing
</code>```

The Collection object does not clean up any object references when it is set equal to Nothing, and it doesn't have a 'RemoveAll' mechanism which does.

...And I wouldn't bet on 'Remove' doing that either, one item at a time. So you do indeed need to loop backwards through the members, in exactly the 'manual' process you're trying to avoid:

```<code>Public Sub Class_Terminate()
Dim i As Integer

    For i = childrenGroup.Count To 1 Step - 1
        Set childrenGroup(i) = Nothing
        childrenGroup.Remove i
    Next I

    Set childrenGroup = Nothing
</code>```

My advice would be: use a Scripting.Dictionary object instead of the VBA Collection:

```<code>Private childrenGroup As New Scripting.Dictionary
</code>```

You'll need a reference to the Scripting Runtime (or to the Windows Scripting Host Object Model) and you may be surprised by the changed order of .Add Item, Key - and you will definitely be surprised by what happens when you request an item with a non-existent key.

Nevertheless, this works. The Dictionary does have a RemoveAll method, and this will clear all the references in its .Items when you call it:

```<code>Public Sub Class_Terminate()
    childrenGroup.RemoveAll
</code>```

You do need to call RemoveAll - it doesn't happen automatically if the dictionary goes out of scope - but that's as close as you'll get.

Note, also, that VBA runs on reference counting: if anything else has a reference to the children, the objects won't be released.

Body:
I have created a class where its children hold a necessary reference to their parent. This means, when the parent class goes out of scope in the routine which calls it, its terminate code is not called, as the children still hold a reference to it.

Is there a way of terminating the parent without having to manually terminate the children first too?

Current work around is to make the parent's terminate code (which contains code to terminate the children) public and to call it from the routine, but this is not ideal as then the parent is terminated twice (once manually, once when it leaves the caller sub's scope). But mainly I don't like having to call it manually

'Caller code
Sub runTest()
    Dim testClass As parentClass
    Set testClass = New parentClass
    Set testClass = Nothing
End Sub

'parentClass
Private childrenGroup As New Collection

Private Sub Class_Initialize()
    Dim childA As New childClass
    Dim childB As New childClass
    childA.Setup "childA", Me 'give name and parent reference to child class
    childB.Setup "childB", Me
    childrenGroup.Add childA 'add children to collection
    childrenGroup.Add childB
End Sub

Public Sub Class_Terminate()
    Set childrenGroup = Nothing
    Debug.Print "Parent terminated"
End Sub

'childClass
Private className As String
Private parent As classParent

Public Sub Setup(itemName As String, parentObj As classParent)
    Set parent = parentObj 'set the reference
    className = itemName
End Sub

Public Property Get Name() As String
    Name = className
End Property

Private Sub Class_Terminate()
    Debug.Print Name;" was terminated" 'only called when parent terminates child
End Sub

Calling runTest() prints

childA was terminated
childB was terminated
Parent terminated
Parent terminated 'to get around this, you could just make another sub in the parent class
                  'to terminate its children
                  'but that still requires a manual call

Body:
No, you can't automatically terminate the children by simply terminating the collection:

Public Sub Class_Terminate()
    Set childrenGroup = Nothing

The Collection object does not clean up any object references when it is set equal to Nothing, and it doesn't have a 'RemoveAll' mechanism which does.

...And I wouldn't bet on 'Remove' doing that either, one item at a time. So you do indeed need to loop backwards through the members, in exactly the 'manual' process you're trying to avoid:

Public Sub Class_Terminate()
Dim i As Integer

    For i = childrenGroup.Count To 1 Step - 1
        Set childrenGroup(i) = Nothing
        childrenGroup.Remove i
    Next I

    Set childrenGroup = Nothing

My advice would be: use a Scripting.Dictionary object instead of the VBA Collection:

Private childrenGroup As New Scripting.Dictionary

You'll need a reference to the Scripting Runtime (or to the Windows Scripting Host Object Model) and you may be surprised by the changed order of .Add Item, Key - and you will definitely be surprised by what happens when you request an item with a non-existent key.

Nevertheless, this works. The Dictionary does have a RemoveAll method, and this will clear all the references in its .Items when you call it:

Public Sub Class_Terminate()
    childrenGroup.RemoveAll

You do need to call RemoveAll - it doesn't happen automatically if the dictionary goes out of scope - but that's as close as you'll get.

Note, also, that VBA runs on reference counting: if anything else has a reference to the children, the objects won't be released.


问:
How do I convert an array of Strings to an Array of Int in Kotlin
I am looking to convert an List<String> to an List<Int> in Kotlin.

```<code>val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}
</code>```

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

答:
You can use .map { ... } with .toInt() or .toIntOrNull():

```<code> val result = strings.map { it.toInt() }
</code>```

Only the result is not an array but a list. It is preferable to use lists over arrays in non-performance-critical code, see the differences.

If you need an array, add .toTypedArray() or .toIntArray().

Body:
I am looking to convert an List<String> to an List<Int> in Kotlin.

val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

Body:
You can use .map { ... } with .toInt() or .toIntOrNull():

 val result = strings.map { it.toInt() }

Only the result is not an array but a list. It is preferable to use lists over arrays in non-performance-critical code, see the differences.

If you need an array, add .toTypedArray() or .toIntArray().


答:
To use np.hstack, we need to convert V1 to 2D such that the lengths along the first axis for the three input arrays are the same -

```<code>np.hstack((V1[:,None],V2,V3))
</code>```

As alternatives, we can use np.column_stack or np.concatenate along the second axis on 2D converted V1 alongwith others or np.c_ -

```<code>np.column_stack((V1,V2,V3))
np.concatenate([V1[:,None],V2,V3],axis=1)
np.c_[V1,V2,V3]
</code>```

Title: ValueError: all the input arrays must have same number of dimensions . Stacking vectors

Body:
l have three arrays to append.
Here a sample of my vectors :

V1=array([ 0.03317591, -0.01624349, -0.01151019])
V2=array([[ 0.06865846, -0.00223798],
       [-0.02872752, -0.00369226],
       [-0.02063454, -0.00231726]])
V3=
array([[ 0.01160267,  0.12610824, -0.01634712,  0.01217519],
       [-0.00727594, -0.0501376 , -0.01641992,  0.00933081],
       [-0.05305551,  0.01195211,  0.04031831, -0.04476306]])

in order to append the three vectors and get one vector l did the following :

new_v=np.hstack((V1,V2,V3))

l got the following error :

ValueError: all the input arrays must have same number of dimensions

However :

 V2_V3=np.hstack((V2,V3))

works, it returns :

array([[ 0.06865846, -0.00223798,  0.01160267,  0.12610824, -0.01634712,
         0.01217519],
       [-0.02872752, -0.00369226, -0.00727594, -0.0501376 , -0.01641992,
         0.00933081],
       [-0.02063454, -0.00231726, -0.05305551,  0.01195211,  0.04031831,
        -0.04476306]])

What l would like to get is the following :

array([[0.03317591, 0.06865846, -0.00223798,  0.01160267,  0.12610824, -0.01634712,
         0.01217519],
       [-0.01624349, -0.02872752, -0.00369226, -0.00727594, -0.0501376 , -0.01641992,
         0.00933081],
       [-0.01151019, -0.02063454, -0.00231726, -0.05305551,  0.01195211,  0.04031831,
        -0.04476306]])

What is wrong with V1 ?

Body:
To use np.hstack, we need to convert V1 to 2D such that the lengths along the first axis for the three input arrays are the same -

np.hstack((V1[:,None],V2,V3))

As alternatives, we can use np.column_stack or np.concatenate along the second axis on 2D converted V1 alongwith others or np.c_ -

np.column_stack((V1,V2,V3))
np.concatenate([V1[:,None],V2,V3],axis=1)
np.c_[V1,V2,V3]


问:
How to send 404 HTTP status code with Polymer Starter Kit
When starting a new project with the polymer starter kit 2, it comes with decent client side routing based on the PRPL pattern as described here.

This works fine on the front end for the end user. However, on requesting a page that does not exist, there is no proper 404 status code sent. This is not good for SEO, in my understanding.

Is there a recommended way of doing this properly? I understand there needs to be some server side logic to determine what response code to send, but I am not sure how to do that in a straightforward way.

I plan to host my app with Firebase hosting, so if there's a solution for that platform, I'm happy to learn about it. But my question is aimed towards a general way of doing this.

答:
Firebase Hosting has additional features that let you customize how your content is hosted. You can set & customize to your own specific need at firebase.json file.

Here this link describes detailed information at hosting side how to define all, customized.
Hope this page heps.


问:
How can I go about diagnosing a poor performing Rails application running on mysql?
I've taken over the maintenance of a Rails 2.3.4 application running on ruby 1.8.7 and mysql. The application is a modified Radiant CMS 0.8.1 site with custom extensions. Currently, the production environment is experiencing frequent periods of slow and sometimes no responsiveness. During these times I've noticed that the mysql CPU usage jumps through the roof. The web site has an international audience and at the time of it's creation scaling the site was not taken into consideration. Currently, the user base is at around 4600 and growing. What are some initial steps I can take to diagnose the poor performance in both Rails and mysql?

Thanks,
Mike

答:
The last place I contracted used a tool called query_reviewer. It's a Rails plugin that in development mode analyzes every query and gives you warnings in the UI letting you know any possible issues. I liked it because you didn't have to switch back and forth between your app and log or other testing tools.

https://github.com/dsboulder/query_reviewer

Another helpful tool is New Relic - it's free for developing if you're just using it on your local. It analyzes more than just SQL, including view rendering and other potential efficiency issues.

http://newrelic.com/