问:
Code behaviour depends on type order in switch operator, how to get rid of this?
Recently I started to learn the Go language.

I am trying to understand interface principles in Go and was completely puzzled by one thing.

The duck principle says: if something quacks like a duck and walks like a duck, then it's a duck.

But I wondered how Go will behave if we have three interfaces like this:

```<code>// Interface A
type InterfaceA interface {
    ActionA() string
}

// Interface B
type InterfaceB interface {
    ActionB() string
}
</code>```

And interface C, which does something different but has functions which are similar to interfaces A and B functions:

```<code>// Interface C with methods A and B interfaces
type InterfaceC interface {
    ActionA() string
    ActionB() string
}
</code>```

Then we have three structures which implement the interfaces above:

```<code>type StructA struct{}

// If it does ActionA then it's interface A
func (a StructA) ActionA() string {
    return "Interface A implementation"
}

type StructB struct{}

// If it does ActionB then it's interface B
func (b StructB) ActionB() string {
    return "Interface B implementation"
}

type StructC struct{}

// If it does ActionA and ActionB, it's an Interface C
func (c StructC) ActionA() string {
    return "Interface C implementation"
}

func (c StructC) ActionB() string {
    return "Interface C implementation"
}
</code>```

And a function that identifies which type it gets:

```<code>func getType(data interface{}) string {
    switch data.(type) {
    default:
        return "Unknown"
    case InterfaceA:
        return "Interface A"
    case InterfaceB:
        return "Interface B"
    case InterfaceC:
        return "Interface C"
    }
}
</code>```

Code inside main function:

```<code>func main() {
    a := StructA{}
    fmt.Println(a.ActionA())
    fmt.Println(getType(a)) // should return InterfaceA
    fmt.Println("")
    b := StructB{}
    fmt.Println(b.ActionB())
    fmt.Println(getType(b)) // should return InterfaceB
    fmt.Println("")
    c := StructC{}
    fmt.Println(c.ActionA())
    fmt.Println(c.ActionB())
    fmt.Println(getType(c)) // should return InterfaceC
}
</code>```

Output:

```<code>Interface A implementation
Interface A

Interface B implementation
Interface B

Interface C implementation
Interface C implementation
Interface A
</code>```

After some experiments I found out if we change the case order inside switch then the function identifies the type correctly:

```<code>func getType(data interface{}) string {
    switch data.(type) {
    default:
        return "Unknown"
    case InterfaceC:
        return "Interface C"
    case InterfaceB:
        return "Interface B"
    case InterfaceA:
        return "Interface A"
    }
}
</code>```

Output:

```<code>Interface A implementation
Interface A

Interface B implementation
Interface B

Interface C implementation
Interface C implementation
Interface C
</code>```

See also full code on play.golang.org

My question: Is it a bug or a feature? And if it's a feature, how should I change getType so that the function doesn't depend on case order?

答:
This is the intended working, as defined by the language spec.

There are 2 types of switch statement, Expression switches and Type switches, and this behavior is documented at the Expression switches:

In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a "default" case, its statements are executed. There can be at most one default case and it may appear anywhere in the "switch" statement.

[...]

A type switch compares types rather than values. It is otherwise similar to an expression switch.

In Go a type implicitly implements an interface if its method set is a superset of the interface. There is no declaration of the intent. So in Go it doesn't matter which interface defines the methods, only thing that matters is the method signatures: if a type has all the methods an interface "prescribes", then that type implicitly implements the said interface.

The problem is that you want to use the Type switch to something it was not designed for. You want to find the "widest" type (with the most methods) that is still implemented by the value. It will only do this if you enumerate the cases (the different types) in this intended order.

That being said, in your case there's no such thing that a value is only InterfaceC implementation. Your code doesn't lie: all values that implement InterfaceC will also implement InterfaceA and InterfaceB too, because the method sets of both InterfaceA and InterfaceB are subsets of the method set of InterfaceC.

If you want to be able to "differentiate" InterfaceC implementations, you have to "alter" the method sets so that the above mentioned relation will not hold (method set of InterfaceC will not be a superset of the method set of InterfaceA and InterfaceB). If you want StructC to not be an InterfaceA implementation, you must change the method signature of ActionA() (either in InterfaceA or in InterfaceC), and similarly ActionB() to not be an InterfaceB implementation.

You could also add a method to InterfaceA (and to InterfaceB) which is missing from InterfaceC:

```<code>type InterfaceA interface {
    ActionA() string
    implementsA()
}

type InteraceB interface {
    ActionB() string
    implementsB()
}
</code>```

And you have to add them to StructA and StructB of course:

```<code>func (a StructA) implementsA() {}

func (b StructB) implementsB() {}
</code>```

This way you get the desired output. Try it on the Go Playground.

If you can't or don't want to do this, your only option is to enumerate the cases in the right order. Or don't use type switch for this.

Body:
Recently I started to learn the Go language.

I am trying to understand interface principles in Go and was completely puzzled by one thing.

The duck principle says: if something quacks like a duck and walks like a duck, then it's a duck.

But I wondered how Go will behave if we have three interfaces like this:

// Interface A
type InterfaceA interface {
    ActionA() string
}

// Interface B
type InterfaceB interface {
    ActionB() string
}

And interface C, which does something different but has functions which are similar to interfaces A and B functions:

// Interface C with methods A and B interfaces
type InterfaceC interface {
    ActionA() string
    ActionB() string
}

Then we have three structures which implement the interfaces above:

type StructA struct{}

// If it does ActionA then it's interface A
func (a StructA) ActionA() string {
    return "Interface A implementation"
}

type StructB struct{}

// If it does ActionB then it's interface B
func (b StructB) ActionB() string {
    return "Interface B implementation"
}

type StructC struct{}

// If it does ActionA and ActionB, it's an Interface C
func (c StructC) ActionA() string {
    return "Interface C implementation"
}

func (c StructC) ActionB() string {
    return "Interface C implementation"
}

And a function that identifies which type it gets:

func getType(data interface{}) string {
    switch data.(type) {
    default:
        return "Unknown"
    case InterfaceA:
        return "Interface A"
    case InterfaceB:
        return "Interface B"
    case InterfaceC:
        return "Interface C"
    }
}

Code inside main function:

func main() {
    a := StructA{}
    fmt.Println(a.ActionA())
    fmt.Println(getType(a)) // should return InterfaceA
    fmt.Println("")
    b := StructB{}
    fmt.Println(b.ActionB())
    fmt.Println(getType(b)) // should return InterfaceB
    fmt.Println("")
    c := StructC{}
    fmt.Println(c.ActionA())
    fmt.Println(c.ActionB())
    fmt.Println(getType(c)) // should return InterfaceC
}

Output:

Interface A implementation
Interface A

Interface B implementation
Interface B

Interface C implementation
Interface C implementation
Interface A

After some experiments I found out if we change the case order inside switch then the function identifies the type correctly:

func getType(data interface{}) string {
    switch data.(type) {
    default:
        return "Unknown"
    case InterfaceC:
        return "Interface C"
    case InterfaceB:
        return "Interface B"
    case InterfaceA:
        return "Interface A"
    }
}

Output:

Interface A implementation
Interface A

Interface B implementation
Interface B

Interface C implementation
Interface C implementation
Interface C

See also full code on play.golang.org

My question: Is it a bug or a feature? And if it's a feature, how should I change getType so that the function doesn't depend on case order?

Body:
This is the intended working, as defined by the language spec.

There are 2 types of switch statement, Expression switches and Type switches, and this behavior is documented at the Expression switches:

In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a "default" case, its statements are executed. There can be at most one default case and it may appear anywhere in the "switch" statement.

[...]

A type switch compares types rather than values. It is otherwise similar to an expression switch.

In Go a type implicitly implements an interface if its method set is a superset of the interface. There is no declaration of the intent. So in Go it doesn't matter which interface defines the methods, only thing that matters is the method signatures: if a type has all the methods an interface "prescribes", then that type implicitly implements the said interface.

The problem is that you want to use the Type switch to something it was not designed for. You want to find the "widest" type (with the most methods) that is still implemented by the value. It will only do this if you enumerate the cases (the different types) in this intended order.

That being said, in your case there's no such thing that a value is only InterfaceC implementation. Your code doesn't lie: all values that implement InterfaceC will also implement InterfaceA and InterfaceB too, because the method sets of both InterfaceA and InterfaceB are subsets of the method set of InterfaceC.

If you want to be able to "differentiate" InterfaceC implementations, you have to "alter" the method sets so that the above mentioned relation will not hold (method set of InterfaceC will not be a superset of the method set of InterfaceA and InterfaceB). If you want StructC to not be an InterfaceA implementation, you must change the method signature of ActionA() (either in InterfaceA or in InterfaceC), and similarly ActionB() to not be an InterfaceB implementation.

You could also add a method to InterfaceA (and to InterfaceB) which is missing from InterfaceC:

type InterfaceA interface {
    ActionA() string
    implementsA()
}

type InteraceB interface {
    ActionB() string
    implementsB()
}

And you have to add them to StructA and StructB of course:

func (a StructA) implementsA() {}

func (b StructB) implementsB() {}

This way you get the desired output. Try it on the Go Playground.

If you can't or don't want to do this, your only option is to enumerate the cases in the right order. Or don't use type switch for this.


来源: stackexchange

问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答:
I was submitting with an old Xcode version, I thought that was the problem, so went to the latest and it gives me the same message, that I am submitting for 8.2 which is higher than 10.3.

Now, here is where it gets really crazy. I said, OK, maybe there is an issue with 8.2, so I switched my minimum target to 8.3, cleaned, archived, submitted. I STILL GET THE MESSAGE ABOUT 8.2!!!

I exported the package I am uploading:

```<code>otool -l MyApp.app/MyApp |fgrep --after-context=3 LC_VERSION_MIN_IPHONEOS
  cmd LC_VERSION_MIN_IPHONEOS
cmdsize 16
version 8.3
    sdk 10.2
--
cmd LC_VERSION_MIN_IPHONEOS
cmdsize 16
version 8.3
    sdk 10.2
</code>```

I grepped both the package and my project directory, there is no friggin' "8.2" string anywhere. The same app without the watch extension validates fine. It seems they have broken the watch submissions (at least WatchOS1), which is something they should have noticed, yet I emailed support 2 days ago with screenshots and they were unimpressed, telling me to send them a video if I want my ticket to be processed! Take 1 minute to look at the upload log, I gave you app ID and timestamp, how hard is that?

Edit: It seems I installed the previous version of xcode, there is one newer out, but it also doesn't fix the issue, the problem appears to be on the Apple side...

Edit 2: The binary that has not been going through since the day before yesterday, just got uploaded. Maybe it is fixed?

Edit 3: But then you get the message in itunes connect when you try to submit the app. So it seems they are working on it, not completely resolved yet.

Edit 4: SUCCESS! Successfully submitted, waiting for review!

ContentLicense: CC BY-SA 3.0

Body:
I was submitting with an old Xcode version, I thought that was the problem, so went to the latest and it gives me the same message, that I am submitting for 8.2 which is higher than 10.3.

Now, here is where it gets really crazy. I said, OK, maybe there is an issue with 8.2, so I switched my minimum target to 8.3, cleaned, archived, submitted. I STILL GET THE MESSAGE ABOUT 8.2!!!

I exported the package I am uploading:

otool -l MyApp.app/MyApp |fgrep --after-context=3 LC_VERSION_MIN_IPHONEOS
  cmd LC_VERSION_MIN_IPHONEOS
cmdsize 16
version 8.3
    sdk 10.2
--
cmd LC_VERSION_MIN_IPHONEOS
cmdsize 16
version 8.3
    sdk 10.2

I grepped both the package and my project directory, there is no friggin' "8.2" string anywhere. The same app without the watch extension validates fine. It seems they have broken the watch submissions (at least WatchOS1), which is something they should have noticed, yet I emailed support 2 days ago with screenshots and they were unimpressed, telling me to send them a video if I want my ticket to be processed! Take 1 minute to look at the upload log, I gave you app ID and timestamp, how hard is that?

Edit: It seems I installed the previous version of xcode, there is one newer out, but it also doesn't fix the issue, the problem appears to be on the Apple side...

Edit 2: The binary that has not been going through since the day before yesterday, just got uploaded. Maybe it is fixed?

Edit 3: But then you get the message in itunes connect when you try to submit the app. So it seems they are working on it, not completely resolved yet.

Edit 4: SUCCESS! Successfully submitted, waiting for review!


问:
Save Many-to-many relation with extra columns Jpa
I'm in this situation. I have three entities: Form, FormComponent and FormComponentJoin.
It is a many-to-many relation with extra column.
I would like to save a form entity and all his children with a single call to the FormRepository save() method but it doesn't work.
This is the error message:
The error is Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing
These are my entities:

```<code>@Data
@Entity
@Table(name = "form")
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Form implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    private String name;

    @OneToMany(mappedBy = "form", cascade = { CascadeType.PERSIST, CascadeType.MERGE }, orphanRemoval = true)
    @NotFound(action = NotFoundAction.IGNORE)
    @Singular
    private List<FormComponentJoin> formComponentJoin = new ArrayList<>();

}

@Data
@EqualsAndHashCode
@Entity
@Table(name = "form_component")
@AllArgsConstructor(suppressConstructorProperties = true)
@NoArgsConstructor
public class FormComponent implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    @JsonIgnore
    @OneToMany(mappedBy = "formComponent", cascade = CascadeType.ALL, orphanRemoval = true)
    @NotFound(action = NotFoundAction.IGNORE)
    private List<FormComponentJoin> formComponentJoin = new ArrayList<>();

    @ManyToOne
    @JsonIgnore
    private FormComponent parent;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    @Singular
    private List<FormComponent> children;

    private String value;
}

@Entity
@Table(name = "form_component_join")
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class FormComponentJoin implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    @ManyToOne
    @JoinColumn(name = "form_id", referencedColumnName = "id")
    @NotFound(action = NotFoundAction.IGNORE)
    @JsonIgnore
    private Form form;

    @ManyToOne
    @JoinColumn(name = "form_component_id", referencedColumnName = "id")
    @NotFound(action = NotFoundAction.IGNORE)
    private FormComponent formComponent;

    @Column(name = "position")
    private int pos;

}

@Repository
@Transactional(readOnly = true)
public interface FormRepository extends PagingAndSortingRepository<Form, String> {

}
</code>```

In order to do tests I use the CommandLineRunner:

```<code>@Bean
public CommandLineRunner initDatabase(FormRepository formRepository) {
    return (args) -> {

    FormComponent formComponent1 = FormComponent.builder().value("test").build();
    formComponent1.setChildren(null);
    formComponent1.setParent(null);

    FormComponentJoin formComponentJoin1 = FormComponentJoin.builder().pos(1).formComponent(formComponent1).build();

    Form form = Form.builder().name("test").build()).child(formComponentJoin1).build();
    formComponentJoin1.setForm(form);

    form = formRepository.save(form);

}
</code>```

This is the full stack trace:

Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.fao.backend.entity.FormComponentJoin.formComponent -> org.fao.backend.entity.FormComponent
        at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:398)
        at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:129)
        at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:442)
        at org.hibernate.event.internal.DefaultPersistEventListener.justCascade(DefaultPersistEventListener.java:188)
        at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:181)
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:145)
        at org.hibernate.internal.SessionImpl.firePersistOnFlush(SessionImpl.java:838)
        at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:831)
        at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:357)
        at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
        at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
        at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
        at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:379)
        at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:319)
        at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:296)
        at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
        at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
        at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:167)
        at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:158)
        at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:91)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
        at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
        at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
        at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
        at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
        ... 58 common frames omitted

答:
Eventually I understand that the error was the mapping in the FormComponentJoin entity.

This is the new mapping:

```<code>@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE })
@JoinColumn(name = "form_id") // , referencedColumnName = "id"
@NotFound(action = NotFoundAction.IGNORE)
@JsonIgnore
private Form form;

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "form_component_id") // , referencedColumnName = "id"
@NotFound(action = NotFoundAction.IGNORE)
private FormComponent formComponent;
</code>```

Body:
I'm in this situation. I have three entities: Form, FormComponent and FormComponentJoin.
It is a many-to-many relation with extra column.
I would like to save a form entity and all his children with a single call to the FormRepository save() method but it doesn't work.
This is the error message:
The error is Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing
These are my entities:

@Data
@Entity
@Table(name = "form")
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Form implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    private String name;

    @OneToMany(mappedBy = "form", cascade = { CascadeType.PERSIST, CascadeType.MERGE }, orphanRemoval = true)
    @NotFound(action = NotFoundAction.IGNORE)
    @Singular
    private List<FormComponentJoin> formComponentJoin = new ArrayList<>();

}

@Data
@EqualsAndHashCode
@Entity
@Table(name = "form_component")
@AllArgsConstructor(suppressConstructorProperties = true)
@NoArgsConstructor
public class FormComponent implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    @JsonIgnore
    @OneToMany(mappedBy = "formComponent", cascade = CascadeType.ALL, orphanRemoval = true)
    @NotFound(action = NotFoundAction.IGNORE)
    private List<FormComponentJoin> formComponentJoin = new ArrayList<>();

    @ManyToOne
    @JsonIgnore
    private FormComponent parent;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    @Singular
    private List<FormComponent> children;

    private String value;
}

@Entity
@Table(name = "form_component_join")
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class FormComponentJoin implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    @ManyToOne
    @JoinColumn(name = "form_id", referencedColumnName = "id")
    @NotFound(action = NotFoundAction.IGNORE)
    @JsonIgnore
    private Form form;

    @ManyToOne
    @JoinColumn(name = "form_component_id", referencedColumnName = "id")
    @NotFound(action = NotFoundAction.IGNORE)
    private FormComponent formComponent;

    @Column(name = "position")
    private int pos;

}

@Repository
@Transactional(readOnly = true)
public interface FormRepository extends PagingAndSortingRepository<Form, String> {

}

In order to do tests I use the CommandLineRunner:

@Bean
public CommandLineRunner initDatabase(FormRepository formRepository) {
    return (args) -> {

    FormComponent formComponent1 = FormComponent.builder().value("test").build();
    formComponent1.setChildren(null);
    formComponent1.setParent(null);

    FormComponentJoin formComponentJoin1 = FormComponentJoin.builder().pos(1).formComponent(formComponent1).build();

    Form form = Form.builder().name("test").build()).child(formComponentJoin1).build();
    formComponentJoin1.setForm(form);

    form = formRepository.save(form);

}

This is the full stack trace:

Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.fao.backend.entity.FormComponentJoin.formComponent -> org.fao.backend.entity.FormComponent
        at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:398)
        at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:129)
        at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:442)
        at org.hibernate.event.internal.DefaultPersistEventListener.justCascade(DefaultPersistEventListener.java:188)
        at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:181)
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:145)
        at org.hibernate.internal.SessionImpl.firePersistOnFlush(SessionImpl.java:838)
        at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:831)
        at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:357)
        at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
        at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
        at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
        at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:379)
        at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:319)
        at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:296)
        at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
        at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
        at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:167)
        at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:158)
        at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:91)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
        at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
        at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
        at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
        at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
        ... 58 common frames omitted

Body:
Eventually I understand that the error was the mapping in the FormComponentJoin entity.

This is the new mapping:

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE })
@JoinColumn(name = "form_id") // , referencedColumnName = "id"
@NotFound(action = NotFoundAction.IGNORE)
@JsonIgnore
private Form form;

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "form_component_id") // , referencedColumnName = "id"
@NotFound(action = NotFoundAction.IGNORE)
private FormComponent formComponent;


问:
Chart.js & Angular 2 - ng2-charts Custom on Click Event
I am trying to implement ng2-charts in my Angular 2 project and I was wondering about creating custom onclick events. Meaning, I want to override the current onclick events on the carts to do some custom functions (redirect to a page, have a modal show up, etc).

Is there a simple way to do this? Is it built in at all?

Any insight would be appreciated it

答:
```<code> public chartClicked(e: any): void {
     console.log(e);
 }
</code>```

e.active[0]._model and e.active[0]._view contain information about the part of the chart you clicked (i.e. label).

Body:
 public chartClicked(e: any): void {
     console.log(e);
 }

e.active[0]._model and e.active[0]._view contain information about the part of the chart you clicked (i.e. label).


问:
Google Maps - Get cities by country
I want to list all cities by country, also get latitude and longitude of the city.

How can I do this by google maps?

答: how about using a data source instead?  something like http://www.geonames.org/ ?</p>

Title: Google Maps - Get cities by country


问:
where cause on related mode django
I have 2 models

```<code>class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = models.ForeignKey(Parent,related_name='child')
    child_name = models.CharField(max_length=80)
    type = models.BooleanField()
</code>```

I want to fetch result from parent model and related records from child

```<code>Parent.objects.all()
</code>```

it returns me all records form parent and child IN django rest framework but I want only that child which type is ture, how can i add condition

Please let me know

答:
In your Parent generic list api view override the get_queryset method:

```<code>def get_queryset(self):
    return (Parent.objects.all()
            .prefetch_related(Prefetch('child', queryset=Child.objects.filter(type=True))))
</code>```

Also on a side note I suggest you not to name the field type on child model since it conflicts with the python keyword type. And another suggestion is to use the related_name value as children.

Title: where cause on related mode django

Body:
I have 2 models

class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = models.ForeignKey(Parent,related_name='child')
    child_name = models.CharField(max_length=80)
    type = models.BooleanField()

I want to fetch result from parent model and related records from child

Parent.objects.all()

it returns me all records form parent and child IN django rest framework but I want only that child which type is ture, how can i add condition

Please let me know

Body:
In your Parent generic list api view override the get_queryset method:

def get_queryset(self):
    return (Parent.objects.all()
            .prefetch_related(Prefetch('child', queryset=Child.objects.filter(type=True))))

Also on a side note I suggest you not to name the field type on child model since it conflicts with the python keyword type. And another suggestion is to use the related_name value as children.


问:
Unable to select DropBox of an element which is a link and a dropbox
As part of work I have to automate a certain functionality But I am facing an issue in finding an element.

When I select the object and perform the operation. Selenium is performing operation link instead of selecting the dropbox.

Any suggestions would be appreciated.

```<code>Xapth=""//a[@id='TabBar:AccountTab']//span[contains(@class,'x-btn-wrap x-btn-split')] which I used to find the dropbox.
</code>```

HTML content for element 'ACCOUNT":

Des
k
top

A
c
count

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

<p>Element "Account" image:</p>

<p><img src="https://i.stack.imgur.com/xLXVz.png" alt="Element Account"></p>

<p>========================================================================</p>

<p><strong>HTML content for element to select from dropdown:</strong></p>

<h2>    New Account          </h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu-1037-innerCt" class="x-box-inner x-vertical-box-overflow-body" role="presentation" style="height: 169px; width: 366px;">
<div id="menu-1037-targetEl" class="x-box-target" role="presentation" style="width: 366px;">
<div id="TabBar:AccountTab:AccountTab_NewAccount" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 0px; margin: 0px; width: 366px;">

<span id="TabBar:AccountTab:AccountTab_NewAccount-textEl" class="x-menu-item-text" unselectable="on">New Account</span>

</div>
<table id="TabBar:AccountTab:AccountTab_AccountNumberSearchItem" class="x-field x-table-plain x-form-item x-form-type-text x-box-item x-field-default x-vbox-form-item x-menu-item-cmp x-menu-item-indent" cellpadding="0" role="presentation" style="table-layout: auto; right: auto; left: 32px; top: 24px; width: 329px; margin: 0px;">
<div id="TabBar:AccountTab:0:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 49px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:1:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 73px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:2:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 97px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:3:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked" style="right: auto; left: 0px; top: 121px; margin: 0px; width: 366px;">
<div id="TabBar:AccountTab:4:accountItem" class="x-component x-box-item x-component-default x-menu-item x-menu-item-unchecked x-menu-item-active" style="right: auto; left: 0px; top: 145px; margin: 0px; width: 366px;">
</div>
</div></code>```

Dropdown element "New Account" image:

Updated Element Image:
Element "New Account"

答:
Then try this :</p>

```<code>Select drp = new Select(driver.findElement(By.xpath("//a[@id='TabBar:AccountTab']/span")));
drp.selectByVisibleText("Value which you want to select");
</code>```

Body:
As part of work I have to automate a certain functionality But I am facing an issue in finding an element.

When I select the object and perform the operation. Selenium is performing operation link instead of selecting the dropbox.

Any suggestions would be appreciated.

Xapth=""//a[@id='TabBar:AccountTab']//span[contains(@class,'x-btn-wrap x-btn-split')] which I used to find the dropbox.

HTML content for element 'ACCOUNT":

Des
k
top

A
c
count

Element "Account" image:

========================================================================

HTML content for element to select from dropdown:

    New Account

New Account

Dropdown element "New Account" image:

Updated Element Image:
Element "New Account"

Body:
Then try this :

Select drp = new Select(driver.findElement(By.xpath("//a[@id='TabBar:AccountTab']/span")));
drp.selectByVisibleText("Value which you want to select");


问:
Can multiple Kafka consumers read from the same partition of same topic by default?
Can multiple Kafka consumers read from the same partition of same topic by default? By default, I mean since group.id is not mandatory I am wondering if I spawn multiple kafka consumers without specifying any group.id and give them the same topic and partition name will they be able to read from the same partition? I understand that If I give different group names for each Kafka consumer then all the consumers can read from the same partition.</p>

答:
Can multiple Kafka consumers read from the same partition of same
  topic by default?

Yes.

By default, I mean since group.id is not mandatory I am wondering if I
  spawn multiple kafka consumers without specifying any group.id and
  give them the same topic and partition name will they be able to read
  from the same partition?

Yes.

You can look at https://kafka.apache.org/documentation/#consumerconfigs for
default values for consumer properties.


问:
iptables with regex url matching
What I need to achieve
   I need count how many users open correct websites and sub websites
    e.g. `http://stackoverflow.com'
         'https://stackoverflow.com/questions'

What I have
   router set on Centos 7
   Iptables
   https://github.com/xnsystems/kpcre/wiki/iptables-string-regex

I can't use squid.
   this count system can't change IP headers (src and dst IP address)
   that is why I need count use iptables with log option
   or maybe there is software which will count urls without any packet modification

Problem
   I can't find a way in which I will see how many IP adress (how many users) hit correct url

My iptables row looks like this and doesn't work
   I mean match all urls (with all sub urls) not only http://stackoverflow.com

sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string "^http://stackoverflow.com$" --algo regex -j ACCEPT

Please help me with this case.

UPDATE:

Below three examples please try make them works

```<code>sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string stackoverflow.com --algo regex -j ACCEPT
sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string stackoverflow.com/documentation --algo regex -j ACCEPT
sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string stackoverflow.com/questions'; --algo regex -j ACCEPT
</code>```

As you see I used --algo regex.

If you know another solution without it please suggest.

答:
I checked the specification link, it is not very complete (e.g. \bseems know, but is not explained), but I think the regex you need is:

```<code>^(http:\/\/){0,1}[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+(\/[a-zA-Z0-9_-]+){0,}$
</code>```

UPDATE: Allow http://prefix and /documentation suffix.

Please try.

The use of capture groups () is not specified, but that usually works.

If you give examples which match and should not or do not match and should, I will adapt this answer.
The easiest adaptation is to insert more characters (to be allowed for the URL) between the [a-zA-Z0-9_and the -], in two places.

Title: iptables with regex url matching

Body:
What I need to achieve
   I need count how many users open correct websites and sub websites
    e.g. `http://stackoverflow.com'
         'https://stackoverflow.com/questions'

What I have
   router set on Centos 7
   Iptables
   https://github.com/xnsystems/kpcre/wiki/iptables-string-regex

I can't use squid.
   this count system can't change IP headers (src and dst IP address)
   that is why I need count use iptables with log option
   or maybe there is software which will count urls without any packet modification

Problem
   I can't find a way in which I will see how many IP adress (how many users) hit correct url

My iptables row looks like this and doesn't work
   I mean match all urls (with all sub urls) not only http://stackoverflow.com

sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string "^http://stackoverflow.com$" --algo regex -j ACCEPT

Please help me with this case.

UPDATE:

Below three examples please try make them works

sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string stackoverflow.com --algo regex -j ACCEPT
sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string stackoverflow.com/documentation --algo regex -j ACCEPT
sudo iptables -I OUTPUT -p tcp --dport 80 -m string --string stackoverflow.com/questions'; --algo regex -j ACCEPT

As you see I used --algo regex.

If you know another solution without it please suggest.

Body:
I checked the specification link, it is not very complete (e.g. \bseems know, but is not explained), but I think the regex you need is:

^(http:\/\/){0,1}[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+(\/[a-zA-Z0-9_-]+){0,}$

UPDATE: Allow http://prefix and /documentation suffix.

Please try.

The use of capture groups () is not specified, but that usually works.

If you give examples which match and should not or do not match and should, I will adapt this answer.
The easiest adaptation is to insert more characters (to be allowed for the URL) between the [a-zA-Z0-9_and the -], in two places.


问:
Cross Domain Login - How to log a user in automatically when transferred from one domain to another
We offer a number of online services. We are required to develop a system which provides a quick/simple experience for users if they are transferred from one service (on domain1.com) to another service (on domain2.com).

Is there a safe and secure way to log a user in automatically once he has been transferred to the new service?

Yell at me if the solution below is completely insecure/wrong.

We were considering a system similar to that provided by a number of online services for password recovery - they are emailed a link with a unique hash which expires, that allows them to change their password.

The domain1.com site would generate a unique hash and store it in a database with the hash linked to a user along with an expire datetime field.

The user will be transferred to domain2.com/auto/?hash=d41d8cd98f00b204e9800998ecf8427e

domain2.com would next make a request to domain1.com with the hash to get the information about the user. domain1.com would then remove the hash from the database. domain2.com would log the user in and set cookies, etc.

Could something based on OpenID or OAuth achieve the same results?

答:
There wouldn't be any point using SSL for the cross-domain login unless you use SSL for the entire session.  It is just as easy to steal a session cookie as it is to use a hash in an url.  What is the point in hiding the hash in SSL if the rest of the session is insecure.

The method given at the top is pretty much the standard method.  Whether you choose to use secure protocols is another matter entirely, but it would be pointless to only encrypt part of the session.

OwnerDisplayName: smashedmercury

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Sam Hasler


问:
Get dimension or CGRect of UIImage after AspectFit
I am just finding the way to get the image size whenever it aspect fit to imageview. but didn't get any proper way to get the image dimension.  I just want to calculate the difference between the imageview and the actual image in the imageview. Please advice.

答:
Actually, when the image is showed, its size(instance of Image) doesn't change unless you call compressing image functions.

The only problem is how it's drawn on ImageView.
When you use aspect fit to imageview, the image is drawn keeping its own rate between width and height based on the larger one of width and height of ImageView.

So, how to calculate the drawn image size is showed above by @Luan Tran.

Thanks

Hope it help


问:
How to check two arrays of objects by propery id and if there is mach add property from one to anothe
How to compare two arrays of objects by id and then if id's match add property cr with value to matching object in the array arr.

```<code>var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

var arr1 =[{
    id:1,
    cr:1313
}, {
    id:2,
    cr:304
}];
</code>```

I have searched for similar questions but could not find any or did not see that.

答:
Loop on each array, compare their ids and if it's a match, assign your second object to your first one:</p>

```<code>arr1.forEach(function(obj1) {
  arr.forEach(function(obj) {
    if (obj1.id === obj.id) {
      Object.assign(obj, obj1)
    }
  })
})
</code>```

Body:
How to compare two arrays of objects by id and then if id's match add property cr with value to matching object in the array arr.

var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

var arr1 =[{
    id:1,
    cr:1313
}, {
    id:2,
    cr:304
}];

I have searched for similar questions but could not find any or did not see that.

Body:
Loop on each array, compare their ids and if it's a match, assign your second object to your first one:

arr1.forEach(function(obj1) {
  arr.forEach(function(obj) {
    if (obj1.id === obj.id) {
      Object.assign(obj, obj1)
    }
  })
})


问:
Using wkhtmltopdf with dynamic templates
I want to generate a PDf of a django template / view; that uses templatetags etc.

From django-wkhtmltopdf's documentation:

```<code>from django.conf.urls.defaults import url, patterns
from wkhtmltopdf.views import PDFTemplateView

urlpatterns = patterns('',
    url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
                                           filename='my_pdf.pdf'), name='pdf'),
)
</code>```

Or they say in your own view:

```<code>from wkhtmltopdf.views import PDFTemplateView

class MyPDF(PDFTemplateView):
    filename = 'my_pdf.pdf'
    template_name = 'my_template.html'
    cmd_options = {
        'margin-top': 3,
    }
</code>```

If this was my view:

```<code>def download_report(request):
    vends = Vends.objects.all()
    return render(request, 'report_template.html', {'vends':vends})
</code>```

How would I generate a report of this VIEW as its rendered? Not just the template, because that would be useless?

答:
It looks like I'm 3 years late :) I put here a working code sample anyway, as reference for future needs:

urls.py

```<code># here you must import MyPDF from [your-app-name].views

urlpatterns = [
  url(r'^pdf/$', MyPDF.as_view(template_name='my_template.html',
                                             filename='my_pdf.pdf'), name='pdf'),
]
</code>```

views.py

```<code>from wkhtmltopdf.views import PDFTemplateView

class MyPDF(PDFTemplateView):
    def get_context_data(self, **kwargs):
        context = super(MyPDF, self).get_context_data(**kwargs)
        context['foo'] = 'BAR'
        return context
</code>```

my_template.html

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
    <h1>{{ foo }}</h1>
</body>
</html>
</code>```

Body:
I want to generate a PDf of a django template / view; that uses templatetags etc.

From django-wkhtmltopdf's documentation:

from django.conf.urls.defaults import url, patterns
from wkhtmltopdf.views import PDFTemplateView

urlpatterns = patterns('',
    url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
                                           filename='my_pdf.pdf'), name='pdf'),
)

Or they say in your own view:

from wkhtmltopdf.views import PDFTemplateView

class MyPDF(PDFTemplateView):
    filename = 'my_pdf.pdf'
    template_name = 'my_template.html'
    cmd_options = {
        'margin-top': 3,
    }

If this was my view:

def download_report(request):
    vends = Vends.objects.all()
    return render(request, 'report_template.html', {'vends':vends})

How would I generate a report of this VIEW as its rendered? Not just the template, because that would be useless?

Body:
It looks like I'm 3 years late :) I put here a working code sample anyway, as reference for future needs:

urls.py

# here you must import MyPDF from [your-app-name].views

urlpatterns = [
  url(r'^pdf/$', MyPDF.as_view(template_name='my_template.html',
                                             filename='my_pdf.pdf'), name='pdf'),
]

views.py

from wkhtmltopdf.views import PDFTemplateView

class MyPDF(PDFTemplateView):
    def get_context_data(self, **kwargs):
        context = super(MyPDF, self).get_context_data(**kwargs)
        context['foo'] = 'BAR'
        return context

my_template.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
    <h1>{{ foo }}</h1>
</body>
</html>


问:
How to avoid to enter repeated number in input text form?
I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,

sample code,

```<code>var mobNumber = $('#phNo').val();

if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
  alert('Please enter valid phone number');
}
</code>```

答:
You could use following regex ^(\d)\1+$ :

^ asserts position at start of the string

(...) 1st capturing group

\d matches a digit (equal to [0-9])

\1 matches the same text as most recently matched by the 1st capturing group

+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).

See following example:

function test(par){
  if(par.match(/^(\d)\1+$/g)){
    console.log(par + " is not valid");
  }else{
    console.log(par + " is valid");
  }
}

test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");```

I hope it helps you. Bye

Body:
I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,

sample code,

var mobNumber = $('#phNo').val();

if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
  alert('Please enter valid phone number');
}

Body:
You could use following regex ^(\d)\1+$ :

^ asserts position at start of the string

(...) 1st capturing group

\d matches a digit (equal to [0-9])

\1 matches the same text as most recently matched by the 1st capturing group

+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).

See following example:

function test(par){
  if(par.match(/^(\d)\1+$/g)){
    console.log(par + " is not valid");
  }else{
    console.log(par + " is valid");
  }
}

test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");

I hope it helps you. Bye


问:
Set value in the second input based on the first input
I have two input fields in Wordpress Options Page. I am calculating the costs and then setting the value in the corresponding input field but it's setting in all of the second input. I want the value to be set only in the corresponding input field.

JSFiddle

$('input[id^="calc_transport_"]').on('change', function() {
  var transport_margin_cost = getRandomNumber();
  $('input[id^="calc_m_transport_"]').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="form-table">
  <tbody>
    <tr>
      <th scope="row">1 KG</th>
      <td>
        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">2 KG</th>
      <td>
        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">3 KG</th>
      <td>
        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">4 KG</th>
      <td>
        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">5 KG</th>
      <td>
        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">
      </td>
    </tr>
  </tbody>
</table></code>```

答:
Use next and this to find next input. next only looks at the next sibling elemnet on the dom.

```<code> $(this).next('input')
</code>```

   $('input[id^="calc_transport_"]').on('change', function() {
   var transport_margin_cost = getRandomNumber();
   $(this).next('input').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="form-table">
  <tbody>
    <tr>
      <th scope="row">1 KG</th>
      <td>
        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">2 KG</th>
      <td>
        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">3 KG</th>
      <td>
        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">4 KG</th>
      <td>
        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">5 KG</th>
      <td>
        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">
      </td>
    </tr>
  </tbody>
</table></code>```

Body:
I have two input fields in Wordpress Options Page. I am calculating the costs and then setting the value in the corresponding input field but it's setting in all of the second input. I want the value to be set only in the corresponding input field.

JSFiddle

$('input[id^="calc_transport_"]').on('change', function() {
  var transport_margin_cost = getRandomNumber();
  $('input[id^="calc_m_transport_"]').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}

      1 KG

        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">

      2 KG

        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">

      3 KG

        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">

      4 KG

        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">

      5 KG

        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">

Body:
Use next and this to find next input. next only looks at the next sibling elemnet on the dom.

 $(this).next('input')

   $('input[id^="calc_transport_"]').on('change', function() {
   var transport_margin_cost = getRandomNumber();
   $(this).next('input').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="form-table">
  <tbody>
    <tr>
      <th scope="row">1 KG</th>
      <td>
        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">2 KG</th>
      <td>
        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">3 KG</th>
      <td>
        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">4 KG</th>
      <td>
        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">5 KG</th>
      <td>
        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">
      </td>
    </tr>
  </tbody>
</table>


问:
Include variable value on data frame name
I'm trying to figure out how can I add something to a data frame df, based on a variable (i.e. a date), ending up with a data frame named df_17 if variable is equal to 2017 for example.

The reason why I want this is because I'm importing datasets from several years and quarters, and I would like to make sure that they are named according to the year variable they have. Each dataset only has 1 date. I know I can do it manually but it would take me less time to automate it.

I know how to do it with columns and rows, but I can't figure it out for objects.

EDIT:

Example 1:
Data frame name "df"

```<code>A   B   Date
1   4   2017
2   3   2017
</code>```

New data frame name "df_2017"

Example 2:
Data frame name "df"

```<code>A   B   Date
1   4   2016
2   3   2016
</code>```

New data frame name - "df_2016 "

答:
The assign function should do what you want. A solution could look like

```<code>assign(paste0("df_", year), dataframe_read_from_file, pos = 1)
</code>```

If you use assign inside a function oder a loop, make sure that you set the pos option correctly.

Body:
I'm trying to figure out how can I add something to a data frame df, based on a variable (i.e. a date), ending up with a data frame named df_17 if variable is equal to 2017 for example.

The reason why I want this is because I'm importing datasets from several years and quarters, and I would like to make sure that they are named according to the year variable they have. Each dataset only has 1 date. I know I can do it manually but it would take me less time to automate it.

I know how to do it with columns and rows, but I can't figure it out for objects.

EDIT:

Example 1:
Data frame name "df"

A   B   Date
1   4   2017
2   3   2017

New data frame name "df_2017"

Example 2:
Data frame name "df"

A   B   Date
1   4   2016
2   3   2016

New data frame name - "df_2016 "

Body:
The assign function should do what you want. A solution could look like

assign(paste0("df_", year), dataframe_read_from_file, pos = 1)

If you use assign inside a function oder a loop, make sure that you set the pos option correctly.


问:
Deploying multi-tenant on Amazon RDS (individual DB for each tenant)
I am currently conceptualizing a cloud application (SaaS) and I am looking to create a DB for every user (tenant) that is registering an account.

May I know if it is programmatically possible to create a new DB on Amazon RDS through API or anything?

答:
Databases are created on RDS using standard SQL DDL statements -- not the API.

For example:

To create additional databases, connect to the DB instance and use the SQL command CREATE DATABASE.

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateInstance.html


问:
Send data from onSharedPreferenceChanged() to another UI Fragment
I play Loop Background Music in app, I use SoundPool.
Also I use PreferenceFragment (and sharedPreferences of course), and UI checkbox “Background Music On/Off”.

As soon as the user remove/set the UI checkbox from Preference Fragment, background music should be to stop/start play it immediately.

Question:

How to send data from PreferenceFragment from onSharedPreferenceChanged() to another UI fragment immediately (see the diagram)?
Thx.

UPD
Problem solved.

Make an Object (which directly controls the sound) as Singleton.
Then from onSharedPreferenceChanged called SoundPool_pause_method directly.

Perhaps this is not true in terms of architecture.

I (quickly) read a lot of information:
Using MediaPlayer in a service,
AsyncTask (I already know that it is not appropriate),
Executor,
ThreadPoolExecutor,
FutureTask,
HandlerThread.

答:
If you are in search of a quick solution then you can try firing custom broadcasts.

You can check tutorial here.  Your MainUIFragment will be BroadcastListener which will listen to specific custom event broadcast which can be fired by PreferenceFragment when intended.

Declaring in manifest

```<code> <receiver android:name="MyReceiver">
         <intent-filter>
            <action android:name="some.identifier.string">
            </action>
         </intent-filter>
  </receiver>
</code>```

Custom Receiver to handle event broadcasts

```<code>public class MyReceiver extends BroadcastReceiver{
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
   }
}
</code>```

Firing event from

```<code>public void broadcastIntent(View view){
      Intent intent = new Intent();
      intent.setAction("some.string.identifier"); sendBroadcast(intent);
   }
</code>```

Body:
If you are in search of a quick solution then you can try firing custom broadcasts.

You can check tutorial here.  Your MainUIFragment will be BroadcastListener which will listen to specific custom event broadcast which can be fired by PreferenceFragment when intended.

Declaring in manifest

 <receiver android:name="MyReceiver">
         <intent-filter>
            <action android:name="some.identifier.string">
            </action>
         </intent-filter>
  </receiver>

Custom Receiver to handle event broadcasts

public class MyReceiver extends BroadcastReceiver{
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
   }
}

Firing event from

public void broadcastIntent(View view){
      Intent intent = new Intent();
      intent.setAction("some.string.identifier"); sendBroadcast(intent);
   }


问:
Android. How test duration execution of method?
I write unit test (JUnit, Espresso) for Android app.

And I want to test the duration of execution of any method in Activity. And my test must be fail if duration more than 1 second.

Is it possible in Android?

答:
Here's an example:</p>

```<code> private long durationTest() {
    long timeBeforeExecution = System.currentTimeMillis();

    someMethod();

    return System.currentTimeMillis() - timeBeforeExecution;  // difference in millis
}

private void someMethod() {
    ...
}
</code>```

Body:
Here's an example:

 private long durationTest() {
    long timeBeforeExecution = System.currentTimeMillis();

    someMethod();

    return System.currentTimeMillis() - timeBeforeExecution;  // difference in millis
}

private void someMethod() {
    ...
}


问:
Updating ArangoDB sub document
I am currently evaluating whether ArangoDB can be a future alternative for us. As a part of this evaluation I am porting code that talks to our current NoSQL db into code that speaks ArangoDB. While it has been a fairly smooth ride so far, I am having surprisingly difficult to wrap my head around on how to update sub documents. Assuming we have something like this:

```<code>{
    "_key": "12345",
    "subdoc": {
        "0": {
            "num_sold": 6,
            "other_attribute": "important"

     },
        "1": {
            "num_sold": 4,
            "other_attribute": "important"
     }
    }
}
</code>```

What I would like to accomplish now it to atomically increase num_sold.

A very first naive approach was of course to try something similar to:

```<code>FOR d in @@collection
   FILTER d._key == "12345"
   UPDATE d WITH { subdoc.0.num_sold : subdoc.0.num_sold + 1 } IN @@collection
RETURN d
</code>```

(Spoiler alert for the copy-pasters out there: move on. This snippet will just make your life miserable.)

This obviously didn't work and most likely for more than one reason. Arango does not seem to like me referencing the attribute using dot notation, the attribute starting with a number ("0") might also be an issue etc. While having found an example here it seemed both a bit complicated and convoluted for what I am trying to do. There is also another discussion here that is close to what I would like to do. However, the proposed solution in that discussion uses the keyword OLD that creates an error in my case as well as the code replacing all keys in "0".

1) What is the best way to atomically increase num_sold?

2) When is an operation atomic? (Trying to stay away from transactions as long as possible)

3) When can the dot notation be used and when can it not be used?

4) Can I bind parameters to an attribute? For instance letting some @attribute be subdoc.0.num_sold?

Thanks!

答:
ArangoDB can't parse the query if you use numbers in the dot notation.
However there is an easy way - simply use brackets instead of the dot notation as you did.

Example - not working:

```<code>db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.0`)

ArangoError 1501: syntax error, unexpected integer number,
expecting identifier or bind parameter near '0' at
position 1:60 (while parsing)
</code>```

Example - fixed:

```<code>db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.[0]`)

[
  "abc"
]
</code>```

Using bind variables - not working:

```<code>db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.@bv`, {bv: 0})

ArangoError 1501: syntax error, unexpected integer number,
expecting identifier or bind parameter near '0' at
position 1:60 (while parsing)
</code>```

Using bind variables - fixed:

```<code>db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.[@bv]`, {bv:0})

[
  "abc"
]
</code>```

Title: Updating ArangoDB sub document

Body:
I am currently evaluating whether ArangoDB can be a future alternative for us. As a part of this evaluation I am porting code that talks to our current NoSQL db into code that speaks ArangoDB. While it has been a fairly smooth ride so far, I am having surprisingly difficult to wrap my head around on how to update sub documents. Assuming we have something like this:

{
    "_key": "12345",
    "subdoc": {
        "0": {
            "num_sold": 6,
            "other_attribute": "important"

     },
        "1": {
            "num_sold": 4,
            "other_attribute": "important"
     }
    }
}

What I would like to accomplish now it to atomically increase num_sold.

A very first naive approach was of course to try something similar to:

FOR d in @@collection
   FILTER d._key == "12345"
   UPDATE d WITH { subdoc.0.num_sold : subdoc.0.num_sold + 1 } IN @@collection
RETURN d

(Spoiler alert for the copy-pasters out there: move on. This snippet will just make your life miserable.)

This obviously didn't work and most likely for more than one reason. Arango does not seem to like me referencing the attribute using dot notation, the attribute starting with a number ("0") might also be an issue etc. While having found an example here it seemed both a bit complicated and convoluted for what I am trying to do. There is also another discussion here that is close to what I would like to do. However, the proposed solution in that discussion uses the keyword OLD that creates an error in my case as well as the code replacing all keys in "0".

1) What is the best way to atomically increase num_sold?

2) When is an operation atomic? (Trying to stay away from transactions as long as possible)

3) When can the dot notation be used and when can it not be used?

4) Can I bind parameters to an attribute? For instance letting some @attribute be subdoc.0.num_sold?

Thanks!

Body:
ArangoDB can't parse the query if you use numbers in the dot notation.
However there is an easy way - simply use brackets instead of the dot notation as you did.

Example - not working:

db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.0`)

ArangoError 1501: syntax error, unexpected integer number,
expecting identifier or bind parameter near '0' at
position 1:60 (while parsing)

Example - fixed:

db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.[0]`)

[
  "abc"
]

Using bind variables - not working:

db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.@bv`, {bv: 0})

ArangoError 1501: syntax error, unexpected integer number,
expecting identifier or bind parameter near '0' at
position 1:60 (while parsing)

Using bind variables - fixed:

db._query(`
  LET testdoc = {subdoc: {"0": "abc"}}
     RETURN testdoc.subdoc.[@bv]`, {bv:0})

[
  "abc"
]


问:
Is there a way of reading HTML tags on the page that are not part of the DOM using javascript?
I have a Chrome Extension that reads meta tags from the current tab in order to display information about the current page to the user.

I've noticed that currently on YouTube, the meta tags containing information about the current video are not accessible via the DOM (open up the Dev Console and check out document.head, no meta tags about the current video are present), yet they are on the page if you look at the page source. I guess they are adding them using document.write as they don't want them part of the DOM.

Is there another way I can access these tags using javascript?

答:
If you want the full list of meta, before it's manipulated by javascript - try this in the console of a youtube video

```<code>fetch('').then(r=>r.text()).then(html=> {
    let p = new DOMParser(),
        d = p.parseFromString(html, 'text/html');
    console.log(d.querySelectorAll('meta'));
});
</code>```

I see 71 meta tags in one example video

I'm sure this can be easily accomplished in a web extension

Body:
If you want the full list of meta, before it's manipulated by javascript - try this in the console of a youtube video

fetch('').then(r=>r.text()).then(html=> {
    let p = new DOMParser(),
        d = p.parseFromString(html, 'text/html');
    console.log(d.querySelectorAll('meta'));
});

I see 71 meta tags in one example video

I'm sure this can be easily accomplished in a web extension


问:
Angular 4.0.0 App built by angular-cli 1.0.0 not working in IE11
I try to run my virgin Angular 4 Application built by the angular-cli 1.0.0 in the Internet Explorer 11, but I have no success and I get the following error:

```<code>Error: The "apply" property of an undefined or null reference can not be retrieved.
</code>```

I have no additional library installed, it is just a new generated project. In Google Chrome it is working perfectly.
My package.json:

```<code>{
"name": "angi4testie",
"version": "0.0.0",
"license": "MIT",
"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},
"private": true,
"dependencies": {
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",
  "core-js": "^2.4.1",
  "rxjs": "^5.1.0",
  "zone.js": "^0.8.4"
},
"devDependencies": {
  "@angular/cli": "1.0.0",
  "@angular/compiler-cli": "^4.0.0",
  "@types/jasmine": "2.5.38",
  "@types/node": "~6.0.60",
  "codelyzer": "~2.0.0",
  "jasmine-core": "~2.5.2",
  "jasmine-spec-reporter": "~3.2.0",
  "karma": "~1.4.1",
  "karma-chrome-launcher": "~2.0.0",
  "karma-cli": "~1.0.1",
  "karma-jasmine": "~1.1.0",
  "karma-jasmine-html-reporter": "^0.2.2",
  "karma-coverage-istanbul-reporter": "^0.2.0",
  "protractor": "~5.1.0",
  "ts-node": "~2.0.0",
  "tslint": "~4.5.0",
  "typescript": "~2.2.0"
}
}
</code>```

答:
There is a need for a ES6 polyfill for IE 11. So you have to add a script tag for that required polyfill in order for your app to run on IE11.

See the docs for guidance on browser support.

Body:
I try to run my virgin Angular 4 Application built by the angular-cli 1.0.0 in the Internet Explorer 11, but I have no success and I get the following error:

Error: The "apply" property of an undefined or null reference can not be retrieved.

I have no additional library installed, it is just a new generated project. In Google Chrome it is working perfectly.
My package.json:

{
"name": "angi4testie",
"version": "0.0.0",
"license": "MIT",
"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},
"private": true,
"dependencies": {
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",
  "core-js": "^2.4.1",
  "rxjs": "^5.1.0",
  "zone.js": "^0.8.4"
},
"devDependencies": {
  "@angular/cli": "1.0.0",
  "@angular/compiler-cli": "^4.0.0",
  "@types/jasmine": "2.5.38",
  "@types/node": "~6.0.60",
  "codelyzer": "~2.0.0",
  "jasmine-core": "~2.5.2",
  "jasmine-spec-reporter": "~3.2.0",
  "karma": "~1.4.1",
  "karma-chrome-launcher": "~2.0.0",
  "karma-cli": "~1.0.1",
  "karma-jasmine": "~1.1.0",
  "karma-jasmine-html-reporter": "^0.2.2",
  "karma-coverage-istanbul-reporter": "^0.2.0",
  "protractor": "~5.1.0",
  "ts-node": "~2.0.0",
  "tslint": "~4.5.0",
  "typescript": "~2.2.0"
}
}


问:
"could not extract ResultSet" in JPQL GROUP BY query
In my Spring Boot 1.5 application with Spring Data JPA, I have a TDR table like:

```<code>     Table TDR
-----------------------
id | c_id | m_id | p_id
 1 |   1  |    1 |    1
 2 |   1  |    1 |    2
 3 |   2  |    1 |    1
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1
</code>```

where I need to find the last records grouped by m_id and p_id. With PostgreSQL SQL, I do this with the MAX aggregate function:

```<code>SELECT t.id, t.c_id, t.m_id, t.p_id
FROM (
  SELECT MAX(id) AS id, m_id, p_id
  FROM tdr
  WHERE m_id = 1                      -- <<< parameterized below
  GROUP BY m_id, p_id
  ) m JOIN tdr t ON t.id = m.id
</code>```

which returns the correct records:

```<code>     Table TDR
-----------------------
id | c_id | m_id | p_id
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1
</code>```

Since the GROUP BY does not include c_id, the SQL is structured as correlated sub-query and matched with a join (see this question for details).

I'd like to convert this SQL to JPQL with this Lombok @Data entity:

```<code>@Data
@Entity
@Table(name = "TDR")
public class TDR implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="m_id")
    private M m;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="p_id")
    private P p;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="c_id")
    private C c;
}
</code>```

but my JPQL for the correlated sub-query with parameterized m ID (:m_id):

```<code>SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) AS id, t.m, t.p FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )
</code>```

results in this error:

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.postgresql.util.PSQLException: ERROR: subquery has too many columns
</code>```

答:
Select just the join column in the correlated sub-query:

```<code>SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )
</code>```

The ObjectDB GROUP BY article was helpful as was this question.

Body:
In my Spring Boot 1.5 application with Spring Data JPA, I have a TDR table like:

     Table TDR
-----------------------
id | c_id | m_id | p_id
 1 |   1  |    1 |    1
 2 |   1  |    1 |    2
 3 |   2  |    1 |    1
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1

where I need to find the last records grouped by m_id and p_id. With PostgreSQL SQL, I do this with the MAX aggregate function:

SELECT t.id, t.c_id, t.m_id, t.p_id
FROM (
  SELECT MAX(id) AS id, m_id, p_id
  FROM tdr
  WHERE m_id = 1                      -- <<< parameterized below
  GROUP BY m_id, p_id
  ) m JOIN tdr t ON t.id = m.id

which returns the correct records:

     Table TDR
-----------------------
id | c_id | m_id | p_id
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1

Since the GROUP BY does not include c_id, the SQL is structured as correlated sub-query and matched with a join (see this question for details).

I'd like to convert this SQL to JPQL with this Lombok @Data entity:

@Data
@Entity
@Table(name = "TDR")
public class TDR implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="m_id")
    private M m;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="p_id")
    private P p;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="c_id")
    private C c;
}

but my JPQL for the correlated sub-query with parameterized m ID (:m_id):

SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) AS id, t.m, t.p FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )

results in this error:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.postgresql.util.PSQLException: ERROR: subquery has too many columns

Body:
Select just the join column in the correlated sub-query:

SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )

The ObjectDB GROUP BY article was helpful as was this question.


问:
Appending json file to html with condition
I am appending a dynamic json file to html.I would like to change the color of openticket row .td elements if value of .openticket is bigger then x number.

My code looks like:

```<code><table id="userdata" border="2">
   <thead>
      <th>Department</th>
      <th>OpenTickets</th>
   </thead>
   <tbody></tbody>
</table>
</code>```

JS

```<code>function repopulateTable(data) {
    var parsedData = JSON.parse(data);
    console.log(parsedData);
    var dashboard = [];
    dashboard.push(JSON.parse(data));
    dashboard.forEach(function (value, index) {;
        var table1Rows = "";
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (key === 'Item1') {
                    value[key].forEach(function (val) {
                        var tbl1Row = "<tr>" + "<td>" + val.Title + "</td>" + "<td>" + val.Ticketnumber + "</td>" + "</tr>"
                        table1Rows += tbl1Row;
                    })
                }
            }
        }
        $("#userdata tbody").html(table1Rows);
    });
}
</code>```

I have made css

```<code>.color{
   color:red;
}
</code>```

and tried captured the val like and add attribute:

```<code>var capture = $(val.Ticketnumber).val();
if (capture.val)>3{
$("td:second").addClass("color");
}
</code>```

without success.

答:
kindly have a look.

```<code>for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (key === 'Item1') {
                    value[key].forEach(function (val) {
                        var tbl1Row = "<tr " + (parseInt(val.Ticketnumber)>3?" class='color'":"") + ">" + "<td>" + val.Title + "</td>" + "<td>" + val.Ticketnumber + "</td>" + "</tr>"
                        table1Rows += tbl1Row;
                    })
                }
            }
        }
</code>```

In the above code, i have append class based on condition ("3?" color":"") + ">")

Body:
I am appending a dynamic json file to html.I would like to change the color of openticket row .td elements if value of .openticket is bigger then x number.

My code looks like:

      Department
      OpenTickets

JS

function repopulateTable(data) {
    var parsedData = JSON.parse(data);
    console.log(parsedData);
    var dashboard = [];
    dashboard.push(JSON.parse(data));
    dashboard.forEach(function (value, index) {;
        var table1Rows = "";
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (key === 'Item1') {
                    value[key].forEach(function (val) {
                        var tbl1Row = "
" + "" + val.Title + "	" + "" + val.Ticketnumber + "	" + "
"
                        table1Rows += tbl1Row;
                    })
                }
            }
        }
        $("#userdata tbody").html(table1Rows);
    });
}

I have made css

.color{
   color:red;
}

and tried captured the val like and add attribute:

var capture = $(val.Ticketnumber).val();
if (capture.val)>3{
$("td:second").addClass("color");
}

without success.

Body:
kindly have a look.

for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (key === 'Item1') {
                    value[key].forEach(function (val) {
                        var tbl1Row = "<tr " + (parseInt(val.Ticketnumber)>3?" class='color'":"") + ">" + "<td>" + val.Title + "</td>" + "<td>" + val.Ticketnumber + "</td>" + "</tr>"
                        table1Rows += tbl1Row;
                    })
                }
            }
        }

In the above code, i have append class based on condition ("3?" color":"") + ">")


答:
Yes, you can do that although it's hard to predict actual execution time as it depends on many factors. With JUnit you could do something like:

```<code>@Test(timeout=1000) //milliseconds
public void performanceTest() {
    //my code
}
</code>```

This test will fail if not executed under 1000ms and will pass for any other value.

With espresso test I believe you could adjust timeout rules but I don't see how that helps you in any way. UI test my depend on many things, how long it takes to "press" buttons, network response, other threads that have their own time management and depend on other factors. In any case check this:

Android Doc

Title: Android. How test duration execution of method?

Body:
I write unit test (JUnit, Espresso) for Android app.

And I want to test the duration of execution of any method in Activity. And my test must be fail if duration more than 1 second.

Is it possible in Android?

Body:
Yes, you can do that although it's hard to predict actual execution time as it depends on many factors. With JUnit you could do something like:

@Test(timeout=1000) //milliseconds
public void performanceTest() {
    //my code
}

This test will fail if not executed under 1000ms and will pass for any other value.

With espresso test I believe you could adjust timeout rules but I don't see how that helps you in any way. UI test my depend on many things, how long it takes to "press" buttons, network response, other threads that have their own time management and depend on other factors. In any case check this:

Android Doc


问:
create a sample matrix from the main matrix
I want to create a sample matrix from the main one with the sam number of columns but less rows (50) I tried to use a series of loops but it didn't work:</p>

```<code>n=nrow(data)
camp <- sample(1:n,size=50,replace=TRUE)

n<-length(camp)
c<-ncol(data)
for(i in 1:n){
      t<-camp[i]
    for(k in 1:c){
    campione[i,k]<-data[t,k]}
}
</code>```

答:
You don't need to use loop. You just have to take random lines from your main matrix:</p>

```<code>mat = matrix(runif(2000),ncol=20)

sample_matrix = mat[sample(1:nrow(mat),50),]
</code>```

Body:
I want to create a sample matrix from the main one with the sam number of columns but less rows (50) I tried to use a series of loops but it didn't work:

n=nrow(data)
camp <- sample(1:n,size=50,replace=TRUE)

n<-length(camp)
c<-ncol(data)
for(i in 1:n){
      t<-camp[i]
    for(k in 1:c){
    campione[i,k]<-data[t,k]}
}

Body:
You don't need to use loop. You just have to take random lines from your main matrix:

mat = matrix(runif(2000),ncol=20)

sample_matrix = mat[sample(1:nrow(mat),50),]


问:
shell_exec is not executing as expected
I wan't to execute shell script with PHP code which will check if git branch is up to date or push or pull is needed. When i run my code i get error.

This is my code

```<code>$check = shell_exec(
'LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base @ @{u})

if [[ $LOCAL = "$REMOTE" ]]; then
    echo "Up-to-date"
elif [[ $LOCAL = "$BASE" ]]; then
    echo "Need to pull"
elif [[ $REMOTE = "$BASE" ]]; then
    echo "Need to push"
else
    echo "Diverged"
fi');
var_dump($check);
</code>```

And this is the error / response which im getting

```<code>sh: 5: [[: not found
sh: 7: [[: not found
sh: 9: [[: not found
string(9) "Diverged
"
</code>```

So how should my code look like in order to start working? If you need any additional informations, please let me know and i will provide. Thank you

答:
This is probably because <code>[[</code> is a bash-builtin. This may work for you.   </p>

```<code>$check = shell_exec(
'LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base @ @{u})

if [ "$LOCAL" -eq "$REMOTE" ]; then
    echo "Up-to-date"
elif [ "$LOCAL" -eq "$BASE" ]; then
    echo "Need to pull"
elif [ "$REMOTE" -eq "$BASE" ]; then
    echo "Need to push"
else
    echo "Diverged"
fi');
var_dump($check);
</code>```

Title: shell_exec is not executing as expected

Body:
I wan't to execute shell script with PHP code which will check if git branch is up to date or push or pull is needed. When i run my code i get error.

This is my code

$check = shell_exec(
'LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base @ @{u})

if [[ $LOCAL = "$REMOTE" ]]; then
    echo "Up-to-date"
elif [[ $LOCAL = "$BASE" ]]; then
    echo "Need to pull"
elif [[ $REMOTE = "$BASE" ]]; then
    echo "Need to push"
else
    echo "Diverged"
fi');
var_dump($check);

And this is the error / response which im getting

sh: 5: [[: not found
sh: 7: [[: not found
sh: 9: [[: not found
string(9) "Diverged
"

So how should my code look like in order to start working? If you need any additional informations, please let me know and i will provide. Thank you

Body:
This is probably because [[ is a bash-builtin. This may work for you.

$check = shell_exec(
'LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base @ @{u})

if [ "$LOCAL" -eq "$REMOTE" ]; then
    echo "Up-to-date"
elif [ "$LOCAL" -eq "$BASE" ]; then
    echo "Need to pull"
elif [ "$REMOTE" -eq "$BASE" ]; then
    echo "Need to push"
else
    echo "Diverged"
fi');
var_dump($check);


问:
Protractor - Change css property to interact with element
Currently in the page I am testing I have a select that is with display: none in css, so I can not interact with this element. I searched but I did not find anything to help me.

HTML

```<code><select name="preview_district" placeholder="Departamento" data-native-select="true" data-toggle-placeholder="true">
<option value="*" disabled="" selected="" hidden="">(Selecciona)</option>
<option value="91">AMAZONAS</option>
<option value="5">ANTIOQUIA</option>
</select>
</code>```

CSS

```<code>select[data-native-select="true"] {
    display: none;
}
</code>```

答:
I assume you are automating an Angular page, so here we go.

First of all be sure that you can interact with the element when it is visible, you can do this from within the DevTools of your browser, make it visible by adding a display:block. Then check that if you change the value of the selectbox, the value can also be used with Angular Binding.

If so, you can easily make the element visible with Protractor by injecting a piece of Javascript in the page with the following command

```<code>browser.executeScript('document.querySelector(\'[name="preview_district"]\').style.display = "block"');
</code>```

This results in a promise, so be aware of that!

You can also pass the protractor ElementFinder, it wil then look like this (use by.model / by.css / or something else)

```<code>browser.executeScript('arguments[0].style.display = "block"', element(by.css('.your-selector')).getWebElement());
</code>```

Hope it helps

Body:
Currently in the page I am testing I have a select that is with display: none in css, so I can not interact with this element. I searched but I did not find anything to help me.

HTML

<select name="preview_district" placeholder="Departamento" data-native-select="true" data-toggle-placeholder="true">
<option value="*" disabled="" selected="" hidden="">(Selecciona)</option>
<option value="91">AMAZONAS</option>
<option value="5">ANTIOQUIA</option>
</select>

CSS

select[data-native-select="true"] {
    display: none;
}

Body:
I assume you are automating an Angular page, so here we go.

First of all be sure that you can interact with the element when it is visible, you can do this from within the DevTools of your browser, make it visible by adding a display:block. Then check that if you change the value of the selectbox, the value can also be used with Angular Binding.

If so, you can easily make the element visible with Protractor by injecting a piece of Javascript in the page with the following command

browser.executeScript('document.querySelector(\'[name="preview_district"]\').style.display = "block"');

This results in a promise, so be aware of that!

You can also pass the protractor ElementFinder, it wil then look like this (use by.model / by.css / or something else)

browser.executeScript('arguments[0].style.display = "block"', element(by.css('.your-selector')).getWebElement());

Hope it helps


问:
Resize text view and table view cell dynamically in static table view
I have a static table view that I am using as a sot of data entry for my app. One of those cells has a UITextView in it, which needs to grow and shrink dynamically as the user types, as well as the cell growing/shrinking logically with it. I read a bunch of posts on this but I think I am getting thrown because I am using a STATIC table view.

Here is my resizing attempt (its pretty much a total fail):

```<code>- (void)textViewDidChange:(UITextView *)textView
{
    self.numberOfLines = (textView.contentSize.height / textView.font.lineHeight) - 1;

    float height = 44.0;
    height += (textView.font.lineHeight * (self.numberOfLines - 1));

    CGRect textViewFrame = [textView frame];
    textViewFrame.size.height = height - 10.0; //The 10 value is to retrieve the same height padding I inputed earlier when I initialized the UITextView
    [textView setFrame:textViewFrame];

    [self.tableView beginUpdates];
    [self.tableView endUpdates];

    [self.messageTextView setContentInset:UIEdgeInsetsZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 44.0;
    if (self.messageTextView) {
        height += (self.messageTextView.font.lineHeight * (self.numberOfLines - 1));
    }
    return height;
}
</code>```

I'll take any tips! Thanks.

答:
Your will need to manually calculate new size of you textView, and manually call update for your tableView.

```<code>static CGFloat cellHeight = 85;//from story board height to
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 0) {
        return cellHeight + [self appendTextViewNewHeight];
    }
    return cell.bounds.size.height;
}

-(CGFloat) appendTextViewNewHeight {
    return _appendHeightForTextView;
}

static CGFloat textViewHeightStartHeight = 33;//from storiboard height
- (void)textViewDidChange:(UITextView *)textView;
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    if (newFrame.size.height >= textViewHeightStartHeight) {
        CGFloat newAppend = newFrame.size.height - textViewHeightStartHeight;
        if (newAppend != self.appendHeightForTextView) {
            self.appendHeightForTextView = newAppend;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }
    }
}
</code>```

Also you need to set delegates on storyboards on in the code.
in viedDidLoad you need to do next things:

```<code>self.appendHeightForTextView = 0;
</code>```

And finally set constraints in storyboard for your cell. Do not set bottom constraint of your textView. Only set right, left, and top.

Body:
I have a static table view that I am using as a sot of data entry for my app. One of those cells has a UITextView in it, which needs to grow and shrink dynamically as the user types, as well as the cell growing/shrinking logically with it. I read a bunch of posts on this but I think I am getting thrown because I am using a STATIC table view.

Here is my resizing attempt (its pretty much a total fail):

- (void)textViewDidChange:(UITextView *)textView
{
    self.numberOfLines = (textView.contentSize.height / textView.font.lineHeight) - 1;

    float height = 44.0;
    height += (textView.font.lineHeight * (self.numberOfLines - 1));

    CGRect textViewFrame = [textView frame];
    textViewFrame.size.height = height - 10.0; //The 10 value is to retrieve the same height padding I inputed earlier when I initialized the UITextView
    [textView setFrame:textViewFrame];

    [self.tableView beginUpdates];
    [self.tableView endUpdates];

    [self.messageTextView setContentInset:UIEdgeInsetsZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 44.0;
    if (self.messageTextView) {
        height += (self.messageTextView.font.lineHeight * (self.numberOfLines - 1));
    }
    return height;
}

I'll take any tips! Thanks.

Body:
Your will need to manually calculate new size of you textView, and manually call update for your tableView.

static CGFloat cellHeight = 85;//from story board height to
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 0) {
        return cellHeight + [self appendTextViewNewHeight];
    }
    return cell.bounds.size.height;
}

-(CGFloat) appendTextViewNewHeight {
    return _appendHeightForTextView;
}

static CGFloat textViewHeightStartHeight = 33;//from storiboard height
- (void)textViewDidChange:(UITextView *)textView;
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    if (newFrame.size.height >= textViewHeightStartHeight) {
        CGFloat newAppend = newFrame.size.height - textViewHeightStartHeight;
        if (newAppend != self.appendHeightForTextView) {
            self.appendHeightForTextView = newAppend;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }
    }
}

Also you need to set delegates on storyboards on in the code.
in viedDidLoad you need to do next things:

self.appendHeightForTextView = 0;

And finally set constraints in storyboard for your cell. Do not set bottom constraint of your textView. Only set right, left, and top.