问:
i have use two dropdown components in single page but only first of them is showing data not second one in nativescript ios
i have used dropdown components in nativescript ios but only one component is loading the data not second one </p>

```<code>//this is my code where i have used dropdown

<StackLayout orientation="horizontal" width="100%" class="padding">
      <StackLayout orientation="horizontal" horizontalAlignment="left" width="50%">
        <GridLayout rows="auto, auto, *" columns="auto, *" class="newstack">
          <TextField [(ngModel)]="userRegister.langauge" class="noline"></TextField>
          <DropDown #Langauge hint="Langauge" class="Nopadding" backgroundcolor="transparent" [items]=ArrayLangauge [selectedIndex]="selectedIndex"
            (selectedIndexChange)="onchangeLanguage(Langauge.selectedIndex)" row="0" colSpan="1"></DropDown>
        </GridLayout>
      </StackLayout>

      <StackLayout orientation="horizontal" textWrap="true" horizontalAlignment="right" width="50%">
        <GridLayout rows="auto, auto, *" columns="auto, *" class="newstack" horizontalAlignment="center">
          <TextField [(ngModel)]="userRegister.state" class="noline"></TextField>
          <DropDown #State hint="State" class="Nopadding" backgroundcolor="transparent" [items]="ArrayState" [selectedIndex]="selectedIndex"
            (selectedIndexChange)="onchangeState(State.selectedIndex)" row="0" colSpan="1"></DropDown>
        </GridLayout>
      </StackLayout>
    </StackLayout>
</code>```

答: Here is the thing that can be causing problem with your second dropdown is that you are using the same variable name for both the dropdown that is [selectedIndex]="selectedIndex" change the name of the string that I have bolded.Try this, apart from that your code is good, I have myself used 5 drop downs in a single page, works for me.

Body:
i have used dropdown components in nativescript ios but only one component is loading the data not second one

//this is my code where i have used dropdown

<StackLayout orientation="horizontal" width="100%" class="padding">
      <StackLayout orientation="horizontal" horizontalAlignment="left" width="50%">
        <GridLayout rows="auto, auto, *" columns="auto, *" class="newstack">
          <TextField [(ngModel)]="userRegister.langauge" class="noline"></TextField>
          <DropDown #Langauge hint="Langauge" class="Nopadding" backgroundcolor="transparent" [items]=ArrayLangauge [selectedIndex]="selectedIndex"
            (selectedIndexChange)="onchangeLanguage(Langauge.selectedIndex)" row="0" colSpan="1"></DropDown>
        </GridLayout>
      </StackLayout>

      <StackLayout orientation="horizontal" textWrap="true" horizontalAlignment="right" width="50%">
        <GridLayout rows="auto, auto, *" columns="auto, *" class="newstack" horizontalAlignment="center">
          <TextField [(ngModel)]="userRegister.state" class="noline"></TextField>
          <DropDown #State hint="State" class="Nopadding" backgroundcolor="transparent" [items]="ArrayState" [selectedIndex]="selectedIndex"
            (selectedIndexChange)="onchangeState(State.selectedIndex)" row="0" colSpan="1"></DropDown>
        </GridLayout>
      </StackLayout>
    </StackLayout>


来源: stackexchange

问:
Django - how to save method apply only on new data
How do I manipulate this method to be applied only on new entries and does not have a previous entry.

When in admin, I will add an record, this method is applied correctly. but when I edit the same record, this method is applied again.

```<code>def save(self):
    p = Product.objects.last()
    if p:
        self.productnumber = 1000 + p.id
    else:
        self.productnumber = 1000
    super(Product, self).save()
</code>```

答:
If you want to execute some code in the save() method, only for non-existing items you should check if a primary key exists.</p>

```<code>def save(self):
    if self.pk is None:
        # Code for new objects
    else:
        # Code for existing objects
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I manipulate this method to be applied only on new entries and does not have a previous entry.

When in admin, I will add an record, this method is applied correctly. but when I edit the same record, this method is applied again.

def save(self):
    p = Product.objects.last()
    if p:
        self.productnumber = 1000 + p.id
    else:
        self.productnumber = 1000
    super(Product, self).save()

Body:
If you want to execute some code in the save() method, only for non-existing items you should check if a primary key exists.

def save(self):
    if self.pk is None:
        # Code for new objects
    else:
        # Code for existing objects


问:
How to add Locale to DecimalFormatter in android
I am trying this code I want apply Locale.US to below code How to do this?</p>

```<code>public String removeDecimalFormat(Double valueDouble) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(false);
    format.setGroupingUsed(true);
    return format.format(valueDouble);
  }
</code>```

答:
```<code>NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat)nf;
</code>```

Body:
I am trying this code I want apply Locale.US to below code How to do this?

public String removeDecimalFormat(Double valueDouble) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(false);
    format.setGroupingUsed(true);
    return format.format(valueDouble);
  }


问:
How to check if node is empty
I'm trying to make a variable, which tells me, whether node1 has something in it or not. node1 can be an empty element  or it may contain an attribute. But right now I would like to know how achieve answer "false" when the node1 is empty .</p>

```<code><xsl:variable name="elementHasData">
    <xsl:choose>
        <xsl:when test="node1 != ''">
            <xsl:value-of select="true()"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="false()"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>
</code>```

答:
```<code><xsl:variable name="elementHasData">
<xsl:choose>
    <xsl:when test="string-length(normalize-space(node1)) gt 0">
        <xsl:value-of select="true()"/>
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="false()"/>
    </xsl:otherwise>
</xsl:choose>
</code>```

Title: How to check if node is empty

Body:
I'm trying to make a variable, which tells me, whether node1 has something in it or not. node1 can be an empty element  or it may contain an attribute. But right now I would like to know how achieve answer "false" when the node1 is empty .

<xsl:variable name="elementHasData">
    <xsl:choose>
        <xsl:when test="node1 != ''">
            <xsl:value-of select="true()"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="false()"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>


问:
What are some good resources for multi-class text classification using word2vec followed by SVM/ANN / Deep Networks?
I need to implement a multi-class text classifier. I thought of using word2vec, can someone lead me to good papers/resources which talk about this.
i would have 4-5 classes and I have loads of data. I have to manually label some of them. It would also be great if someone could throw light on the training size. I plan to use pre-trained word2vec for word embedding.</p>

答:
You can use MLP for this task, check Keras' example for classifying Reuters documents. You can add an embedding layer in the beginning of the model and load it with pretrained model weights.

Keep in mind that there is a multi-class classification which outputs a single class for each input and there is multi-label classification which might output many classes for each input (you didn't say anything about your data character so just letting you know).


问:
How to add a new column to an existing DataFrame?
I have the following indexed DataFrame with named columns and rows not- continuous numbers:

```<code>          a         b         c         d
2  0.671399  0.101208 -0.181532  0.241273
3  0.446172 -0.243316  0.051767  1.577318
5  0.614758  0.075793 -0.451460 -0.012493
</code>```

I would like to add a new column, 'e', to the existing data frame and do not want to change anything in the data frame (i.e., the new column always has the same length as the DataFrame).

```<code>0   -0.335485
1   -1.166658
2   -0.385571
dtype: float64
</code>```

How can I add column e to the above example?

答:
Super simple column assignment

A pandas dataframe is implemented as an ordered dict of columns.

This means that the __getitem__ [] can not only be used to get a certain column, but __setitem__ [] = can be used to assign a new column.

For example, this dataframe can have a column added to it by simply using the [] accessor

```<code>    size      name color
0    big      rose   red
1  small    violet  blue
2  small     tulip   red
3  small  harebell  blue

df['protected'] = ['no', 'no', 'no', 'yes']

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes
</code>```

Note that this works even if the index of the dataframe is off.

```<code>df.index = [3,2,1,0]
df['protected'] = ['no', 'no', 'no', 'yes']
    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes
</code>```

[]= is the way to go, but watch out!

However, if you have a pd.Series and try to assign it to a dataframe where the indexes are off, you will run in to trouble. See example:

```<code>df['protected'] = pd.Series(['no', 'no', 'no', 'yes'])
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no
</code>```

This is because a pd.Series by default has an index enumerated from 0 to n. And the pandas [] = method tries to be "smart"

What actually is going on.

When you use the [] = method pandas is quietly performing an outer join or outer merge using the index of the left hand dataframe and the index of the right hand series. df['column'] = series

Side note

This quickly causes cognitive dissonance, since the []= method is trying to do a lot of different things depending on the input, and the outcome cannot be predicted unless you just know how pandas works. I would therefore advice against the []= in code bases, but when exploring data in a notebook, it is fine.

Going around the problem

If you have a pd.Series and want it assigned from top to bottom, or if you are coding productive code and you are not sure of the index order, it is worth it to safeguard for this kind of issue.

You could downcast the pd.Series to a np.ndarray or a list, this will do the trick.

```<code>df['protected'] = pd.Series(['no', 'no', 'no', 'yes']).values
</code>```

or

```<code>df['protected'] = list(pd.Series(['no', 'no', 'no', 'yes']))
</code>```

But this is not very explicit.

Some coder may come along and say "Hey, this looks redundant, I'll just optimize this away".

Explicit way

Setting the index of the pd.Series to be the index of the df is explicit.

```<code>df['protected'] = pd.Series(['no', 'no', 'no', 'yes'], index=df.index)
</code>```

Or more realistically, you probably have a pd.Series already available.

```<code>protected_series = pd.Series(['no', 'no', 'no', 'yes'])
protected_series.index = df.index

3     no
2     no
1     no
0    yes
</code>```

Can now be assigned

```<code>df['protected'] = protected_series

    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes
</code>```

Alternative way with df.reset_index()

Since the index dissonance is the problem, if you feel that the index of the dataframe should not dictate things, you can simply drop the index, this should be faster, but it is not very clean, since your function now probably does two things.

```<code>df.reset_index(drop=True)
protected_series.reset_index(drop=True)
df['protected'] = protected_series

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes
</code>```

Note on df.assign

While df.assign make it more explicit what you are doing, it actually has all the same problems as the above []=

```<code>df.assign(protected=pd.Series(['no', 'no', 'no', 'yes']))
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no
</code>```

Just watch out with df.assign that your column is not called self. It will cause errors. This makes df.assign smelly, since there are these kind of artifacts in the function.

```<code>df.assign(self=pd.Series(['no', 'no', 'no', 'yes'])
TypeError: assign() got multiple values for keyword argument 'self'
</code>```

You may say, "Well, I'll just not use self then". But who knows how this function changes in the future to support new arguments. Maybe your column name will be an argument in a new update of pandas, causing problems with upgrading.

ContentLicense: CC BY-SA 4.0

Body:
I have the following indexed DataFrame with named columns and rows not- continuous numbers:

          a         b         c         d
2  0.671399  0.101208 -0.181532  0.241273
3  0.446172 -0.243316  0.051767  1.577318
5  0.614758  0.075793 -0.451460 -0.012493

I would like to add a new column, 'e', to the existing data frame and do not want to change anything in the data frame (i.e., the new column always has the same length as the DataFrame).

0   -0.335485
1   -1.166658
2   -0.385571
dtype: float64

How can I add column e to the above example?

Body:
Super simple column assignment

A pandas dataframe is implemented as an ordered dict of columns.

This means that the __getitem__ [] can not only be used to get a certain column, but __setitem__ [] = can be used to assign a new column.

For example, this dataframe can have a column added to it by simply using the [] accessor

    size      name color
0    big      rose   red
1  small    violet  blue
2  small     tulip   red
3  small  harebell  blue

df['protected'] = ['no', 'no', 'no', 'yes']

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes

Note that this works even if the index of the dataframe is off.

df.index = [3,2,1,0]
df['protected'] = ['no', 'no', 'no', 'yes']
    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes

[]= is the way to go, but watch out!

However, if you have a pd.Series and try to assign it to a dataframe where the indexes are off, you will run in to trouble. See example:

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'])
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no

This is because a pd.Series by default has an index enumerated from 0 to n. And the pandas [] = method tries to be "smart"

What actually is going on.

When you use the [] = method pandas is quietly performing an outer join or outer merge using the index of the left hand dataframe and the index of the right hand series. df['column'] = series

Side note

This quickly causes cognitive dissonance, since the []= method is trying to do a lot of different things depending on the input, and the outcome cannot be predicted unless you just know how pandas works. I would therefore advice against the []= in code bases, but when exploring data in a notebook, it is fine.

Going around the problem

If you have a pd.Series and want it assigned from top to bottom, or if you are coding productive code and you are not sure of the index order, it is worth it to safeguard for this kind of issue.

You could downcast the pd.Series to a np.ndarray or a list, this will do the trick.

df['protected'] = pd.Series(['no', 'no', 'no', 'yes']).values

or

df['protected'] = list(pd.Series(['no', 'no', 'no', 'yes']))

But this is not very explicit.

Some coder may come along and say "Hey, this looks redundant, I'll just optimize this away".

Explicit way

Setting the index of the pd.Series to be the index of the df is explicit.

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'], index=df.index)

Or more realistically, you probably have a pd.Series already available.

protected_series = pd.Series(['no', 'no', 'no', 'yes'])
protected_series.index = df.index

3     no
2     no
1     no
0    yes

Can now be assigned

df['protected'] = protected_series

    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes

Alternative way with df.reset_index()

Since the index dissonance is the problem, if you feel that the index of the dataframe should not dictate things, you can simply drop the index, this should be faster, but it is not very clean, since your function now probably does two things.

df.reset_index(drop=True)
protected_series.reset_index(drop=True)
df['protected'] = protected_series

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes

Note on df.assign

While df.assign make it more explicit what you are doing, it actually has all the same problems as the above []=

df.assign(protected=pd.Series(['no', 'no', 'no', 'yes']))
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no

Just watch out with df.assign that your column is not called self. It will cause errors. This makes df.assign smelly, since there are these kind of artifacts in the function.

df.assign(self=pd.Series(['no', 'no', 'no', 'yes'])
TypeError: assign() got multiple values for keyword argument 'self'

You may say, "Well, I'll just not use self then". But who knows how this function changes in the future to support new arguments. Maybe your column name will be an argument in a new update of pandas, causing problems with upgrading.


问:
covariant type A occurs in contravariant position in type A of value a
I have following class:

```<code>case class Box[+A](value: A) {

  def set(a: A): Box[A] = Box(a)

}
</code>```

And the compiler complain:

```<code>Error:(4, 11) covariant type A occurs in contravariant position in type A of value a
  def set(a: A): Box[A] = Box(a)
</code>```

I was searching a lot about the error, but could not find something useful that
help me to understand the error.

Could someone please explain, why the error occurs?

答:
Basically you cant put As in if A is covariant, you can only take it out (ex: returning A). If you wish to put As in, then you would need to make it contravariant.

```<code>case class Box[-A](value: A)
</code>```

Do you want to  do both, then just make it invariant

```<code>case class Box[A](value: A)
</code>```

The best is to keep it covariant and get rid of the setter and go for an immutable approach.

Body:
I have following class:

case class Box[+A](value: A) {

  def set(a: A): Box[A] = Box(a)

}

And the compiler complain:

Error:(4, 11) covariant type A occurs in contravariant position in type A of value a
  def set(a: A): Box[A] = Box(a)

I was searching a lot about the error, but could not find something useful that
help me to understand the error.

Could someone please explain, why the error occurs?

Body:
Basically you cant put As in if A is covariant, you can only take it out (ex: returning A). If you wish to put As in, then you would need to make it contravariant.

case class Box[-A](value: A)

Do you want to  do both, then just make it invariant

case class Box[A](value: A)

The best is to keep it covariant and get rid of the setter and go for an immutable approach.


问:
Odd Umbraco backend behavior after deployment
I've had this before, but can't seem to replicate the steps I did back then.
I've got an Umbraco 4.5.2. site which is running on port 8084 in a development-environment. All works well.

When I want to publish the website to the production server, the umbraco-backend seems to want to keep using the port 8084 and therefor my backend (starting at login) is really strange. Can't seem to update any content (or anything else for that matter).

Now, I assume, it has something to do with caching of sorts, but what setting to change (or what to delete)?

This is my login-screen (no red border on erronous login)

And this is my back-end (there is content - i can see content in the front-end - just not visible in the content-tree);

This is my back-end on the development machine (did nothing but crude copy and edited the database connectionstring to match my production database).

答:
How do you change the port number? I am assuming you're putting it into the hostname on the root item in umbraco content tree.

Have you tried republishing the entire site to make sure the published links do not contain the port number?

ContentLicense: CC BY-SA 2.5


问:
How to generate client key & secret for application registering on my site & how to use OAuth to implement provider
Hi I have an rails application & I want to build an API for the same.I have never worked on API building so far. So please tell me from where should I start to build an API. I want to make it public so that developers can build application using my  API. I have two questions in my mind

How should I generate & assign app key & app secret to an application

I know that for secure API access I have to use OAuth.

I have read following links & tutorials but I am not getting it how to implement it.

I tried to run demo at here but only part is working but I am unable to run client part.

Please guide me in detail to learn this stuff. Thanks in advance...!

答:
It's been a while since this question was asked, and there are many great resources that have been created since, which I'll summarise and link to below.

Adding OAuth 2 provider functionality

The Doorkeeper gem allows you to implement OAuth provider functionality, and is well documented and well maintained. It integrates well with Devise, and there are example applications to learn from.

On the client side of things (for testing the integration, or if you want to provide a Ruby client for external developers), you can use OmniAuth, and the Doorkeeper docs take you through the process of creating a custom strategy.

You may not need OAuth?

Depending on what sort of API you're building, you may find that OAuth is overkill. OAuth is useful in cases where you are a content provider, and the developer is a third party that wants to access information on behalf of a user, but without needing knowledge of their password.

If your use case is more simple (e.g. you can provide a secret token and key directly to the API user), then generating and checking access tokens may be enough. In this case, you generate a key (using SecureRandom.urlsafe_base64, or has_secure_token if you're on Rails 5) and store it. The API user provides this token on each request in order to authenticate, and you can regenerate the token if the original is ever compromised.

More detailed info on that here and here.


问:
Updating firebase in my gradle app module ruined my app. Going back to previous versions does not work
Before any changes my gradle looked like this:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.google.android.gms:play-services-auth:10.0.1'

    compile 'com.firebaseui:firebase-ui-auth:1.0.1'
}
apply plugin: 'com.google.gms.google-services'
</code>```

and

```<code>buildscript {
    repositories {
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

and everything was working fine. Then I updated all of the com/google... dependencies to 10.2.0 version and firebaseui to 1.2.0 as the table here says https://github.com/firebase/FirebaseUI-Android#compatibility-with-firebase--google-play-services-libraries

Then I got some errors on mFirebaseAuth = FirebaseAuth.getInstance() line (sorry but can't remember what exactly) so I changed back all of the versions to 10.0.1 and 1.0.1 and I'm still getting error and my application crashes on start (this error is different than the previous one).

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mnm135.emil.showsmanager, PID: 3837
                  java.lang.NoSuchMethodError: No static method zzdz(Ljava/lang/String;)Z in class Lcom/google/android/gms/common/util/zzw; or its super classes (declaration of 'com.google.android.gms.common.util.zzw' appears in /data/app/com.mnm135.emil.showsmanager-1/base.apk)
                      at com.google.firebase.FirebaseOptions.<init>(Unknown Source)
                      at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                      at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                      at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                      at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                      at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                      at android.app.ActivityThread.installProvider(ActivityThread.java:5811)
                      at android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
                      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
                      at android.app.ActivityThread.-wrap2(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

I tried Invalidate caches/restart, clean and rerun. Even rebooting my pc. Nothing seems to work.

Any ideas?

Edit:

I tried aaroncio's solution, removed apply plugin: 'com.google.gms.google-services' and I'm getting different error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mnm135.emil.showsmanager, PID: 5157
                  java.lang.NoSuchMethodError: No static method zzzq()Ljava/lang/String; in class Lcom/google/android/gms/common/util/zzu; or its super classes (declaration of 'com.google.android.gms.common.util.zzu' appears in /data/app/com.mnm135.emil.showsmanager-2/base.apk)
                      at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                      at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
                      at com.mnm135.emil.showsmanager.base.LoginActivity.onCreate(LoginActivity.java:34)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

Line mentioned in comment is mFirebaseAuth = FirebaseAuth.getInstance();

答:
I solved it removing the line about firebase-authentication in the build-gradle file:

```<code>compile 'com.google.firebase:firebase-auth:10.2.1'
</code>```

I removed the imports about authentication also, I was just making some experiments with firebase auth so its not important in this case, but to others may not be ideal solution.

Body:
Before any changes my gradle looked like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.google.android.gms:play-services-auth:10.0.1'

    compile 'com.firebaseui:firebase-ui-auth:1.0.1'
}
apply plugin: 'com.google.gms.google-services'

and

buildscript {
    repositories {
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and everything was working fine. Then I updated all of the com/google... dependencies to 10.2.0 version and firebaseui to 1.2.0 as the table here says https://github.com/firebase/FirebaseUI-Android#compatibility-with-firebase--google-play-services-libraries

Then I got some errors on mFirebaseAuth = FirebaseAuth.getInstance() line (sorry but can't remember what exactly) so I changed back all of the versions to 10.0.1 and 1.0.1 and I'm still getting error and my application crashes on start (this error is different than the previous one).

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mnm135.emil.showsmanager, PID: 3837
                  java.lang.NoSuchMethodError: No static method zzdz(Ljava/lang/String;)Z in class Lcom/google/android/gms/common/util/zzw; or its super classes (declaration of 'com.google.android.gms.common.util.zzw' appears in /data/app/com.mnm135.emil.showsmanager-1/base.apk)
                      at com.google.firebase.FirebaseOptions.<init>(Unknown Source)
                      at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                      at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                      at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                      at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                      at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                      at android.app.ActivityThread.installProvider(ActivityThread.java:5811)
                      at android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
                      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
                      at android.app.ActivityThread.-wrap2(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I tried Invalidate caches/restart, clean and rerun. Even rebooting my pc. Nothing seems to work.

Any ideas?

Edit:

I tried aaroncio's solution, removed apply plugin: 'com.google.gms.google-services' and I'm getting different error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mnm135.emil.showsmanager, PID: 5157
                  java.lang.NoSuchMethodError: No static method zzzq()Ljava/lang/String; in class Lcom/google/android/gms/common/util/zzu; or its super classes (declaration of 'com.google.android.gms.common.util.zzu' appears in /data/app/com.mnm135.emil.showsmanager-2/base.apk)
                      at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                      at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
                      at com.mnm135.emil.showsmanager.base.LoginActivity.onCreate(LoginActivity.java:34)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Line mentioned in comment is mFirebaseAuth = FirebaseAuth.getInstance();

Body:
I solved it removing the line about firebase-authentication in the build-gradle file:

compile 'com.google.firebase:firebase-auth:10.2.1'

I removed the imports about authentication also, I was just making some experiments with firebase auth so its not important in this case, but to others may not be ideal solution.


问:
How does {...object, property: value} work with spread syntax?
When reviewing the ES6 docs, I noted that it is recommended to use the spread syntax over the more verbose Object.assign() method. But, I am a bit confused as to how this is being accomplished.

Is object in this case being broken down to key: value pairs, after which the property on the right of the comma is either added or overwritten, and finally being reassembled?

答:
Is object in this case being broken down to key: value pairs, after which the property on the right of the comma is either added or overwritten, and finally being reassembled?

The key-value pairs of the original object object are actually being used in combination (merging) with the new object which has an extra property var2( they are getting combined to newObject).

You can think of it as object is becoming a subset of newObject in the place where the spread syntax in being used, while properties with same key are being overridden.

Check the below example:

const object = { txt: 'Test' };
const newObject = {...object, var2: 'aa' };

// logs Object {txt: "Test", var2: "aa"}
console.log(newObject);

const object2 = { txt: 'Test' };
const newObject2 = {...object, txt: 'Test2', var2: 'aa' };

// Object {txt: "Test2", var2: "aa"}
console.log(newObject2);

// merging all objects to a new object
var object3 = {first: 'Hello', second: 'World'};
var newObject3 = {...object, anotherVar: 'stack', ...object2, ...object3};

// Object {txt: "Test", anotherVar: "stack", first: "Hello", second: "World"}
console.log(newObject3);```


问:
How can I match common rows?
I have a table like this:

```<code>// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1  | 1       | Peter  |
| 2  | 1       | Martin |
| 3  | 2       | Jack   |
| 4  | 1       | Barman |
| 5  | 3       | Peter  |
| 6  | 1       | Jack   |
| 7  | 3       | David  |
| 8  | 2       | David  |
| 9  | 3       | Martin |
+----+---------+--------+
</code>```

Now I have two user_ids. For example 1 and 3. Now I want to match the rows which have common friends. So this is expected result:

```<code>| Peter  |
| Martin |
</code>```

Because Peter and Martin are common for both ids 1 and 3.

Is doing that possible by pure sql ?

答:
Another way</p>

```<code>SELECT friend
FROM t
GROUP BY friend
HAVING SUM(user_id =1)>0
AND SUM(user_id =3)>0
</code>```

Title: How can I match common rows?

Body:
I have a table like this:

// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1  | 1       | Peter  |
| 2  | 1       | Martin |
| 3  | 2       | Jack   |
| 4  | 1       | Barman |
| 5  | 3       | Peter  |
| 6  | 1       | Jack   |
| 7  | 3       | David  |
| 8  | 2       | David  |
| 9  | 3       | Martin |
+----+---------+--------+

Now I have two user_ids. For example 1 and 3. Now I want to match the rows which have common friends. So this is expected result:

| Peter  |
| Martin |

Because Peter and Martin are common for both ids 1 and 3.

Is doing that possible by pure sql ?

Body:
Another way

SELECT friend
FROM t
GROUP BY friend
HAVING SUM(user_id =1)>0
AND SUM(user_id =3)>0


问:
I cannot get my traffic light sequence to work in html
In my a452 computing class, I am trying to change an image with a button to represent I traffic light sequence.

I can display my first picture but the pictures will not change. in my sequence I have the pictures of the traffic lights but they cannot be displayed.

when I run it the first picture is loaded but then it will not load any other images

In my a452 computing I am trying to change an image with a button to represent I traffic light sequence. I can display my first picture but the pictures will not change, please help. Here is my code:

<!DOCTYPE html>

          <input type="button" id="change" value="change lights" onclick=TL()>

```

答:
You have syntax errors in your code, check the console!
Once you fix them, the script works: getElemenybyId is not correct.


问:
Updating a variable inside stream in Java 8
I'm just playing around with Java 8.
For now I'm trying to understand stream.
So far I haven't seen an example about looping through a map or list then populating a variable that is not part of the map or list.

Here is an example:

```<code>class RandomObject {
    private int i1;
    private String s1;
    //setter
    //getter
}

// Java 7
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();
Map<Integer, String> collect = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

for (Map.Entry<Integer, String> entry : mappy.entrySet()) {
    if (entry.getKey() == 2) {
        randomObj.seti1(entry.getKey());
        randomObj.sets1(entry.getValue());
        collect.put(entry.getKey(), entry.getValue());
    }
}

// Java 8
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
// Hmmm i don't know where to put randomObj
</code>```

答:
Since you are using a Map, it makes no sense to use such a boilerplate code except for "using streams", because a Map can't have the same key twice.

This is the best solution

```<code>String s = mappy.get(2);
if (s==null) {
    throw new IllegalStateException("No value with key = 2 were present");
}
new RandomObject(2, s);
</code>```

But if you realy whant to use stream, i see three solutions :

The ugly one (even if it is faster) :

```<code>Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .peek(entry -> {
        randomObj.seti1(entry.getKey());
        randomObj.sets1(entry.getValue());
    })
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
</code>```

peek() is used to peek each elements of the stream. And it returns the same stream. (But i would not recommend this way).

A better one (require twice as iteration):

```<code>Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

collect.entrySet().stream()
.forEach(entry -> {
    randomObj.seti1(entry.getKey());
    randomObj.sets1(entry.getValue());
});
</code>```

The better one :

```<code>Optional<RandomObject> randomObj = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .mapToObj(entry -> new RandomObject(entry.getKey(), entry.getValue()))
    .findFirst();

if (!randomObj.isPresent()) {
    throw new IllegalStateException("No value with key = 2 were present");
}
</code>```

Body:
I'm just playing around with Java 8.
For now I'm trying to understand stream.
So far I haven't seen an example about looping through a map or list then populating a variable that is not part of the map or list.

Here is an example:

class RandomObject {
    private int i1;
    private String s1;
    //setter
    //getter
}

// Java 7
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();
Map<Integer, String> collect = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

for (Map.Entry<Integer, String> entry : mappy.entrySet()) {
    if (entry.getKey() == 2) {
        randomObj.seti1(entry.getKey());
        randomObj.sets1(entry.getValue());
        collect.put(entry.getKey(), entry.getValue());
    }
}

// Java 8
RandomObject randomObj = new RandomObject();
Map<Integer, String> mappy = new HashMap<Integer, String>();

mappy.put(1, "good map");
mappy.put(2, "nice map");
mappy.put(3, "wow");
mappy.put(4, "mappy the best map");

Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
// Hmmm i don't know where to put randomObj

Body:
Since you are using a Map, it makes no sense to use such a boilerplate code except for "using streams", because a Map can't have the same key twice.

This is the best solution

String s = mappy.get(2);
if (s==null) {
    throw new IllegalStateException("No value with key = 2 were present");
}
new RandomObject(2, s);

But if you realy whant to use stream, i see three solutions :

The ugly one (even if it is faster) :

Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .peek(entry -> {
        randomObj.seti1(entry.getKey());
        randomObj.sets1(entry.getValue());
    })
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

peek() is used to peek each elements of the stream. And it returns the same stream. (But i would not recommend this way).

A better one (require twice as iteration):

Map<Integer, String> collect = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

collect.entrySet().stream()
.forEach(entry -> {
    randomObj.seti1(entry.getKey());
    randomObj.sets1(entry.getValue());
});

The better one :

Optional<RandomObject> randomObj = mappy.entrySet().stream()
    .filter(map -> map.getKey() == 2)
    .mapToObj(entry -> new RandomObject(entry.getKey(), entry.getValue()))
    .findFirst();

if (!randomObj.isPresent()) {
    throw new IllegalStateException("No value with key = 2 were present");
}


问:
How to pull strings out of JSON object
Here is the code

```<code>$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);
</code>```

output:

```<code>  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) )
</code>```

my question how can i pull individual values and insert them into the database
 fullname, role and username

答:
if you do

```<code>$data = JSON_decode($jsonString, true); // just add true
</code>```

then just use

```<code>$name = $data['myObject'][0]['name'];
</code>```

and save it

Title: How to pull strings out of JSON object

Body:
Here is the code

$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);

output:

  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) )

my question how can i pull individual values and insert them into the database
 fullname, role and username

Body:
if you do

$data = JSON_decode($jsonString, true); // just add true

then just use

$name = $data['myObject'][0]['name'];

and save it


问:
Symfony 3 Collection of Forms not persisting foreign key
I Embed a Collection of Forms. When I am adding a new record, foreign key is always null.

Does someone knows where is the problem? I tried to loop over results and persist each record but foreign key is still null.

Controller:

```<code> public function newAction(Request $request)
    {
        $bus = new BusVehicles();
        $busAmenities = new BusVehiclesAmenities();
       // dump ($busAmenities);
        //   $this->getDoctrine()->getManager()->persist($busAmenities);
        $bus->addBusVehiclesAmenities($busAmenities);
        $form = $this->createForm(BusVehiclesType::class, $bus);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $form->get('busVehiclesAmenities')->getData()->map(
                function ($amenities) use ($em, $bus) {

                    $bus->addBusVehiclesAmenities($amenities);
                    $em->persist($amenities);
                }
            );
         //   $em->persist($form->get('busVehiclesAmenities')->getData());
            $em->persist($bus);

            // Adding flash message to our user

            $this->addFlash('success', 'admin.bus.created');

            //  return $this->redirectToRoute('bus_add');

        }
        return [
            'form' => $form->createView(),
        ];
    }
</code>```

Bus Entity (Parent)

```<code>/** @ORM\OneToMany(
     *     targetEntity="BusVehiclesAmenities",
     *     mappedBy="busVehicles",
     *     cascade={"persist"}
     * )
     *
     */

    private $busVehiclesAmenities;

    public function __construct()
    {

        $this->busVehiclesAmenities = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

        if ($this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
             return;
         }
        $this->busVehiclesAmenities->add($busVehiclesAmenities);
        $busVehiclesAmenities->addBusVehicles($this);

        return $this;
    }

    /**
     * Remove busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     */
    public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        if (!$this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
            return;
        }
        $this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
        $busVehiclesAmenities->removeBusVehicles(this);

    }

    /**
     * Get busVehiclesAmenities
     *
     * @return ArrayCollection
     */
    public function getBusVehiclesAmenities()
    {
        return $this->busVehiclesAmenities;

    }

    /**
     * Set busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     * @return ArrayCollection
     */
   public function setBusVehiclesAmenities($busVehiclesAmenities)
    {
        $this->busVehiclesAmenities = $busVehiclesAmenities;

    }
</code>```

Bus Amenities Entity (Child):

```<code>/**
     *
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\BusVehicles", inversedBy="busVehiclesAmenities")
     * @ORM\JoinColumn(name="bus_vehicles_id", referencedColumnName="id")
     */
    private $busVehicles;

    /**
     *
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\Amenities", inversedBy="amenities")
     * @ORM\JoinColumn(name="amenities_id", referencedColumnName="id")

     *
     */
    private $amenities;

    /**
     * @var float
     * @ORM\Column(name="price", type="float", scale=2)
     */
    protected $price;

    public function __construct()
    {
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get busId
     *
     * @return integer
     */
    public function getBusVehicles()
    {
        return $this->busVehicles;
    }

    /**
     * Add bus
     *
     * @param \AppBundle\Entity\BusVehicles
     *
     * @return BusVehiclesAmenities
     */
    public function addBusVehicles(BusVehicles $busVehicles)
    {

        $this->busVehicles = $busVehicles;

        //$bus->setBusVehiclesAmenities($this);

        return $this;
    }

    /**
     * Remove bus
     *
     * @param \AppBundle\Entity\BusVehicles
     *
     * @return BusVehiclesAmenities
     */
    public function removeBusVehicles(BusVehicles $busVehicles = null)
    {

        $this->busVehicles = null;

        //$bus->setBusVehiclesAmenities($this);

        return $this;
    }
</code>```

答:
You mapped BusVehicle and Amenity as a bidirectional association.
The fk for Amenities is null because you don't set the BusVehicle for the Amenity.

You need to implement a method, say: setBusVehicle() in Amenities class:

```<code>public function setBusVehicle(BusVehicles $bus) {
    $this->busVehicles = $bus;
}
</code>```

When using bidirectional mapping, you must set the objects from both sides.

Body:
I Embed a Collection of Forms. When I am adding a new record, foreign key is always null.

Does someone knows where is the problem? I tried to loop over results and persist each record but foreign key is still null.

Controller:

 public function newAction(Request $request)
    {
        $bus = new BusVehicles();
        $busAmenities = new BusVehiclesAmenities();
       // dump ($busAmenities);
        //   $this->getDoctrine()->getManager()->persist($busAmenities);
        $bus->addBusVehiclesAmenities($busAmenities);
        $form = $this->createForm(BusVehiclesType::class, $bus);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $form->get('busVehiclesAmenities')->getData()->map(
                function ($amenities) use ($em, $bus) {

                    $bus->addBusVehiclesAmenities($amenities);
                    $em->persist($amenities);
                }
            );
         //   $em->persist($form->get('busVehiclesAmenities')->getData());
            $em->persist($bus);

            // Adding flash message to our user

            $this->addFlash('success', 'admin.bus.created');

            //  return $this->redirectToRoute('bus_add');

        }
        return [
            'form' => $form->createView(),
        ];
    }

Bus Entity (Parent)

/** @ORM\OneToMany(
     *     targetEntity="BusVehiclesAmenities",
     *     mappedBy="busVehicles",
     *     cascade={"persist"}
     * )
     *
     */

    private $busVehiclesAmenities;

    public function __construct()
    {

        $this->busVehiclesAmenities = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
     * @return BusVehicles
     */
    public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {

        if ($this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
             return;
         }
        $this->busVehiclesAmenities->add($busVehiclesAmenities);
        $busVehiclesAmenities->addBusVehicles($this);

        return $this;
    }

    /**
     * Remove busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     */
    public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
    {
        if (!$this->busVehiclesAmenities->contains($busVehiclesAmenities)) {
            return;
        }
        $this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
        $busVehiclesAmenities->removeBusVehicles(this);

    }

    /**
     * Get busVehiclesAmenities
     *
     * @return ArrayCollection
     */
    public function getBusVehiclesAmenities()
    {
        return $this->busVehiclesAmenities;

    }

    /**
     * Set busVehiclesAmenities
     *
     * @param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
     * @return ArrayCollection
     */
   public function setBusVehiclesAmenities($busVehiclesAmenities)
    {
        $this->busVehiclesAmenities = $busVehiclesAmenities;

    }

Bus Amenities Entity (Child):

/**
     *
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\BusVehicles", inversedBy="busVehiclesAmenities")
     * @ORM\JoinColumn(name="bus_vehicles_id", referencedColumnName="id")
     */
    private $busVehicles;

    /**
     *
     * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\Amenities", inversedBy="amenities")
     * @ORM\JoinColumn(name="amenities_id", referencedColumnName="id")

     *
     */
    private $amenities;

    /**
     * @var float
     * @ORM\Column(name="price", type="float", scale=2)
     */
    protected $price;

    public function __construct()
    {
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get busId
     *
     * @return integer
     */
    public function getBusVehicles()
    {
        return $this->busVehicles;
    }

    /**
     * Add bus
     *
     * @param \AppBundle\Entity\BusVehicles
     *
     * @return BusVehiclesAmenities
     */
    public function addBusVehicles(BusVehicles $busVehicles)
    {

        $this->busVehicles = $busVehicles;

        //$bus->setBusVehiclesAmenities($this);

        return $this;
    }

    /**
     * Remove bus
     *
     * @param \AppBundle\Entity\BusVehicles
     *
     * @return BusVehiclesAmenities
     */
    public function removeBusVehicles(BusVehicles $busVehicles = null)
    {

        $this->busVehicles = null;

        //$bus->setBusVehiclesAmenities($this);

        return $this;
    }

Body:
You mapped BusVehicle and Amenity as a bidirectional association.
The fk for Amenities is null because you don't set the BusVehicle for the Amenity.

You need to implement a method, say: setBusVehicle() in Amenities class:

public function setBusVehicle(BusVehicles $bus) {
    $this->busVehicles = $bus;
}

When using bidirectional mapping, you must set the objects from both sides.


问:
Putting JSON data from Google sheets into an array
My sheet: https://docs.google.com/spreadsheets/d/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/edit?usp=sharing

I'm using Google sheets JSON data to display on my website but I want to put some of the data into arrays so it doesn't repeat itself on the website.

For example, this is how it displays, but I would like to be able to just have the one heading for each group (zouk, zen ect) and then all the members to be under the one header.
https://www.kentunion.co.uk/test1/

So I am trying to figure out some javascript that adds all the positions of one group into an array. Go from this:

```<code>"Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "President",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }
</code>```

to this:

```<code>"Zouk Society" [{
      "position" : "President",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }
]
</code>```

I have tried the following JS but I am just getting an error from it:

```<code> // ID of the Google Spreadsheet
 var spreadsheetID = "1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY";

 // Make sure it is public or set to Anyone with link can view
 var url = "https://spreadsheets.google.com/feeds/list/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/od6/public/values?alt=json";
     $(document).ready(function () {
         $.getJSON(url, function(data) {

             var entry = data.feed.entry;

             $(entry).each(function(){
                  // Column names are name, age, etc.
                  $('.results').prepend('<h2>'+this.gsx$name.$t+'</h2><p>'+this.gsx$position.$t+'</p><p>'+this.gsx$member.$t+'</p>');
             });
         });

    var grouped = {};

        entry.forEach(function (a) {
          grouped[a.name] = grouped[a.name] || [];
                grouped[a.name].push({ position: a.position, member: a.member });
        });
        document.write('```' + JSON.stringify(grouped, 0, 4) + '```');

  });
</code>```

This is the error that I get:

Uncaught ReferenceError: entry is not defined at
  HTMLDocument. (scripts.js:19)

答:
You can't access entry outside of the callback scope.

Do your grouping inside the callback, like this:

```<code>// ID of the Google Spreadsheet
var spreadsheetID = "1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY";

// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/od6/public/values?alt=json";

$(document).ready(function () {
    $.getJSON(url, function(data) {
        var entry = data.feed.entry;

        $(entry).each(function(){
            // Column names are name, age, etc.
            $('.results').prepend('<h2>'+this.gsx$name.$t+'</h2><p>'+this.gsx$position.$t+'</p><p>'+this.gsx$member.$t+'</p>');
        });

        var grouped = {};

        entry.forEach(function (a) {
            grouped[a.gsx$name.$t] = grouped[a.gsx$name.$t] || [];
            grouped[a.gsx$name.$t].push({ position: a.gsx$position.$t, member: a.gsx$member.$t });
        });

        document.write('```' + JSON.stringify(grouped, 0, 4) + '```');
    });
});
</code>```

Body:
My sheet: https://docs.google.com/spreadsheets/d/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/edit?usp=sharing

I'm using Google sheets JSON data to display on my website but I want to put some of the data into arrays so it doesn't repeat itself on the website.

For example, this is how it displays, but I would like to be able to just have the one heading for each group (zouk, zen ect) and then all the members to be under the one header.
https://www.kentunion.co.uk/test1/

So I am trying to figure out some javascript that adds all the positions of one group into an array. Go from this:

"Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "President",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    "Zouk Society" : {
      "name" : "Zouk Society",
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }

to this:

"Zouk Society" [{
      "position" : "President",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Secretary",
      "member" : "Currently Vacant"
    },
    {
      "position" : "Treasurer",
      "member" : "Currently Vacant"
    }
]

I have tried the following JS but I am just getting an error from it:

 // ID of the Google Spreadsheet
 var spreadsheetID = "1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY";

 // Make sure it is public or set to Anyone with link can view
 var url = "https://spreadsheets.google.com/feeds/list/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/od6/public/values?alt=json";
     $(document).ready(function () {
         $.getJSON(url, function(data) {

             var entry = data.feed.entry;

             $(entry).each(function(){
                  // Column names are name, age, etc.
                  $('.results').prepend('
'+this.gsx$name.$t+'

'+this.gsx$position.$t+'

'+this.gsx$member.$t+'
');
             });
         });

    var grouped = {};

        entry.forEach(function (a) {
          grouped[a.name] = grouped[a.name] || [];
                grouped[a.name].push({ position: a.position, member: a.member });
        });
        document.write('
' + JSON.stringify(grouped, 0, 4) + '
');

  });

This is the error that I get:

Uncaught ReferenceError: entry is not defined at
  HTMLDocument. (scripts.js:19)

Body:
You can't access entry outside of the callback scope.

Do your grouping inside the callback, like this:

// ID of the Google Spreadsheet
var spreadsheetID = "1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY";

// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/1pruXYXrbITR7CoQXZG1I1kyS4DahYBXmGMDEK2T6MpY/od6/public/values?alt=json";

$(document).ready(function () {
    $.getJSON(url, function(data) {
        var entry = data.feed.entry;

        $(entry).each(function(){
            // Column names are name, age, etc.
            $('.results').prepend('<h2>'+this.gsx$name.$t+'</h2><p>'+this.gsx$position.$t+'</p><p>'+this.gsx$member.$t+'</p>');
        });

        var grouped = {};

        entry.forEach(function (a) {
            grouped[a.gsx$name.$t] = grouped[a.gsx$name.$t] || [];
            grouped[a.gsx$name.$t].push({ position: a.gsx$position.$t, member: a.gsx$member.$t });
        });

        document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
    });
});


问:
How can I write XML which is divided into three horizontal columns and four vertical rows?
How can I write xml which is divided into three horizontal columns and four vertical rows?

It should be divide into three columns while three columns further divided into four rows as per screenshot shown below.

How can I get views like attached image through XML?

For horizontal:

```<code><LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_marginTop="2dp"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:id="@+id/l1"
        android:background="#ffff">

        <ImageView
            android:id="@+id/glassconsumed1"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed22"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed32"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />
        </LinearLayout>
</code>```

for Vertical

```<code><LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_marginTop="2dp"
            android:layout_height="wrap_content"
            android:weightSum="3"
            android:layout_below="@+id/glassconsumed1"
            android:id="@+id/l2"
            android:background="#ffff">
        <TextView
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_weight="1"
            android:layout_below="@+id/glassconsumed1"
            android:hint="   14/16"
            android:textSize="16dp"
            android:layout_width="wrap_content"
            android:background="@color/white"
            android:textColorHint="#8E8E8E"
            android:layout_marginTop="2dp"
            android:paddingLeft="@dimen/desc_padding"
            android:paddingRight="@dimen/desc_padding"
            android:textColor="#000000"
            android:id="@+id/editTextvalue1" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue1"
                android:layout_weight="1"
                android:hint="  Glasses"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue2" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue2"
                android:layout_weight="1"
                android:hint="Consumed"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue3" />
            </LinearLayout>
</code>```

答:
try to set this type hope this can help you..</p>

```<code> <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal"
   android:weightSum="1">

  <LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:orientation="vertical">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="14/16" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Glasses" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Consumed" />

</LinearLayout>

<View
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:orientation="vertical">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="14/16" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Glasses" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Consumed" />

</LinearLayout>

<View
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:orientation="vertical">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="14/16" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Glasses" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Consumed" />

  </LinearLayout>

</LinearLayout>
</code>```

Body:
How can I write xml which is divided into three horizontal columns and four vertical rows?

It should be divide into three columns while three columns further divided into four rows as per screenshot shown below.

How can I get views like attached image through XML?

For horizontal:

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_marginTop="2dp"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:id="@+id/l1"
        android:background="#ffff">

        <ImageView
            android:id="@+id/glassconsumed1"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed22"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed32"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />
        </LinearLayout>

for Vertical

<LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_marginTop="2dp"
            android:layout_height="wrap_content"
            android:weightSum="3"
            android:layout_below="@+id/glassconsumed1"
            android:id="@+id/l2"
            android:background="#ffff">
        <TextView
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_weight="1"
            android:layout_below="@+id/glassconsumed1"
            android:hint="   14/16"
            android:textSize="16dp"
            android:layout_width="wrap_content"
            android:background="@color/white"
            android:textColorHint="#8E8E8E"
            android:layout_marginTop="2dp"
            android:paddingLeft="@dimen/desc_padding"
            android:paddingRight="@dimen/desc_padding"
            android:textColor="#000000"
            android:id="@+id/editTextvalue1" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue1"
                android:layout_weight="1"
                android:hint="  Glasses"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue2" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue2"
                android:layout_weight="1"
                android:hint="Consumed"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue3" />
            </LinearLayout>

Body:
try to set this type hope this can help you..

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal"
   android:weightSum="1">

  <LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:orientation="vertical">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="14/16" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Glasses" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Consumed" />

</LinearLayout>

<View
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:orientation="vertical">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="14/16" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Glasses" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Consumed" />

</LinearLayout>

<View
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".33"
    android:orientation="vertical">

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="14/16" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Glasses" />

    <TextView
        android:textColor="#cccccc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Consumed" />

  </LinearLayout>

</LinearLayout>


问:
Angular 2 add multiple classes via [class.className] binding
While adding a single class works great in this way -

[class.loading-state]="loading"

But how do I add multiple classes
Ex if loading is true add class - "loading-state" & "my-class"

How do I get it done via the [class] binding

答:
You can do this by simply using ngClass :

Here first,second and third are the name of the classes.

And instead of true/false , you can directly put your conditions over there

```<code> <div [ngClass]="{'first': true, 'second': true, 'third': false}">...</div>
</code>```

In your case

```<code> <div [ngClass]="{'loading-state': loading, 'my-class': loading }">...</div>
</code>```

Or Shorter Veriosn (as @matko.kvesic commented)

```<code><div [ngClass]="{'loading-state my-class': loading}">...</div>
</code>```

Body:
You can do this by simply using ngClass :

Here first,second and third are the name of the classes.

And instead of true/false , you can directly put your conditions over there

 <div [ngClass]="{'first': true, 'second': true, 'third': false}">...</div>

In your case

 <div [ngClass]="{'loading-state': loading, 'my-class': loading }">...</div>

Or Shorter Veriosn (as @matko.kvesic commented)

<div [ngClass]="{'loading-state my-class': loading}">...</div>


问:
How to pass header string to service in Camel
We are building a message router based on Apache Camel and decided to use a generic flow for multiple formats. We input our message trough a generic rest endpoint and conditionally map the body of this call onto one of multiple specific message formats. We generated our specific dataformats from different XSD's.

The mapping happens in a processor, which dependending on the content of the message uses a different mapper. This processor puts the specific Java model in the body of the exchange.

In the next step we would like to marshal and validate the body to XML. This is a "generic" step, as all messages must be marshalled to XML. After this they get send to a dynamic endpoint, again based on the message content.

To marshal the XML we use the following route:

```<code>from("direct:marshal-xml")
 .marshal(jaxbDataFormat)
 .to("direct:validate-and-send");
</code>```

Depending on a header property called "messageType", we would like to use a different jaxbDataFormat object to marshal to XML. We could do this with a choice in the route itself, but we would like to use a dedicated service which takes a string input, the messageType, and returns the correct jaxbDataFormat.

Now the question is how to pass the header property "messageType" as an argument to the service. We would like to use something like:

```<code>from("direct:marshal-xml")
 .marshal(jaxbDataFormatService.getDataFormat(getHeader("messageType")))
 .to("direct:validate-and-send");
</code>```

But I can't seem to get the messageType as a string from the header. There seems to be a difference between the routebuilder, which "models" the route, and the runtime route, which is generated from this model.

I tried using simple expresions, but I can't seem to evaluate them without an exchange:

```<code>simple("${header.messageType}").evaluate(exchange, String.class);
</code>```

How to solve this problem? Do I have to use the choice component in the routebuilder, or is it possible to use this dedicated service still?

答:
You can always implement your own "composite data format" for example by implementing org.apache.camel.spi.DataFormat that will have knowledge of all the data formats you want to use and use the one that you want.

Something like this, just to give you an idea:

```<code>public class MyCompositeFormat implements DataFormat, CamelContextAware {

    public MyCompositeFormat(DataFormat... formats) {
        // store them to local variable
    }

    public CamelContext getCamelContext() {
        return camelContext;
    }

    public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
    }

    public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception {
      if (exchange.getIn().getHeader("SomeHeader",String.class).equals("whatever") {
        return someFormatYouStored.marshal(exchange,graph,stream);
      } else {
        return anotherFormat.marshal(exchange,graph,stream);
      }

    }

    public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
      // similar approach to marshal
    }

}
</code>```

And in your route:

```<code>MyCompositeFormat myCompositeFormat = new MyCompositeFormat(otherFormats);
from("direct:marshal-xml")
 .marshal(myCustomFormat)
 .to("direct:validate-and-send");
</code>```

Body:
We are building a message router based on Apache Camel and decided to use a generic flow for multiple formats. We input our message trough a generic rest endpoint and conditionally map the body of this call onto one of multiple specific message formats. We generated our specific dataformats from different XSD's.

The mapping happens in a processor, which dependending on the content of the message uses a different mapper. This processor puts the specific Java model in the body of the exchange.

In the next step we would like to marshal and validate the body to XML. This is a "generic" step, as all messages must be marshalled to XML. After this they get send to a dynamic endpoint, again based on the message content.

To marshal the XML we use the following route:

from("direct:marshal-xml")
 .marshal(jaxbDataFormat)
 .to("direct:validate-and-send");

Depending on a header property called "messageType", we would like to use a different jaxbDataFormat object to marshal to XML. We could do this with a choice in the route itself, but we would like to use a dedicated service which takes a string input, the messageType, and returns the correct jaxbDataFormat.

Now the question is how to pass the header property "messageType" as an argument to the service. We would like to use something like:

from("direct:marshal-xml")
 .marshal(jaxbDataFormatService.getDataFormat(getHeader("messageType")))
 .to("direct:validate-and-send");

But I can't seem to get the messageType as a string from the header. There seems to be a difference between the routebuilder, which "models" the route, and the runtime route, which is generated from this model.

I tried using simple expresions, but I can't seem to evaluate them without an exchange:

simple("${header.messageType}").evaluate(exchange, String.class);

How to solve this problem? Do I have to use the choice component in the routebuilder, or is it possible to use this dedicated service still?

Body:
You can always implement your own "composite data format" for example by implementing org.apache.camel.spi.DataFormat that will have knowledge of all the data formats you want to use and use the one that you want.

Something like this, just to give you an idea:

public class MyCompositeFormat implements DataFormat, CamelContextAware {

    public MyCompositeFormat(DataFormat... formats) {
        // store them to local variable
    }

    public CamelContext getCamelContext() {
        return camelContext;
    }

    public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
    }

    public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception {
      if (exchange.getIn().getHeader("SomeHeader",String.class).equals("whatever") {
        return someFormatYouStored.marshal(exchange,graph,stream);
      } else {
        return anotherFormat.marshal(exchange,graph,stream);
      }

    }

    public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
      // similar approach to marshal
    }

}

And in your route:

MyCompositeFormat myCompositeFormat = new MyCompositeFormat(otherFormats);
from("direct:marshal-xml")
 .marshal(myCustomFormat)
 .to("direct:validate-and-send");


问:
Alternative build manager to Hudson
I work at a software company where our primary development language is Java. Naturally, we use Hudson for continuous builds, which it works brilliantly for. However, Hudson is not so good at some of the other things we ask it to do. We also use Hudson jobs to deploy binaries, refresh databases, run load testing, run regressions, etc. We really run into trouble when there are build dependencies (i.e. load testings requires DB refresh).

Here's the one thing that Hudson doesn't do that we really need:

Build dependency: It supports build dependencies for Ant builds, but not for Hudson jobs. We're using the URL invocation feature to cause a Hudson job to invoke another Hudson job. The problem is that Hudson always returns a 200 and does not block until the job is done. This means that the calling job doesn't know a) if the build failed and b) if it didn't fail, how long it took.

It would be nice to not have to use shell scripting to specify the behavior of a build, but that's not totally necessary.

Any direction would be nice. Perhaps we're not using Hudson the right way (i.e. should all builds be Ant builds?) or perhaps we need another product for our one-click deployment, load testing, migration, DB refresh, etc.

Edit:

To clarify, we have parameters in our builds that can cause different dependencies depending on the parameters.  I.e. sometimes we want load testing with a DB refresh, sometimes without a DB refresh.  Unfortunately, creating a Hudson job for each combination of parameters (as the Join plugin requires) won't work because sometimes the different combinations could lead to dozens of jobs.

答:
I don't think I understand your "build dependency" requirements. Any Hudson job can be configured to trigger another (downstream) job, or be triggered by another (upstream) job. </p>

<p>The Downstream-Ext plugin and Join plugin allow for more complex definition of build dependencies. </p>

Title: Alternative build manager to Hudson

Body:
I don't think I understand your "build dependency" requirements. Any Hudson job can be configured to trigger another (downstream) job, or be triggered by another (upstream) job.

The Downstream-Ext plugin and Join plugin allow for more complex definition of build dependencies.


问:
checking if a string is in alphabetical order in python
I've put together the following code to check if a string/word is alphabetically ordered:

```<code>def isInAlphabeticalOrder(word):
    word1=sorted(word)
    word2=[]
    for i in word:
        word2.append(i)
    if word2 == word1:
        return True
    else:
        return False
</code>```

but I feel like there must be a more efficient way (fewer lines of code) to check other than turning the strings into lists. Isn't there a operand to sort strings alphabetically without turning each char into a list? Can anyone suggest a more efficient way?

答:
This is the easiest:</p>

```<code>def alphabetical(word):
    return list(word) == sorted(word)
</code>```

Body:
I've put together the following code to check if a string/word is alphabetically ordered:

def isInAlphabeticalOrder(word):
    word1=sorted(word)
    word2=[]
    for i in word:
        word2.append(i)
    if word2 == word1:
        return True
    else:
        return False

but I feel like there must be a more efficient way (fewer lines of code) to check other than turning the strings into lists. Isn't there a operand to sort strings alphabetically without turning each char into a list? Can anyone suggest a more efficient way?

Body:
This is the easiest:

def alphabetical(word):
    return list(word) == sorted(word)


问:
Material fastscroll thumb with GridView and ArrayAdapter
I have a GridView layout that makes use of an ArrayAdapter to populate its contents. I want to make use of fast-scrolling and as such have added the following attributed to the layout XML:

```<code>android:fastScrollAlwaysVisible="true"
android:fastScrollStyle="@android:style/Widget.Material.FastScroll"
</code>```

I am now able to make use of fast scrolling to navigate but would now like to add a material thumb preview as such:

From my understanding, I would have to implement the SectionIndexer interface from my ArrayAdapter as so:

```<code>class exampleArrayAdapter extends ArrayAdapter<...> implements SectionIndexer
</code>```

At this point, I have reached a bump and can't figure out how to get the thumb preview and fear I may be doing something wrong. Pointers as to how I can get this working or what I should look up would be appreciated.

答:
I have finally had time to look back at this, and the solution turns out to be very trivial! This is what I did:

```<code>@Override
public Object[] getSections() {
    ArrayList<String> labels = new ArrayList<>();
    for (LaunchableActivity activity: mActivityInfos) {
        labels.add(activity.getActivityLabel());
    }

    return labels.toArray();
}

@Override
public int getPositionForSection(int i) {
    return i;
}

@Override
public int getSectionForPosition(int i) {
    // We do not need this
    return 0;
}
</code>```

I had a list of LaunchableActivity and based of that created a sections array to be returned. For my needs, all I required was to implement getPositionForSection and not getSectionForPosition. Your use case may vary.

The source code where I implemented this is available here, specifically on commits:

a2c9ddd1c647919afbf24262ac1a7772a08e468c

08802e17f4c75835c28232353fed68964f5d7746

0d73a788c6b92d7b9c05a2871778da42af02afd8

f13a59f02690481801bd07ffc593648b8e71d036

Body:
I have a GridView layout that makes use of an ArrayAdapter to populate its contents. I want to make use of fast-scrolling and as such have added the following attributed to the layout XML:

android:fastScrollAlwaysVisible="true"
android:fastScrollStyle="@android:style/Widget.Material.FastScroll"

I am now able to make use of fast scrolling to navigate but would now like to add a material thumb preview as such:

From my understanding, I would have to implement the SectionIndexer interface from my ArrayAdapter as so:

class exampleArrayAdapter extends ArrayAdapter<...> implements SectionIndexer

At this point, I have reached a bump and can't figure out how to get the thumb preview and fear I may be doing something wrong. Pointers as to how I can get this working or what I should look up would be appreciated.

Body:
I have finally had time to look back at this, and the solution turns out to be very trivial! This is what I did:

@Override
public Object[] getSections() {
    ArrayList<String> labels = new ArrayList<>();
    for (LaunchableActivity activity: mActivityInfos) {
        labels.add(activity.getActivityLabel());
    }

    return labels.toArray();
}

@Override
public int getPositionForSection(int i) {
    return i;
}

@Override
public int getSectionForPosition(int i) {
    // We do not need this
    return 0;
}

I had a list of LaunchableActivity and based of that created a sections array to be returned. For my needs, all I required was to implement getPositionForSection and not getSectionForPosition. Your use case may vary.

The source code where I implemented this is available here, specifically on commits:

a2c9ddd1c647919afbf24262ac1a7772a08e468c

08802e17f4c75835c28232353fed68964f5d7746

0d73a788c6b92d7b9c05a2871778da42af02afd8

f13a59f02690481801bd07ffc593648b8e71d036


问:
How to redirect to the successs page upon successfull http post request in angular Javascript
I am learning how to use angular javascript alongside my favorite, PHP framework (CodeIgniter). I have a login section that authenticates to a service and gets the response using angular js. The code works fine. See snippet below

```<code>var login = angular.module('authenticationApp' , ['ngMaterial' , 'ngRoute']) ;

    login.controller('authenticationController', function ($scope, $http) {

        $scope.authenticate = function () {

            if ($scope.username == undefined || $scope.password == undefined) {
                $scope.login_error_message = "All form fields are required" ;

            } else {
                var url = get_base_url() + 'student/authentication/login?username=' + $scope.username + '&password=' + $scope.password ;

                $http.post(url).then(
                    function (response) {
                        console.log(response) ;
                        /*Here I handle success*/
                    }, function (response) {
                        $scope.login_error_message = "Service Error!. Response: " + response ;
                    }
                ) ;
            }
        } ;
</code>```

My problem is how can I send that response to the success.php page and also redirect to the success page. I can redirect using

```<code> window.location.href = get_base_url() + 'administrator/authentication/dashboard' ;
</code>```

My challenge now is actually sending the response to this new location.

Thanks in advance and I am ready to provide more details if need be

答: After battling for long, I just decided to use plain js. Crappy but works.</p>

Body:
I am learning how to use angular javascript alongside my favorite, PHP framework (CodeIgniter). I have a login section that authenticates to a service and gets the response using angular js. The code works fine. See snippet below

var login = angular.module('authenticationApp' , ['ngMaterial' , 'ngRoute']) ;

    login.controller('authenticationController', function ($scope, $http) {

        $scope.authenticate = function () {

            if ($scope.username == undefined || $scope.password == undefined) {
                $scope.login_error_message = "All form fields are required" ;

            } else {
                var url = get_base_url() + 'student/authentication/login?username=' + $scope.username + '&password=' + $scope.password ;

                $http.post(url).then(
                    function (response) {
                        console.log(response) ;
                        /*Here I handle success*/
                    }, function (response) {
                        $scope.login_error_message = "Service Error!. Response: " + response ;
                    }
                ) ;
            }
        } ;

My problem is how can I send that response to the success.php page and also redirect to the success page. I can redirect using

 window.location.href = get_base_url() + 'administrator/authentication/dashboard' ;

My challenge now is actually sending the response to this new location.

Thanks in advance and I am ready to provide more details if need be