问:
Remove Duplicate objects from JSON Array
I'm trying to create a series of lists in HTML of the form:

```<code><div>
    <h3>Math K</h3>
    <li>Counting & Cardinality</li>
    <li>Geometry</li>
</div>
<div>
    <h3>Math 1</h3>
    <li>Counting & Cardinality</li>
    <li>Orders of Operation</li>
</div>
<div>
    <h3>Math 2</h3>
    <li>Geometry</li>
</div>
</code>```

My original though was to create an array and push that into the
 element on the page with $("#divid").append(array). I created an array that looks like this:

```<code>var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];
</code>```

And I need to remove the duplicates so that something like this remains:

```<code>var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];
</code>```

I've tried installing underscore.js and using ._uniq but that only seems to work when a single key:value pair appears in the object. I can't seem to get it to work across multiple keys.

When I try something like:

```<code>var uniqueStandards = _.uniq(standardsList, function(item, key, Domain){
    return item.Domain;
});
</code>```

I only get the first three unique values (one per grade). But I need all the unique values across both grade and domain. Is there a simple way to feed both keys to the _.uniq function?

Ultimately, I need a list with the each unique grade as the header and the unique domains as the list items to pass into an HTML page.

答:
I know there are many answers already but the best one that worked for me for a complex json structure is:

var arr = [{ "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }];

var clean = arr.filter((arr, index, self) =>
    index === self.findIndex((t) => (t.save === arr.save && t.State === arr.State)))

console.log(clean);```

You can try this directly to chrome browser console and edit according to your need.

I hope this helps someone.

Body:
I'm trying to create a series of lists in HTML of the form:

Math K

Counting & Cardinality

Geometry

Math 1

Counting & Cardinality

Orders of Operation

Math 2

Geometry

My original though was to create an array and push that into the
 element on the page with $("#divid").append(array). I created an array that looks like this:

var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];

And I need to remove the duplicates so that something like this remains:

var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];

I've tried installing underscore.js and using ._uniq but that only seems to work when a single key:value pair appears in the object. I can't seem to get it to work across multiple keys.

When I try something like:

var uniqueStandards = _.uniq(standardsList, function(item, key, Domain){
    return item.Domain;
});

I only get the first three unique values (one per grade). But I need all the unique values across both grade and domain. Is there a simple way to feed both keys to the _.uniq function?

Ultimately, I need a list with the each unique grade as the header and the unique domains as the list items to pass into an HTML page.

Body:
I know there are many answers already but the best one that worked for me for a complex json structure is:

var arr = [{ "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RWCW", "desc": "WEST", "code": "RWCW", "level": 0, "save": "RWCW : WEST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RCSW", "desc": "SOUTHWEST", "code": "RCSW", "level": 0, "save": "RCSW : SOUTHWEST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RCNW", "desc": "MIDWEST", "code": "RCNW", "level": 0, "save": "RCNW : MIDWEST", "attribute1": "", "attribute2": "" }, { "State": "RSCW", "desc": "SOUTHEAST", "code": "RSCW", "level": 0, "save": "RSCW : SOUTHEAST", "attribute1": "", "attribute2": "" }, { "State": "RECW", "desc": "NORTHEAST", "code": "RECW", "level": 0, "save": "RECW : NORTHEAST", "attribute1": "", "attribute2": "" }];

var clean = arr.filter((arr, index, self) =>
    index === self.findIndex((t) => (t.save === arr.save && t.State === arr.State)))

console.log(clean);

You can try this directly to chrome browser console and edit according to your need.

I hope this helps someone.


来源: stackexchange

问:
Does Power BI Rest API need only one Power BI Pro account for integrate reports, which will use for all end users?
We are working Power BI Reports and we are new in Power BI. For embed Power BI reports in our web application we want to choose Rest APIs. </p>

<p>Is it possible that we subscribe only one Power BI Pro account and publish our all reports and it could be available for all end-users with access token? </p>

答:
Technically that's possible, but I'm not sure if it's ok from licensing point of view.

I mean, Power BI Premium was released so that not all of the people in the organization should need Pro licenses. With Premium you're able to create and publish a report with a single Pro license and everybody else viewing the report can be Free-license users. The report might contain some Pro-freatures (like a gateway connection to on-premise) and it's still viewable to Free-users.

Premium isn't cheap, but it might work in some middle to large size organizations.

Another way to publish a report to multiple users is to use Publish to web -feature (https://powerbi.microsoft.com/en-us/documentation/powerbi-service-publish-to-web/), but it's got some limitations and security related issues.

ContentLicense: CC BY-SA 3.0

Body:
We are working Power BI Reports and we are new in Power BI. For embed Power BI reports in our web application we want to choose Rest APIs.

Is it possible that we subscribe only one Power BI Pro account and publish our all reports and it could be available for all end-users with access token?


问:
How to write proper test for reactive interface repository which returns Observable only when there is some event, how to mock triggering that event
I am trying to write proper test for my reactive repository, which just listen for location changes. I don't want to actually listen for location changes and just 'invoke' new location change multiple times with just created custom Location.

Here is the repository and its function for gathering locations:

```<code>interface RxLocationRepository {

@SuppressLint("MissingPermission")
fun onLocationUpdate(): Observable<Location>

fun stopLocationUpdates()
}
</code>```

Here is the implementation of it, which actually DON'T MATTER because i don't want to listen for real location updates, but i want to show you that it is just reactive implementation for listen to LocationManager updates:

```<code>class LocationNativeRepository(
    val locationManager: LocationManager,
    val geoEventsDistanceMeters: Int,
    val geoEventsIntervalSeconds: Int) : RxLocationRepository{

var locationToPopulate: Location = Location(LocationManager.GPS_PROVIDER)
lateinit var mLocationCallbackNativeApi: LocationListener
private val subject: BehaviorSubject<Location> = BehaviorSubject.createDefault(locationToPopulate)
var locationEmitter: Observable<Location> = subject.hide()

init {
    configureNativeLocationEmitter()
}

override fun onLocationUpdate(): Observable<Location> {
    return locationEmitter
}

@SuppressLint("MissingPermission")
override fun stopLocationUpdates() {
    locationManager.removeUpdates(mLocationCallbackNativeApi)
}

@SuppressLint("MissingPermission")
private fun configureNativeLocationEmitter() {

    mLocationCallbackNativeApi = object : LocationListener {

        override fun onLocationChanged(location: Location) {
            subject.onNext(location)
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

        override fun onProviderEnabled(provider: String) {}

        override fun onProviderDisabled(provider: String) {}

    }

    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }

    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }
 }

}
</code>```

So how i can invoke this repository in my test to actually trigger the onLocationUpdate() method? So for example i will make it emit 3 times location like this:

```<code> val location = Location("test").apply {
        latitude = 1.234
        longitude = 5.678
        accuracy = 20f
        time = Date().time
    }
</code>```

答: Create a PublishSubject<Location> variable. Create an anonymous sub-class of RxLocationRepository, where the onLocationUpdate() method returns the variable. Then emit values into the variable to provide new locations.

Body:
I am trying to write proper test for my reactive repository, which just listen for location changes. I don't want to actually listen for location changes and just 'invoke' new location change multiple times with just created custom Location.

Here is the repository and its function for gathering locations:

interface RxLocationRepository {

@SuppressLint("MissingPermission")
fun onLocationUpdate(): Observable<Location>

fun stopLocationUpdates()
}

Here is the implementation of it, which actually DON'T MATTER because i don't want to listen for real location updates, but i want to show you that it is just reactive implementation for listen to LocationManager updates:

class LocationNativeRepository(
    val locationManager: LocationManager,
    val geoEventsDistanceMeters: Int,
    val geoEventsIntervalSeconds: Int) : RxLocationRepository{

var locationToPopulate: Location = Location(LocationManager.GPS_PROVIDER)
lateinit var mLocationCallbackNativeApi: LocationListener
private val subject: BehaviorSubject<Location> = BehaviorSubject.createDefault(locationToPopulate)
var locationEmitter: Observable<Location> = subject.hide()

init {
    configureNativeLocationEmitter()
}

override fun onLocationUpdate(): Observable<Location> {
    return locationEmitter
}

@SuppressLint("MissingPermission")
override fun stopLocationUpdates() {
    locationManager.removeUpdates(mLocationCallbackNativeApi)
}

@SuppressLint("MissingPermission")
private fun configureNativeLocationEmitter() {

    mLocationCallbackNativeApi = object : LocationListener {

        override fun onLocationChanged(location: Location) {
            subject.onNext(location)
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

        override fun onProviderEnabled(provider: String) {}

        override fun onProviderDisabled(provider: String) {}

    }

    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }

    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                (geoEventsIntervalSeconds * 1000).toLong(),
                geoEventsDistanceMeters.toFloat(),
                mLocationCallbackNativeApi,
                Looper.getMainLooper())
    } catch (ignored: IllegalArgumentException) {
        ignored.printStackTrace()
    }
 }

}

So how i can invoke this repository in my test to actually trigger the onLocationUpdate() method? So for example i will make it emit 3 times location like this:

 val location = Location("test").apply {
        latitude = 1.234
        longitude = 5.678
        accuracy = 20f
        time = Date().time
    }


问:
Angular5 @output decorator
Hello there learning angular and came across the @output decorators in angular. After researching the topic I still have some difficulty wrapping my head around this concept.

Code example:

app.component.html:

```<code><app-tutorials(event)="doSomething($event)"></app-tutorials>
</code>```

app.component.ts:

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

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

  doSomething(event){
    alert("being executed");
  }
}
</code>```

tutorial.component.html:

```<code><button (click)="beingClicked($event)"_>click me</button>
</code>```

tutorial.component.ts:

```<code>import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-tutorials',
  templateUrl: './tutorials.component.html',
  styleUrls: ['./tutorials.component.css']
})
export class TutorialsComponent{

  @Output() event = new EventEmitter();

  beingClicked(event){
    this.event.emit(event);
  }
}
</code>```

My current understanding is this, plz correct me if I'm wrong:

output is used to transfer data only from child components the parent component.

When the button is clicked beingClicked(event) is fired and passes through event info in the argument with $event.

We can emit the event with this.event.emit(event);   because we first instantiated the event earlier in the class with the statement: @Output() event = new EventEmitter();

Now the parent component listens for (event) in the app.component.html:<app-tutorials(event)="doSomething($event)"></app-tutorials>

When the event is emitted from the child component the doSomething($event) function is fired and gets passed in the $event

Question:

Is my current understanding correct?

What exactly is this EventEmitter and is it always needed to data upwards?

答:
Is my current understanding correct?

Your understanding is correct. There are other ways to share data but to notify the parent of an event that needs to be reacted to this is the appropriate way to do it. For more details / examples of component interaction see also the documentation Parent listens for child event.

What exactly is this EventEmitter and is it always needed to data upwards?

The EventEmitter is an event that other code (components, services, etc.) can subscribe to. The owner of the EventEmitter can then fire the event with data whenever it is appropriate and the code that has subscribed to the event can decide how to handle the call or ignore it all together if it is not relevant. See also Event-driven Programming.

It is not necessarily only for upstream (child to parent) it could also be used horizontally (child to child) communication via a shared service dependency or for downstream (also using a shared service dependency) so that child components can decide how to handle an event triggered by a parent component.

Title: Angular5 @output decorator

Body:
Hello there learning angular and came across the @output decorators in angular. After researching the topic I still have some difficulty wrapping my head around this concept.

Code example:

app.component.html:

<app-tutorials(event)="doSomething($event)"></app-tutorials>

app.component.ts:

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

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

  doSomething(event){
    alert("being executed");
  }
}

tutorial.component.html:

<button (click)="beingClicked($event)"_>click me</button>

tutorial.component.ts:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-tutorials',
  templateUrl: './tutorials.component.html',
  styleUrls: ['./tutorials.component.css']
})
export class TutorialsComponent{

  @Output() event = new EventEmitter();

  beingClicked(event){
    this.event.emit(event);
  }
}

My current understanding is this, plz correct me if I'm wrong:

output is used to transfer data only from child components the parent component.

When the button is clicked beingClicked(event) is fired and passes through event info in the argument with $event.

We can emit the event with this.event.emit(event);   because we first instantiated the event earlier in the class with the statement: @Output() event = new EventEmitter();

Now the parent component listens for (event) in the app.component.html:<app-tutorials(event)="doSomething($event)"></app-tutorials>

When the event is emitted from the child component the doSomething($event) function is fired and gets passed in the $event

Question:

Is my current understanding correct?

What exactly is this EventEmitter and is it always needed to data upwards?


问:
Using index during order by clause?
I  have created the index on created_date column of employee table but when i see the explain plan of below query
i do not see index being used. Why ?

```<code>    Select * from employee order by created_date desc;
</code>```

Per mine understanding, oracle will keep the created date in sorted fashion(using B tree) along with row id. So
why it does not use the already sorted data then fetch the other data using row id ?

If it does not use index then it will fetch all data in memory, then sort it and return it. Is n't it ?

答:
most probably that your created_date column is nullable. Add

```<code>where created_date is not null
</code>```

to your query,

Select * from employee where created_date is not null order by
  created_date desc;

and look your explain plan again.

No guarantee to use index, but uses most probably if it doesn't need a full-scan. ( if a query returns more than 10 percent, doesn't need an index generally )

Oracle checks for data magnitude(we could query from dba_tables, manually also), if CBO(Cost based optimization,in most of the systems, this type of optimization preferred,instead of Rule-based optimization) used, and relevant table analyzed.

The CBO uses database statistics to generate several execution
plans, picking the one with the lowest cost, where cost relates to
system resources required to complete the operation.

Title: Using index during order by clause?

Body:
I  have created the index on created_date column of employee table but when i see the explain plan of below query
i do not see index being used. Why ?

    Select * from employee order by created_date desc;

Per mine understanding, oracle will keep the created date in sorted fashion(using B tree) along with row id. So
why it does not use the already sorted data then fetch the other data using row id ?

If it does not use index then it will fetch all data in memory, then sort it and return it. Is n't it ?

Body:
most probably that your created_date column is nullable. Add

where created_date is not null

to your query,

Select * from employee where created_date is not null order by
  created_date desc;

and look your explain plan again.

No guarantee to use index, but uses most probably if it doesn't need a full-scan. ( if a query returns more than 10 percent, doesn't need an index generally )

Oracle checks for data magnitude(we could query from dba_tables, manually also), if CBO(Cost based optimization,in most of the systems, this type of optimization preferred,instead of Rule-based optimization) used, and relevant table analyzed.

The CBO uses database statistics to generate several execution
plans, picking the one with the lowest cost, where cost relates to
system resources required to complete the operation.


问:
Why do we need the tensor name
Imagine I have a layer I want to repeat K times:

```<code>    {conv - relu - pool} x K
</code>```

In that case I need to iteratively run the forward pass for K-th layer:

```<code>for k in range(len(K)):
    Wk = ...
    bk = ...
    conv = tf.nn.conv2d(pool, Wk, ...) + bk
</code>```

Here if I miss 'name' parameter - will my conv tensor be replaced on every iteration? Would the correct variant be:

```<code>for k in range(len(K)):
    Wk = ...
    bk = ...
    name='conv%d' % (k)
    conv = tf.nn.conv2d(name=name, pool, Wk, ...) + bk
</code>```

答:
So, if you don't put a name, IT DOESN'T OVERWRITE or replace the value. TF comes up with its own naming convention like const_1, const_2, etc.

At least one of the reasons name parameter helps is because TensorBoard uses that. This parameter is used in TF namespace (vs Python namespace - hence the variable name is ignored by TF).

So, when you have multiple iterations, that naming convention will be used to name different names.

WRT how to use it, there are few ways of doing this -one of them you already typed. Another way is to use "scope" - so that your TB (TensorBoard) graphs look much neater and manageable. Using scope is also optional at least from TB perspective.

Title: Why do we need the tensor name

Body:
Imagine I have a layer I want to repeat K times:

    {conv - relu - pool} x K

In that case I need to iteratively run the forward pass for K-th layer:

for k in range(len(K)):
    Wk = ...
    bk = ...
    conv = tf.nn.conv2d(pool, Wk, ...) + bk

Here if I miss 'name' parameter - will my conv tensor be replaced on every iteration? Would the correct variant be:

for k in range(len(K)):
    Wk = ...
    bk = ...
    name='conv%d' % (k)
    conv = tf.nn.conv2d(name=name, pool, Wk, ...) + bk


问:
Google Apps Script; Docs; convert selected element to HTML
I am just starting with Google Apps Script and following the Add-on quickstart

https://developers.google.com/apps-script/quickstart/docs

In the quickstart you can create a simple add-on to get a selection from a document and translate it with the LanguageApp service. The example gets the underlying text using this:

```<code>function getSelectedText() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var text = [];
    var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      if (elements[i].isPartial()) {
        var element = elements[i].getElement().asText();
        var startIndex = elements[i].getStartOffset();
        var endIndex = elements[i].getEndOffsetInclusive();

        text.push(element.getText().substring(startIndex, endIndex + 1));
      } else {
        var element = elements[i].getElement();
        // Only translate elements that can be edited as text; skip images and
        // other non-text elements.
        if (element.editAsText) {
          var elementText = element.asText().getText();
          // This check is necessary to exclude images, which return a blank
          // text element.
          if (elementText != '') {
            text.push(elementText);
          }
        }
      }
    }
    if (text.length == 0) {
      throw 'Please select some text.';
    }
    return text;
  } else {
    throw 'Please select some text.';
  }
}
</code>```

It gets the text only: element.getText(), without any formatting.

I know the underlying object is not html, but is there a way to get the selection converted into a HTML string? For example, if the selection has a mix of formatting, like bold:

this is a sample with bold text

Then is there any method, extension, library, etc, -- like element.getHTML() -- that could return this?

this is a sample with bold text

instead of this?

this is a sample with bold text

答:
There is a script GoogleDoc2HTML by Omar AL Zabir. Its purpose is to convert the entire document into HTML. Since you only want to convert rich text within the selected element, the function relevant to your task is processText from the script, shown below.

The method getTextAttributeIndices gives the starting offsets for each change of text attribute, like from normal to bold or back. If there is only one change, that's the attribute for the entire element (typically paragraph), and this is dealt with in the first part of if-statement.

The second part deals with the general case, looping over the indices and inserting HTML markup corresponding to the attributes.

The script isn't maintained, so consider it as a starting point for your own code, rather than a ready-to-use library. There are some unmerged PRs that improve the conversion process, in particular for inline links.

```<code>function processText(item, output) {
  var text = item.getText();
  var indices = item.getTextAttributeIndices();

  if (indices.length <= 1) {
    // Assuming that a whole para fully italic is a quote
    if(item.isBold()) {
      output.push('<b>' + text + '</b>');
    }
    else if(item.isItalic()) {
      output.push('<blockquote>' + text + '</blockquote>');
    }
    else if (text.trim().indexOf('http://') == 0) {
      output.push('<a href="' + text + '" rel="nofollow">' + text + '</a>');
    }
    else {
      output.push(text);
    }
  }
  else {

    for (var i=0; i < indices.length; i ++) {
      var partAtts = item.getAttributes(indices[i]);
      var startPos = indices[i];
      var endPos = i+1 < indices.length ? indices[i+1]: text.length;
      var partText = text.substring(startPos, endPos);

      Logger.log(partText);

      if (partAtts.ITALIC) {
        output.push('<i>');
      }
      if (partAtts.BOLD) {
        output.push('<b>');
      }
      if (partAtts.UNDERLINE) {
        output.push('<u>');
      }

      // If someone has written [xxx] and made this whole text some special font, like superscript
      // then treat it as a reference and make it superscript.
      // Unfortunately in Google Docs, there's no way to detect superscript
      if (partText.indexOf('[')==0 && partText[partText.length-1] == ']') {
        output.push('<sup>' + partText + '</sup>');
      }
      else if (partText.trim().indexOf('http://') == 0) {
        output.push('<a href="' + partText + '" rel="nofollow">' + partText + '</a>');
      }
      else {
        output.push(partText);
      }

      if (partAtts.ITALIC) {
        output.push('</i>');
      }
      if (partAtts.BOLD) {
        output.push('</b>');
      }
      if (partAtts.UNDERLINE) {
        output.push('</u>');
      }

    }
  }
}
</code>```

Body:
I am just starting with Google Apps Script and following the Add-on quickstart

https://developers.google.com/apps-script/quickstart/docs

In the quickstart you can create a simple add-on to get a selection from a document and translate it with the LanguageApp service. The example gets the underlying text using this:

function getSelectedText() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var text = [];
    var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      if (elements[i].isPartial()) {
        var element = elements[i].getElement().asText();
        var startIndex = elements[i].getStartOffset();
        var endIndex = elements[i].getEndOffsetInclusive();

        text.push(element.getText().substring(startIndex, endIndex + 1));
      } else {
        var element = elements[i].getElement();
        // Only translate elements that can be edited as text; skip images and
        // other non-text elements.
        if (element.editAsText) {
          var elementText = element.asText().getText();
          // This check is necessary to exclude images, which return a blank
          // text element.
          if (elementText != '') {
            text.push(elementText);
          }
        }
      }
    }
    if (text.length == 0) {
      throw 'Please select some text.';
    }
    return text;
  } else {
    throw 'Please select some text.';
  }
}

It gets the text only: element.getText(), without any formatting.

I know the underlying object is not html, but is there a way to get the selection converted into a HTML string? For example, if the selection has a mix of formatting, like bold:

this is a sample with bold text

Then is there any method, extension, library, etc, -- like element.getHTML() -- that could return this?

this is a sample with bold text

instead of this?

this is a sample with bold text

Body:
There is a script GoogleDoc2HTML by Omar AL Zabir. Its purpose is to convert the entire document into HTML. Since you only want to convert rich text within the selected element, the function relevant to your task is processText from the script, shown below.

The method getTextAttributeIndices gives the starting offsets for each change of text attribute, like from normal to bold or back. If there is only one change, that's the attribute for the entire element (typically paragraph), and this is dealt with in the first part of if-statement.

The second part deals with the general case, looping over the indices and inserting HTML markup corresponding to the attributes.

The script isn't maintained, so consider it as a starting point for your own code, rather than a ready-to-use library. There are some unmerged PRs that improve the conversion process, in particular for inline links.

function processText(item, output) {
  var text = item.getText();
  var indices = item.getTextAttributeIndices();

  if (indices.length <= 1) {
    // Assuming that a whole para fully italic is a quote
    if(item.isBold()) {
      output.push('<b>' + text + '</b>');
    }
    else if(item.isItalic()) {
      output.push('<blockquote>' + text + '</blockquote>');
    }
    else if (text.trim().indexOf('http://') == 0) {
      output.push('<a href="' + text + '" rel="nofollow">' + text + '</a>');
    }
    else {
      output.push(text);
    }
  }
  else {

    for (var i=0; i < indices.length; i ++) {
      var partAtts = item.getAttributes(indices[i]);
      var startPos = indices[i];
      var endPos = i+1 < indices.length ? indices[i+1]: text.length;
      var partText = text.substring(startPos, endPos);

      Logger.log(partText);

      if (partAtts.ITALIC) {
        output.push('<i>');
      }
      if (partAtts.BOLD) {
        output.push('<b>');
      }
      if (partAtts.UNDERLINE) {
        output.push('<u>');
      }

      // If someone has written [xxx] and made this whole text some special font, like superscript
      // then treat it as a reference and make it superscript.
      // Unfortunately in Google Docs, there's no way to detect superscript
      if (partText.indexOf('[')==0 && partText[partText.length-1] == ']') {
        output.push('<sup>' + partText + '</sup>');
      }
      else if (partText.trim().indexOf('http://') == 0) {
        output.push('<a href="' + partText + '" rel="nofollow">' + partText + '</a>');
      }
      else {
        output.push(partText);
      }

      if (partAtts.ITALIC) {
        output.push('</i>');
      }
      if (partAtts.BOLD) {
        output.push('</b>');
      }
      if (partAtts.UNDERLINE) {
        output.push('</u>');
      }

    }
  }
}


问:
Error: Could not find or load main class Disneyland
My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda

The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop

Error: Could not find or load main class Disneyland
    package com.Kassie$;

```<code>import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
   try {
       //Read from file
       String[] aItems = new String(Files.readAllBytes
           (Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
           .split("\n");
       return aItems;
    } catch (IOException e) {
       e.printStackTrace();
   }
   return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
   try {
       //Read from file
           String[] aPrices = new String(Files.readAllBytes
           (Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
           .split("\n");
           return aPrices;
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
   for(int i = 0; i < storedValue.length; i++) {
       if(storedValue[i][0].equals(name)) {
           return (storedValue[i][1]);
       }
   }
   return null;
}
public static void main(String[] args) {
   char choice = ' ';
   int totPrice = 0;
   Scanner s = new Scanner(System.in);
   String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
       {"Minnie Mouse", "Toon Town"},
       {"Goofy","Frontier Land"},
       {"Pluto","Tomorrowland"},
       {"Belle","Fantasyland"},
       {"Jasmine", "Adventureland"}};
   System.out.println("Do you like to know the "
       + "Disney Character's location(Y/N)?");
   choice = s.next().charAt(0);
   if(choice == 'Y' || choice == 'y') {
       System.out.println("Enter the name of the character");
       String aName = s.next();
       String location = findLocation(characterLocation,aName);
       if( location != null) {
           System.out.println("The character is located in " + location);
       }
       else {
           System.out.println("Sorry! The character you are looking for "
               + "is not in park today");
       }
   }
   String[] items = getItems();
   String[] prices = getPrices();
   choice = ' ';
   System.out.println("Would you like to view the menu?(Y/N)");
   choice = s.next().charAt(0);
   if(choice == 'N' || choice == 'n') {
       System.exit(0);
   }
   while(choice == 'Y' || choice == 'y') {
       for(int i = 0; i < items.length; i++) {
           System.out.println("Enter " + (i+1) + " for " + items[i]);
       }
       int option = s.nextInt();
       System.out.println("Item : " + items[option-1]);
       System.out.println("Price : " + prices[option-1]);
       totPrice = totPrice + Integer.parseInt(prices[option-1]);
       System.out.println("Do you want to order more(Y/N)?");
       choice = s.next().charAt(0);
   }
   System.out.println("Are you an Annual Pass Holder?(Y/N)?");
   choice = s.next().charAt(0);
   if(choice == 'Y' || choice == 'y') {
       System.out.println("Your bill amount due : $" +        ((double)totPrice -
   ((double)(totPrice*15))/100));
       System.exit(1);
   }
   System.out.println("Your bill amount due : $" + totPrice);
}
}
</code>```

答:
You need to escape the dollar sign in your path.

To match a dollar sign, use "\$"

```<code>public static String[] getPrices() {
   try {
       //Read from file
           String[] aPrices = new String(Files.readAllBytes
           (Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
           .split("\n");
           return aPrices;
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
}
</code>```

Body:
My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda

The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop

Error: Could not find or load main class Disneyland
    package com.Kassie$;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
   try {
       //Read from file
       String[] aItems = new String(Files.readAllBytes
           (Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
           .split("\n");
       return aItems;
    } catch (IOException e) {
       e.printStackTrace();
   }
   return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
   try {
       //Read from file
           String[] aPrices = new String(Files.readAllBytes
           (Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
           .split("\n");
           return aPrices;
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
   for(int i = 0; i < storedValue.length; i++) {
       if(storedValue[i][0].equals(name)) {
           return (storedValue[i][1]);
       }
   }
   return null;
}
public static void main(String[] args) {
   char choice = ' ';
   int totPrice = 0;
   Scanner s = new Scanner(System.in);
   String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
       {"Minnie Mouse", "Toon Town"},
       {"Goofy","Frontier Land"},
       {"Pluto","Tomorrowland"},
       {"Belle","Fantasyland"},
       {"Jasmine", "Adventureland"}};
   System.out.println("Do you like to know the "
       + "Disney Character's location(Y/N)?");
   choice = s.next().charAt(0);
   if(choice == 'Y' || choice == 'y') {
       System.out.println("Enter the name of the character");
       String aName = s.next();
       String location = findLocation(characterLocation,aName);
       if( location != null) {
           System.out.println("The character is located in " + location);
       }
       else {
           System.out.println("Sorry! The character you are looking for "
               + "is not in park today");
       }
   }
   String[] items = getItems();
   String[] prices = getPrices();
   choice = ' ';
   System.out.println("Would you like to view the menu?(Y/N)");
   choice = s.next().charAt(0);
   if(choice == 'N' || choice == 'n') {
       System.exit(0);
   }
   while(choice == 'Y' || choice == 'y') {
       for(int i = 0; i < items.length; i++) {
           System.out.println("Enter " + (i+1) + " for " + items[i]);
       }
       int option = s.nextInt();
       System.out.println("Item : " + items[option-1]);
       System.out.println("Price : " + prices[option-1]);
       totPrice = totPrice + Integer.parseInt(prices[option-1]);
       System.out.println("Do you want to order more(Y/N)?");
       choice = s.next().charAt(0);
   }
   System.out.println("Are you an Annual Pass Holder?(Y/N)?");
   choice = s.next().charAt(0);
   if(choice == 'Y' || choice == 'y') {
       System.out.println("Your bill amount due : $" +        ((double)totPrice -
   ((double)(totPrice*15))/100));
       System.exit(1);
   }
   System.out.println("Your bill amount due : $" + totPrice);
}
}

Body:
You need to escape the dollar sign in your path.

To match a dollar sign, use "\$"

public static String[] getPrices() {
   try {
       //Read from file
           String[] aPrices = new String(Files.readAllBytes
           (Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
           .split("\n");
           return aPrices;
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
}


问:
How to provide a SAS token to Azure CLI within PowerShell
I'm using the Azure CLI 2.0 from PowerShell to manage a storage account. I have a SAS token (which I am storing in a variable) and I want to use it in a command. Here's the script I'm running:

```<code>$sasToken = 'st=2017-11-13T10%3A55%3A06Z&se=2017-11-13T11%3A27%3A06Z&sp=w&spr=https&sv=2017-04-17&sr=c&sig=%2BA6LDTwHes6JdxEAHXSvbYc70y30OcznjMVSyFbCXog%3D'

az storage blob upload `
    --account-name mystorageaccount `
    --container-name mycontainer `
    --file c:\temp\file.txt `
    --name file.txt `
    --sas-token $sasToken
</code>```

When I run this, I get this error:

```<code>The specified resource does not exist.
'se' is not recognized as an internal or external command,
operable program or batch file.
'sp' is not recognized as an internal or external command,
operable program or batch file.
'spr' is not recognized as an internal or external command,
operable program or batch file.
'sv' is not recognized as an internal or external command,
operable program or batch file.
'sr' is not recognized as an internal or external command,
operable program or batch file.
'sig' is not recognized as an internal or external command,
operable program or batch file.
</code>```

It appears to me that PowerShell is truncating the SAS token every time it sees an ampersand, and the Azure CLI isn't getting this as all part of the same string.

Is there a way to force PowerShell to call the Azure CLI with the SAS token exactly as-is?

答:
Try wrapping the SAS token in a 2nd set of quotes:

$sasToken = '"st=2017-11-13T10%3A55%3A06Z&se=2017-11-13T11%3A27%3A06Z&sp=w&spr=https&sv=2017-04-17&sr=c&sig=%2BA6LDTwHes6JdxEAHXSvbYc70y30OcznjMVSyFbCXog%3D"'

so that the CLI command looks like this:

--sas-token "st=2017-11-13T10%3A55%3A06Z&se=2017-11-13T11%3A27%3A06Z&sp=w&spr=https&sv=2017-04-17&sr=c&sig=%2BA6LDTwHes6JdxEAHXSvbYc70y30OcznjMVSyFbCXog%3D"

Body:
I'm using the Azure CLI 2.0 from PowerShell to manage a storage account. I have a SAS token (which I am storing in a variable) and I want to use it in a command. Here's the script I'm running:

$sasToken = 'st=2017-11-13T10%3A55%3A06Z&se=2017-11-13T11%3A27%3A06Z&sp=w&spr=https&sv=2017-04-17&sr=c&sig=%2BA6LDTwHes6JdxEAHXSvbYc70y30OcznjMVSyFbCXog%3D'

az storage blob upload `
    --account-name mystorageaccount `
    --container-name mycontainer `
    --file c:\temp\file.txt `
    --name file.txt `
    --sas-token $sasToken

When I run this, I get this error:

The specified resource does not exist.
'se' is not recognized as an internal or external command,
operable program or batch file.
'sp' is not recognized as an internal or external command,
operable program or batch file.
'spr' is not recognized as an internal or external command,
operable program or batch file.
'sv' is not recognized as an internal or external command,
operable program or batch file.
'sr' is not recognized as an internal or external command,
operable program or batch file.
'sig' is not recognized as an internal or external command,
operable program or batch file.

It appears to me that PowerShell is truncating the SAS token every time it sees an ampersand, and the Azure CLI isn't getting this as all part of the same string.

Is there a way to force PowerShell to call the Azure CLI with the SAS token exactly as-is?


问:
Node.js DocumentDB DocumentClient - how to create a collectionLink
When using Node.js documentdb.DocumentClient I can easily create a database and a collection, but if all I want to do is query an existing collection how do I build the collectionLink that should be the 1st parameter in this line of code?
What should the collectionLink contain?</p>

```<code>client.queryDocuments(collectionLink, "SELECT * FROM docs d WHERE d.Email = 'test@test.com'").toArray(function(err, results){});
</code>```

答:
A DocumentCollection link is built on the format
dbs/databaseId/colls/collectionId

So if your databaseId was MyDatabase and your collectionId was MyCollection then the collectionLink would be:

dbs/mydatabase/colls/mycollection

Or more simply, you can use the DocumentClient you already have to build this for you:

```<code>var collectionLink = client.createDocumentCollectionUri(databaseId, collectionId);
</code>```

Body:
When using Node.js documentdb.DocumentClient I can easily create a database and a collection, but if all I want to do is query an existing collection how do I build the collectionLink that should be the 1st parameter in this line of code?
What should the collectionLink contain?

client.queryDocuments(collectionLink, "SELECT * FROM docs d WHERE d.Email = 'test@test.com'").toArray(function(err, results){});

Body:
A DocumentCollection link is built on the format
dbs/databaseId/colls/collectionId

So if your databaseId was MyDatabase and your collectionId was MyCollection then the collectionLink would be:

dbs/mydatabase/colls/mycollection

Or more simply, you can use the DocumentClient you already have to build this for you:

var collectionLink = client.createDocumentCollectionUri(databaseId, collectionId);


问:
can two injectable (service.ts) communicate with each other in angular 4?
can two services.ts files that are injectable can communicate with each other, for example, can one service call the function or method of another service file .
if yes then how this is possible nevertheless whats the reason?</p>

答:
Two services can communicate with each other using "Injector" class.

```<code>import { Injectable, Injector } from '@angular/core';
import { MyService } from 'app/services/my.service';
</code>```

Inject "Injector" object inside your constructor

```<code>constructor(private injector: Injector) {}
</code>```

Then call your service

```<code>var myService = this.injector.get(MyService);
myService.get();
</code>```

Body:
Two services can communicate with each other using "Injector" class.

import { Injectable, Injector } from '@angular/core';
import { MyService } from 'app/services/my.service';

Inject "Injector" object inside your constructor

constructor(private injector: Injector) {}

Then call your service

var myService = this.injector.get(MyService);
myService.get();


问:
Java coursework questions
I'm an undergraduate student and I'm looking for help with troubleshooting the code I'm writing for my coursework.

```<code>import weather.WeatherData;
import Weather.data.classes.WeatherReading;
import Weather.data.classes.WeatherStation;

/**
 * QUESTION 01
 *
 * If you decide to answer question 01 then the main method below should be used as the entry point for your application
 * You may use as many other classes as you feel necessary as long as all code is supplied
 *
 * Remember to add -Xmx1024m to the VM arguments using menu run --> run configurations in eclipse
 */
public class Answer01 {
    public static void main(String[] args) {
        System.out.println("Question 01");
        /*
         * Add your code below
         */
        WeatherStation x = new WeatherStation("site", "a", 1.1, 1.0);
        WeatherReading y = new WeatherReading(1,2,3,4,5,6);
        String line[] = WeatherData.getData();
        ArrayList<WeatherStation>weatherSize = new ArrayList<>();
        for(int i = 1; i < line.length; i++){
        String [] split = line[i].split(",");
        WeatherStation z = new WeatherStation(line[0], line[1], Double.parseDouble(line[2]), Double.parseDouble(line[3]));
        weatherSize.add(z);
        }

        System.out.println(weatherSize.size() + " test");

    }
}
</code>```

The problem I'm having here is that weatherSize.size() is printing out 0 instead of the correct answer which is 136.

The code draws data from a JAR file called weather.WeatherData and I created two classes which have getters and setters and toString() methods, called WeatherStation and WeatherReading.

The jar file is library item called WeatherData.jar and it records weather data recorded at different locations in the uk.

String[] weatherData = WeatherData.getData();

Returns an array of string and the first element at index 0 contains header information.

Element 0: SiteId,SiteName,Latitude,Longitude,Year,Month,Date,Hour,WindSpeed,Temperature
Element 1:
3002,BALTASOUND (3002),60.7490,-0.8540,2015,01,01,0,21,8.70

When I run my code for Answer01 it simply says: 0 test

```<code>    package Weather.data.classes;

    public class WeatherStation {
    public String siteId;
    public String siteName;
    public double latitude;
    public double longitude;

    public WeatherStation(String siteId, String siteName, double latitude, double longitute){
        super();
        this.siteId = siteId;
        this.siteName = siteName;
        this.latitude = latitude;
        this.longitude = longitude;
        }
    }
</code>```

And WeatherReading:

```<code>package Weather.data.classes;

public class WeatherReading {
    public int year;
    public int month;
    public int date;
    public int hour;
    public int windSpeed;
    public int temperature;

    public WeatherReading(int year, int month, int date, int hour, int windSpeed, int temperature){
        this.year = year;
        this.month = month;
        this.date = date;
        this.hour = hour;
        this.windSpeed = windSpeed;
        this.temperature = temperature;
    }
}
</code>```

答:
```<code> String line[] = WeatherData.getData();
</code>```

Are you sure WeatherData.getData(); returning something ? and there exits ","in the String which it is returning.And Kindly tell about the jar you importing so that i can correct if problem not solves.
I think you are not clear what you are doing.

Title: Java coursework questions

Body:
I'm an undergraduate student and I'm looking for help with troubleshooting the code I'm writing for my coursework.

import weather.WeatherData;
import Weather.data.classes.WeatherReading;
import Weather.data.classes.WeatherStation;

/**
 * QUESTION 01
 *
 * If you decide to answer question 01 then the main method below should be used as the entry point for your application
 * You may use as many other classes as you feel necessary as long as all code is supplied
 *
 * Remember to add -Xmx1024m to the VM arguments using menu run --> run configurations in eclipse
 */
public class Answer01 {
    public static void main(String[] args) {
        System.out.println("Question 01");
        /*
         * Add your code below
         */
        WeatherStation x = new WeatherStation("site", "a", 1.1, 1.0);
        WeatherReading y = new WeatherReading(1,2,3,4,5,6);
        String line[] = WeatherData.getData();
        ArrayList<WeatherStation>weatherSize = new ArrayList<>();
        for(int i = 1; i < line.length; i++){
        String [] split = line[i].split(",");
        WeatherStation z = new WeatherStation(line[0], line[1], Double.parseDouble(line[2]), Double.parseDouble(line[3]));
        weatherSize.add(z);
        }

        System.out.println(weatherSize.size() + " test");

    }
}

The problem I'm having here is that weatherSize.size() is printing out 0 instead of the correct answer which is 136.

The code draws data from a JAR file called weather.WeatherData and I created two classes which have getters and setters and toString() methods, called WeatherStation and WeatherReading.

The jar file is library item called WeatherData.jar and it records weather data recorded at different locations in the uk.

String[] weatherData = WeatherData.getData();

Returns an array of string and the first element at index 0 contains header information.

Element 0: SiteId,SiteName,Latitude,Longitude,Year,Month,Date,Hour,WindSpeed,Temperature
Element 1:
3002,BALTASOUND (3002),60.7490,-0.8540,2015,01,01,0,21,8.70

When I run my code for Answer01 it simply says: 0 test

    package Weather.data.classes;

    public class WeatherStation {
    public String siteId;
    public String siteName;
    public double latitude;
    public double longitude;

    public WeatherStation(String siteId, String siteName, double latitude, double longitute){
        super();
        this.siteId = siteId;
        this.siteName = siteName;
        this.latitude = latitude;
        this.longitude = longitude;
        }
    }

And WeatherReading:

package Weather.data.classes;

public class WeatherReading {
    public int year;
    public int month;
    public int date;
    public int hour;
    public int windSpeed;
    public int temperature;

    public WeatherReading(int year, int month, int date, int hour, int windSpeed, int temperature){
        this.year = year;
        this.month = month;
        this.date = date;
        this.hour = hour;
        this.windSpeed = windSpeed;
        this.temperature = temperature;
    }
}

Body:
 String line[] = WeatherData.getData();

Are you sure WeatherData.getData(); returning something ? and there exits ","in the String which it is returning.And Kindly tell about the jar you importing so that i can correct if problem not solves.
I think you are not clear what you are doing.


问:
How to use event like (onSelect) instead of (change)

because for (change) event to trigger , We  need to change the selected data in UI. Can we use EventEmitter for this. I want one event which gets triggered when we select one or more elements. Thanks

<select multiple (change)="setSelected($event.target)">
    <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
</select>

```<code>export class myClass {
...
myOptions: [];
...
setSelected(selectElement) {
    for (var i = 0; i < selectElement.options.length; i++) {
        var optionElement = selectElement.options[i];
        var optionModel = this.myOptions[i];

        if (optionElement.selected == true) { optionModel.selected = true; }
        else { optionModel.selected = false; }
    }
}
</code>```

}

答:
```<code><select [ngModel]="selectedItem" (ngModelChange)="setSelected($event)">
setSelected(newVal) {
    this.selectedItem = newVal //If changing the model is required
    // ... do other stuff here ...
}
</code>```

Hope that helps

Body:
because for (change) event to trigger , We  need to change the selected data in UI. Can we use EventEmitter for this. I want one event which gets triggered when we select one or more elements. Thanks

<select multiple (change)="setSelected($event.target)">
    <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
</select>

export class myClass {
...
myOptions: [];
...
setSelected(selectElement) {
    for (var i = 0; i < selectElement.options.length; i++) {
        var optionElement = selectElement.options[i];
        var optionModel = this.myOptions[i];

        if (optionElement.selected == true) { optionModel.selected = true; }
        else { optionModel.selected = false; }
    }
}

}

Body:
<select [ngModel]="selectedItem" (ngModelChange)="setSelected($event)">
setSelected(newVal) {
    this.selectedItem = newVal //If changing the model is required
    // ... do other stuff here ...
}

Hope that helps


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
A number of answers appeal to the spec. In what turns out to be an unusual turn of events, the C# 4 spec does not justify the behaviour specifically mentioned of comparison of two null literals. In fact, a strict reading of the spec says that "null == null" should give an ambiguity error! (This is due to an editing error made during the cleanup of the C# 2 specification in preparation for C# 3; it is not the intention of the spec authors to make this illegal.)

Read the spec carefully if you don't believe me. It says that there are equality operators defined on int, uint, long, ulong, bool, decimal, double, float, string, enums, delegates and objects, plus the lifted-to-nullable versions of all the value type operators.

Now, immediately we have a problem; this set is infinitely large. In practice we do not form the infinite set of all operators on all possible delegate and enum types. The spec needs to be fixed up here to note that the only operators on enum and delegate types which are added to the candidate sets are those of enum or delegate types that are the types of either argument.

Let's therefore leave enum and delegate types out of it, since neither argument has a type.

We now have an overload resolution problem; we must first eliminate all the inapplicable operators, and then determine the best of the applicable operators.

Clearly the operators defined on all the non-nullable value types are inapplicable. That leaves the operators on the nullable value types, and string, and object.

We can now eliminate some for reasons of "betterness". The better operator is the one with the more specific types. int? is more specific than any of the other nullable numeric types, so all of those are eliminated. String is more specific than object, so object is eliminated.

That leaves equality operators for string, int? and bool? as the applicable operators. Which one is the best?  None of them is better than the other.  Therefore this should be an ambiguity error.

For this behaviour to be justified by the spec we are going to have to emend the specification to note that "null == null" is defined as having the semantics of string equality, and that it is the compile-time constant true.

I actually just discovered this fact yesterday; how odd that you should ask about it.

To answer the questions posed in other answers about why null >= null gives a warning about comparisons to int? -- well, apply the same analysis as I just did. The >= operators on non-nullable value types are inapplicable, and of the ones that are left, the operator on int? is the best. There is no ambiguity error for >= because there is no >= operator defined on bool? or string. The compiler is correctly analyzing the operator as being comparison of two nullable ints.

To answer the more general question about why operators on null values (as opposed to literals) have a particular unusual behaviour, see my answer to the duplicate question.  It clearly explains the design criteria that justify this decision. In short: operations on null should have the semantics of operations on "I don't know". Is a quantity you don't know greater than or equal to another quantity you don't know?  The only sensible answer is "I don't know!" But we need to turn that into a bool, and the sensible bool is "false". But when comparing for equality, most people think that null should be equal to null even though comparing two things that you don't know for equality should also result in "I don't know". This design decision is the result of trading off many undesirable outcomes against one another to find the least bad one that makes the feature work; it does make the language somewhat inconsistent, I agree.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

ContentLicense: CC BY-SA 2.5


问:
Git ignore deleted folders during a merge?
A developer has been working on some feature branch f1 that branched off of master.

Due to poor modularization of the repo (the system is modular, but lives in a monolithic repo) and other reasons, the developer decided to delete "a bunch of irrelevant stuff" (other modules unrelated to his feature) in the f1 branch. The feature unit-tests successfully, but the branch now contains all these deletions of entire other modules of the system.

What is the easiest, most painless way to merge f1 back into master while ignoring folder deletions? Assume some of the files modified in f1 were also modified in the evolution of master.

Additional Requirement
Work on the f1 branch may need to continue for a little while after the merge. I'm not quite sure how the answers proposed so far would impact that.

答:
Assuming the quality of your source history is a priority, I would recommend rewriting the history of F1 to exclude the deletes.  Any "painless fix" is going to leave weird deletes and adds that will complicate future analysis of the project evolution.

(As an aside, the practice of deleting "parts of the project I'm not working on" is objectively incorrect.  See "sparse checkout" for a potential solution that is not objectively incorrect.)

The more developers that have a copy of the F1 branch, and the more changes (if any) anyone has that are based on the F1 branch, the more tedious a history rewrite would be.  However, if this is a feature branch that was only worked on by the one developer, and no merge of the feature has been pushed to origin, then it may be rather straightforward.

If F1 itself is linear, a rebase will do.  For example

```<code>x -- x -- x -- x <--(master)
      \
       A -- B -- C <--(F1)
</code>```

Because master..F1 (the set of commits reachable from F1 but not reachable from master; A, B, and C in this example) does not include any merges, and no other branches are based on any commit in master..F1, this is a simple case for rebase.

```<code>git rebase -i master f1
</code>```

You'll see a "TODO" list containing an entry for each commit on F1.  Change the first commit's command from pick to edit.  Exit the editor and the rebase begins.

The rebase pauses and gives you a prompt after tentatively accepting A "as is".  Now you need to put back the files that were deleted.  You can use something like git show --name-status to identify the deleted files, and git checkout HEAD^ -- path/to/deleted/file/or/directory to restore something that was deleted.

Once you've restored all of the files, git commit --amend.  Then continue the rebase.

There are other procedures as well that will work; this is one of the simplest cases.

After the rebase, if F1 has ever been pushed before, then you probably need to force-push it.  git push -f  At this point anyone who has a copy of F1 in their local repo needs to recover (see "recover from upstream rebase" in the git rebase documentation).  If anyone has worked based on F1 they'll have to rebase it to the new F1.

You should be able to complete the merge against the new F1 without delete issues.

Body:
Assuming the quality of your source history is a priority, I would recommend rewriting the history of F1 to exclude the deletes.  Any "painless fix" is going to leave weird deletes and adds that will complicate future analysis of the project evolution.

(As an aside, the practice of deleting "parts of the project I'm not working on" is objectively incorrect.  See "sparse checkout" for a potential solution that is not objectively incorrect.)

The more developers that have a copy of the F1 branch, and the more changes (if any) anyone has that are based on the F1 branch, the more tedious a history rewrite would be.  However, if this is a feature branch that was only worked on by the one developer, and no merge of the feature has been pushed to origin, then it may be rather straightforward.

If F1 itself is linear, a rebase will do.  For example

x -- x -- x -- x <--(master)
      \
       A -- B -- C <--(F1)

Because master..F1 (the set of commits reachable from F1 but not reachable from master; A, B, and C in this example) does not include any merges, and no other branches are based on any commit in master..F1, this is a simple case for rebase.

git rebase -i master f1

You'll see a "TODO" list containing an entry for each commit on F1.  Change the first commit's command from pick to edit.  Exit the editor and the rebase begins.

The rebase pauses and gives you a prompt after tentatively accepting A "as is".  Now you need to put back the files that were deleted.  You can use something like git show --name-status to identify the deleted files, and git checkout HEAD^ -- path/to/deleted/file/or/directory to restore something that was deleted.

Once you've restored all of the files, git commit --amend.  Then continue the rebase.

There are other procedures as well that will work; this is one of the simplest cases.

After the rebase, if F1 has ever been pushed before, then you probably need to force-push it.  git push -f  At this point anyone who has a copy of F1 in their local repo needs to recover (see "recover from upstream rebase" in the git rebase documentation).  If anyone has worked based on F1 they'll have to rebase it to the new F1.

You should be able to complete the merge against the new F1 without delete issues.


问:
How to prevent long words from breaking my div?
Ever since switching from TABLE-layout to DIV-layout, one common problem remains:

PROBLEM: you fill your DIV with dynamic text and inevitably there is a super-long word that extends over the edge of your div column and makes your site look unprofessional.

RETRO-WHINING: This never happened with table layouts. A table cell will always nicely expand to the width of the longest word.

SEVERITY: I see this problem on even the most major sites, especially on German sites where even common words such as "speed limit" are very long ("Geschwindigkeitsbegrenzung").

Does anyone have a workable solution to this?

答:
I've written a function that works great where it inserts  x letters into the word for good line breaking. All answers here did not support all browsers and devices but this works well using PHP:

```<code>/**
 * Add line-break to text x characters in
 * @param  string  $text
 * @param  integer $characters_in
 * @return string
 */
function line_break_text($text, $characters_in = 10) {

    $split = explode(' ', $text);

    if ( ! empty($split)) {

        foreach ($split as $key => $var) {

            if ( strlen($var) > $characters_in ) {

                $split[$key] = substr_replace($var, '', $characters_in, 0);

            }

        }

    }

    return implode(' ', $split);

}
</code>```

OwnerDisplayName: Edward Tanguay

Body:
I've written a function that works great where it inserts &shy; x letters into the word for good line breaking. All answers here did not support all browsers and devices but this works well using PHP:

/**
 * Add line-break to text x characters in
 * @param  string  $text
 * @param  integer $characters_in
 * @return string
 */
function line_break_text($text, $characters_in = 10) {

    $split = explode(' ', $text);

    if ( ! empty($split)) {

        foreach ($split as $key => $var) {

            if ( strlen($var) > $characters_in ) {

                $split[$key] = substr_replace($var, '&shy;', $characters_in, 0);

            }

        }

    }

    return implode(' ', $split);

}


问:
Angular CLI Error
If I want to make ng serve, I get this error :

ERROR in TypeError: Cannot read property 'provide' of undefined
      at C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@angular\compiler-cli\src\ngtools_impl.js:150:14
      at Array.reduce (native)
      at _collectRoutes (C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@angular\compiler-cli\src\ngtools_impl.js:149:22)
      at _extractLazyRoutesFromStaticModule (C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@angular\compiler-cli\src\ngtools_impl.js:113:8)
      at Object.listLazyRoutesOfModule (C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
      at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
      at AotPlugin._getLazyRoutesFromNgtools (C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@ngtools\webpack\src\plugin.js:207:44)
      at _donePromise.Promise.resolve.then.then.then.then.then (C:\Users\Samir\Documents\AngularProjects\test\angular_website\node_modules\@ngtools\webpack\src\plugin.js:443:24)

I also deleted all node_modules and installed the newest version of the cli,
but this is not my code. Has someone a solution for this problem ?

答:
In app.module.ts, are you using any import like this:

```<code>import MyImport from 'myPath';
</code>```

?
If yes, you need change your MyImport.ts to be imported like this:

```<code>import { MyImport } from 'myPath';
</code>```

Title: Angular CLI Error

Body:
In app.module.ts, are you using any import like this:

import MyImport from 'myPath';

?
If yes, you need change your MyImport.ts to be imported like this:

import { MyImport } from 'myPath';


问:
Rails 3 has_many :through is only adding id from on side of the relationship
I am trying to move from a has_many, belongs_to relationship to a has_many :through relationship with my Project and User model. However when I test it in the rails console only one side of the relationship seems to get set in the join model.

I currently have it set up like this:

```<code>class Project < ActiveRecord::Base
  has_many :collaborations
  has_many :users, :through => :collaborations
end

class User < ActiveRecord::Base
  has_many :collaborations
  has_many :projects, :through => :collaborations
end

class Collaboration < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end
</code>```

Then in the console I'm typing in:

```<code>me = User.find(1)

p = Project.new(:name => "somename")
p.users << me
p.save
</code>```

And what happens is that the Collaboration model gets the project_id set but not the user_id.

And the opposite happens (the user_id gets set but not the project_id) when I do something like this:

```<code>me.projects << p
</code>```

Basically, it creates a "Collaboration" but only one side of the relationship gets saved.

I have been stuck at this for hours now and I feel like it's something minor - maybe something left over from when I was doing the one-to-many relationship between these two models.

---Edit---
This is what the schema looks like:

```<code>create_table "collaborations", :force => true do |t|
  t.integer  "project_id"
  t.integer  "user_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "projects", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.boolean  "shared",      :default => false
  t.integer  "position",    :default => 0
  t.string   "permalink"
  t.text     "description"
end

create_table "users", :force => true do |t|
  t.string   "username"
  t.string   "email"
  t.string   "crypted_password"
  t.string   "password_salt"
  t.string   "persistence_token"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "role"
  t.string   "first_name"
  t.string   "last_name"
  t.string   "perishable_token",  :default => "", :null => false
  t.integer  "avatar",            :default => 0
end
</code>```

Any help would be really appreciated!

答:
It sounds like you're trying to build a has_and_belongs_to_many relationship in a roundabout way. Your Collaboration model looks exactly like a join model.

I'd suggest going with a proper has_and_belongs_to_many relationship. Basically, what you have will become:

```<code>class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :projects
end
</code>```

And then you'll need to create a migration for the join table:

```<code>def self.up
  create_table :projects_users, :id => false do |t|
    t.references :project, :user
  end
end

def self.down
  drop_table :projects_users
end
</code>```

You should then be able to do User.find(123).projects and Project.find(321).users, as well as the << you're trying to do. For further explanation of how has_and_belongs_to_many works, as well as the various methods you can use on the associations, please see the Rails docs.

Body:
I am trying to move from a has_many, belongs_to relationship to a has_many :through relationship with my Project and User model. However when I test it in the rails console only one side of the relationship seems to get set in the join model.

I currently have it set up like this:

class Project < ActiveRecord::Base
  has_many :collaborations
  has_many :users, :through => :collaborations
end

class User < ActiveRecord::Base
  has_many :collaborations
  has_many :projects, :through => :collaborations
end

class Collaboration < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

Then in the console I'm typing in:

me = User.find(1)

p = Project.new(:name => "somename")
p.users << me
p.save

And what happens is that the Collaboration model gets the project_id set but not the user_id.

And the opposite happens (the user_id gets set but not the project_id) when I do something like this:

me.projects << p

Basically, it creates a "Collaboration" but only one side of the relationship gets saved.

I have been stuck at this for hours now and I feel like it's something minor - maybe something left over from when I was doing the one-to-many relationship between these two models.

---Edit---
This is what the schema looks like:

create_table "collaborations", :force => true do |t|
  t.integer  "project_id"
  t.integer  "user_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "projects", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.boolean  "shared",      :default => false
  t.integer  "position",    :default => 0
  t.string   "permalink"
  t.text     "description"
end

create_table "users", :force => true do |t|
  t.string   "username"
  t.string   "email"
  t.string   "crypted_password"
  t.string   "password_salt"
  t.string   "persistence_token"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "role"
  t.string   "first_name"
  t.string   "last_name"
  t.string   "perishable_token",  :default => "", :null => false
  t.integer  "avatar",            :default => 0
end

Any help would be really appreciated!

Body:
It sounds like you're trying to build a has_and_belongs_to_many relationship in a roundabout way. Your Collaboration model looks exactly like a join model.

I'd suggest going with a proper has_and_belongs_to_many relationship. Basically, what you have will become:

class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :projects
end

And then you'll need to create a migration for the join table:

def self.up
  create_table :projects_users, :id => false do |t|
    t.references :project, :user
  end
end

def self.down
  drop_table :projects_users
end

You should then be able to do User.find(123).projects and Project.find(321).users, as well as the << you're trying to do. For further explanation of how has_and_belongs_to_many works, as well as the various methods you can use on the associations, please see the Rails docs.


问:
Laravel 5: Convert existing web.php to api.php (RESTFUL API)
I have a set of currently working routes on Laravel 5.3 (they are either called routes or web.php).

For example:

```<code>Route::group(['middleware' => ['web','auth']], function () {

Route::get('/post-aaron', 'ProductsController@postaaron');
Route::post('/post-aaron', 'ProductsController@savepostaaron');
Route::get('/aarons-posted', 'ProductsController@aaronsposted');
Route::get('/aaron-board', 'ProductsController@aaronboard');
Route::get('/edit-aaron/{id}', 'ProductsController@editaaron');
Route::get('/edit-aaron', 'ProductsController@updatepostaaron');

});
</code>```

I want to make RESTFUL API for scaling across different platforms. How do I convert my existing web.php into api.php?

答:
This depends on the code and logic in your controllers. Most likely, your controller are returing views. For example, return view('aaron-board').
However, a RESTful api will require a JSON response, something like return response()->json(['data' => 'users']).

It's not an easy task to convert a traditional web app to an api if you did not plan that from the beginning. However, it's doable.

Depending on the scale of your application, you may want to have dedicated controllers to process api requests or, if your application is small, you can have them processed by the current/same controllers. Another issue is routing. The middleware web will cause issues with api requests.

Here is what I would do as a starting point. I will adapt my controllers to response to api requests as well as normal request for the web application.

For example, let's say we have the following route:

```<code>// web.php

Route::get('/users', 'UsersController@index');
</code>```

And our index method:

```<code>public function index(Request $request)
{
    $users = App\User::paginate();

    return view('users.index', compact('users');
}
</code>```

We can basically change the index method to return a JSON response if the coming request is an api request as the follwing:

```<code>public function index(Request $request)
{
    $users = App\User::paginate();

    if ($request->wantsJson()) {

         return response()->json(['data' => $users]);

    }

    return view('users.index', compact('users');
}
</code>```

Now for the route, we'll duplicate the same route in the api.php file.

```<code>// api.php

Route::get('/users', 'UsersController@index');
</code>```

This will give our application two routes:

www.example.com/users (will return a view)

www.example.com/api/users (will return a JSON response)

Note I'is important to set proper headers for the api requests to get the JSON response. i.e Accept: application/json. And also be mindful of CORS configurations.

As a side note, you're adding the web middleware to your routes in web.php file. This is fine but unnecessary. The middleware is already added by the RouteServiceProvider check the method mapWebRoutes at this file. You will see also that mapApiRoutes() adds the api middleware to all routes defined in the api.php file.

Body:
I have a set of currently working routes on Laravel 5.3 (they are either called routes or web.php).

For example:

Route::group(['middleware' => ['web','auth']], function () {

Route::get('/post-aaron', 'ProductsController@postaaron');
Route::post('/post-aaron', 'ProductsController@savepostaaron');
Route::get('/aarons-posted', 'ProductsController@aaronsposted');
Route::get('/aaron-board', 'ProductsController@aaronboard');
Route::get('/edit-aaron/{id}', 'ProductsController@editaaron');
Route::get('/edit-aaron', 'ProductsController@updatepostaaron');

});

I want to make RESTFUL API for scaling across different platforms. How do I convert my existing web.php into api.php?

Body:
This depends on the code and logic in your controllers. Most likely, your controller are returing views. For example, return view('aaron-board').
However, a RESTful api will require a JSON response, something like return response()->json(['data' => 'users']).

It's not an easy task to convert a traditional web app to an api if you did not plan that from the beginning. However, it's doable.

Depending on the scale of your application, you may want to have dedicated controllers to process api requests or, if your application is small, you can have them processed by the current/same controllers. Another issue is routing. The middleware web will cause issues with api requests.

Here is what I would do as a starting point. I will adapt my controllers to response to api requests as well as normal request for the web application.

For example, let's say we have the following route:

// web.php

Route::get('/users', 'UsersController@index');

And our index method:

public function index(Request $request)
{
    $users = App\User::paginate();

    return view('users.index', compact('users');
}

We can basically change the index method to return a JSON response if the coming request is an api request as the follwing:

public function index(Request $request)
{
    $users = App\User::paginate();

    if ($request->wantsJson()) {

         return response()->json(['data' => $users]);

    }

    return view('users.index', compact('users');
}

Now for the route, we'll duplicate the same route in the api.php file.

// api.php

Route::get('/users', 'UsersController@index');

This will give our application two routes:

www.example.com/users (will return a view)

www.example.com/api/users (will return a JSON response)

Note I'is important to set proper headers for the api requests to get the JSON response. i.e Accept: application/json. And also be mindful of CORS configurations.

As a side note, you're adding the web middleware to your routes in web.php file. This is fine but unnecessary. The middleware is already added by the RouteServiceProvider check the method mapWebRoutes at this file. You will see also that mapApiRoutes() adds the api middleware to all routes defined in the api.php file.


问:
how can i install the packages in r properly and correctly using Rstudio app?
I tried to install "xlsx" package using Rstudio, and i couldn't install it.

I am trying to install my packages using install.packages("xlsxjars").  I already tried doing that from Tools window in Rstudio app, and I tried using the console.

I am using Linux (Gnome 17.04).  I get this error:

input

```<code>install.packages("xlsxjars")
</code>```

output

```<code>Installing package into ‘/home/aim/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/xlsxjars_0.6.1.tar.gz'
Error in install.packages : error reading from connection
</code>```

答:
I spent a while struggling with that too. Eventually I just gave up as the java in that package was out of date and I would have needed to load older Java up to get it to run. I would suggest readxl instead.

A simple intro to the package can be found here: https://www.datacamp.com/community/tutorials/r-tutorial-read-excel-into-r#readxl

Body:
I tried to install "xlsx" package using Rstudio, and i couldn't install it.

I am trying to install my packages using install.packages("xlsxjars").  I already tried doing that from Tools window in Rstudio app, and I tried using the console.

I am using Linux (Gnome 17.04).  I get this error:

input

install.packages("xlsxjars")

output

Installing package into ‘/home/aim/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/xlsxjars_0.6.1.tar.gz'
Error in install.packages : error reading from connection


问:
Child elements flowing out of parent in Firefox
In Chrome, when I search for recipes on my website, it will stretch the element with the id of recipeSection to fit all the recipes that match the search request.

However in Firefox, the child elements will just flow on out of the parent element (or when I open dev tools, they all smush together to fit in the container??).

I've done a lot of research on positioning and flow in the last couple hours and looking at similar questions on StackOverflow - I've been yet to find anything that can fix my issue. Any ideas?

You can test it at this website

Just put in any ingredient in the searchbox at the top of the page. Flour works. The project uses materialize framework but it's not being used very much here.

#recipeSection {
  width: 70%;
  height: auto;
  background-color: #e5e5e5;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.recipeStyle {
  width: 80%;
  height: auto;
  margin: 2.5%;
  padding: 1%;
  border-radius: 5px;
  font-size: 2.2rem;
  color: #2d2d2d;
  text-align: left;
  font-family: 'mada';
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recipeTitle {
  width: 80%;
  cursor: pointer;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="recipeSection">
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
  <div class="recipeStyle card grey lighten-5">
    <div class="recipeTitle">Example Recipe Title</div>
  </div>
</div></code>```

答: Changing the padding and margin to be measured in px instead of a percentage has solved the issue. not entirely sure why - is this percentage not being calculated into the height created by auto, leaving the parent container not to be large enough for its child elements? That seems like a peculiar interaction.</p>

Body:
In Chrome, when I search for recipes on my website, it will stretch the element with the id of recipeSection to fit all the recipes that match the search request.

However in Firefox, the child elements will just flow on out of the parent element (or when I open dev tools, they all smush together to fit in the container??).

I've done a lot of research on positioning and flow in the last couple hours and looking at similar questions on StackOverflow - I've been yet to find anything that can fix my issue. Any ideas?

You can test it at this website

Just put in any ingredient in the searchbox at the top of the page. Flour works. The project uses materialize framework but it's not being used very much here.

#recipeSection {
  width: 70%;
  height: auto;
  background-color: #e5e5e5;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.recipeStyle {
  width: 80%;
  height: auto;
  margin: 2.5%;
  padding: 1%;
  border-radius: 5px;
  font-size: 2.2rem;
  color: #2d2d2d;
  text-align: left;
  font-family: 'mada';
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recipeTitle {
  width: 80%;
  cursor: pointer;
  padding: 10px;
}

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title

Example Recipe Title