问:
Passing data between Widgets without using Navigator?
I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.

So if there is anyone who can help me I will be very thankful.

Details :

```<code> List<String> _instructions = [];

class Details extends StatefulWidget {
  @override
  _DetailsState createState() => new _DetailsState();
}

class _DetailsState extends State<Details> {
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(3),
                  child: OutlineButton(
                    highlightElevation: 21,
                    color: Colors.white,
                    shape: StadiumBorder(),
                    textColor: Colors.lightBlue,
                    child: Text(
                      'ENVOYER',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        fontStyle: FontStyle.normal,
                        color: Colors.lightBlue,
                      ),
                    ),
                    borderSide: BorderSide(
                        color: Colors.lightBlue,
                        style: BorderStyle.solid,
                        width: 1),
                    onPressed: () {

                    },
                  ),
                ),
              ),
}}
</code>```

so what I want is that,when I press the button I will send my list to the next widget without using navigator.

答:
I think a more appropriate approach should be similar to how android fragments connect to each other using bloc pattern or master-details flow.
I created an example repository to show the complete concept.
In short, the idea is to create a class with StreamController inside. Both widgets will have a reference to bloc instance. When the first widget wants to send data to the second it adds a new item to Stream. The second listen to the stream and updates its content accordingly.

Inside bloc:

```<code>  StreamController<String> _selectedItemController = new BehaviorSubject();

  Stream<String> get selectedItem => _selectedItemController.stream;

  void setSelected(String item) {
    _selectedItemController.add(item);
  }
</code>```

First fragment:

```<code>class FragmentList extends StatelessWidget {
  final Bloc bloc;

  const FragmentList(
    this.bloc, {
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: bloc.selectedItem,
      initialData: "",
      builder: (BuildContext context, AsyncSnapshot<String> screenType) {
        return ListView.builder(
          itemBuilder: (context, index) {
            return ListTile(
              selected: bloc.items[index] == screenType.data,
              title: Text(bloc.items[index]),
              onTap: () {
                bloc.setSelected(bloc.items[index]);
              },
            );
          },
          itemCount: bloc.items.length,
        );
      },
    );
  }
}
</code>```

The second fragment:

```<code>class FragmentDetails extends StatelessWidget {
  final Bloc bloc;

  const FragmentDetails(
    this.bloc, {
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: StreamBuilder(
        initialData: "Nothing selected",
        stream: bloc.selectedItem,
        builder: (BuildContext context, AsyncSnapshot<String> screenType) {
          final info = screenType.data;
          return Text(info);
        },
      ),
    );
  }
}
</code>```

Body:
I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.

So if there is anyone who can help me I will be very thankful.

Details :

 List<String> _instructions = [];

class Details extends StatefulWidget {
  @override
  _DetailsState createState() => new _DetailsState();
}

class _DetailsState extends State {
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(3),
                  child: OutlineButton(
                    highlightElevation: 21,
                    color: Colors.white,
                    shape: StadiumBorder(),
                    textColor: Colors.lightBlue,
                    child: Text(
                      'ENVOYER',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        fontStyle: FontStyle.normal,
                        color: Colors.lightBlue,
                      ),
                    ),
                    borderSide: BorderSide(
                        color: Colors.lightBlue,
                        style: BorderStyle.solid,
                        width: 1),
                    onPressed: () {

                    },
                  ),
                ),
              ),
}}

so what I want is that,when I press the button I will send my list to the next widget without using navigator.

Body:
I think a more appropriate approach should be similar to how android fragments connect to each other using bloc pattern or master-details flow.
I created an example repository to show the complete concept.
In short, the idea is to create a class with StreamController inside. Both widgets will have a reference to bloc instance. When the first widget wants to send data to the second it adds a new item to Stream. The second listen to the stream and updates its content accordingly.

Inside bloc:

  StreamController<String> _selectedItemController = new BehaviorSubject();

  Stream<String> get selectedItem => _selectedItemController.stream;

  void setSelected(String item) {
    _selectedItemController.add(item);
  }

First fragment:

class FragmentList extends StatelessWidget {
  final Bloc bloc;

  const FragmentList(
    this.bloc, {
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: bloc.selectedItem,
      initialData: "",
      builder: (BuildContext context, AsyncSnapshot<String> screenType) {
        return ListView.builder(
          itemBuilder: (context, index) {
            return ListTile(
              selected: bloc.items[index] == screenType.data,
              title: Text(bloc.items[index]),
              onTap: () {
                bloc.setSelected(bloc.items[index]);
              },
            );
          },
          itemCount: bloc.items.length,
        );
      },
    );
  }
}

The second fragment:

class FragmentDetails extends StatelessWidget {
  final Bloc bloc;

  const FragmentDetails(
    this.bloc, {
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: StreamBuilder(
        initialData: "Nothing selected",
        stream: bloc.selectedItem,
        builder: (BuildContext context, AsyncSnapshot<String> screenType) {
          final info = screenType.data;
          return Text(info);
        },
      ),
    );
  }
}


来源: stackexchange

问:
Configuring a single Jenkins job for multiple maven projects
I have 3 library projects based on Maven, A, B, and C.

A

-- B

--  --C

Here C is dependent on both A & B and B is dependent on A.

Now I want to know, how can I configure a Jenkins job in such a way that a single job runs all three projects as per their dependency order?

Things I did: I created 3 Jenkins job and adding a relationship between them as per their build order.

I want a single job to do this. I might be missing something. Any help will be great.

答:
Create a pipeline job with 3 stage can solve it.

```<code>   ....
        stages {
          stage ('build A') {
               (steps in A)
          }
          stage ('build B') {
               (steps in B)
          }
          stage ('build C') {
               (steps in C)
          }
        }
        ...
</code>```

In pipeline each stage depends on the result of previous one. You can print logs at each stage. Hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
Create a pipeline job with 3 stage can solve it.

   ....
        stages {
          stage ('build A') {
               (steps in A)
          }
          stage ('build B') {
               (steps in B)
          }
          stage ('build C') {
               (steps in C)
          }
        }
        ...

In pipeline each stage depends on the result of previous one. You can print logs at each stage. Hope it helps.


问:
Unexpected token function when executing custom Azure DevOps Pipeline Task
The custom Azure pipeline task that has the issue can be found here and has been created by following this tutorial. The task tests are working without any issue, so the task is actually running and calling my external package dependency.

After packaging and publishing the task on the VisualStudio Marketplace and using it in my Azure Devops Release Pipeline (using the default Hosted VS2017 agent) I get the following error output:

```<code>2019-05-28T06:03:34.4430730Z ##[error]Unhandled: Unexpected token function
2019-05-28T06:03:34.4438636Z ##[debug]Processed: ##vso[task.issue type=error;]Unhandled: Unexpected token function
2019-05-28T06:03:34.4439433Z ##[debug]Processed: ##vso[task.complete result=Failed;]Unhandled: Unexpected token function
</code>```

The issue occurs when I call a 3rd-party npm package (like directline-jabber in this case). I suspect the node runtime is not accepting my async / await but when I output the node version on the build agent it outputs v10.15.3.

答: The issue was caused by the package readdirp that heavily relies on the NodeJS filesystem (fs). I expect that those functions fail because they are either not supported or running behind the NodeJS version that is used in their tasks package.

Body:
The custom Azure pipeline task that has the issue can be found here and has been created by following this tutorial. The task tests are working without any issue, so the task is actually running and calling my external package dependency.

After packaging and publishing the task on the VisualStudio Marketplace and using it in my Azure Devops Release Pipeline (using the default Hosted VS2017 agent) I get the following error output:

2019-05-28T06:03:34.4430730Z ##[error]Unhandled: Unexpected token function
2019-05-28T06:03:34.4438636Z ##[debug]Processed: ##vso[task.issue type=error;]Unhandled: Unexpected token function
2019-05-28T06:03:34.4439433Z ##[debug]Processed: ##vso[task.complete result=Failed;]Unhandled: Unexpected token function

The issue occurs when I call a 3rd-party npm package (like directline-jabber in this case). I suspect the node runtime is not accepting my async / await but when I output the node version on the build agent it outputs v10.15.3.


问:
How to fix Refused to display in a frame because it set 'X-Frame-Options' to 'sameorigin
I'm getting an error while using an i-frame in angular. It refused to display in a frame because it set 'X-Frame-Options' to 'sameorigin'

Refused to display 'https://docs.google.com/gview?url=https://subtreebucket.s3.amazonaws.com/docsFile_1559124133664_dummy.pdf' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

答:
How about stripping away the https://docs.google.com/gview?url= part from the src url?

```<code><iframe
  src="https://subtreebucket.s3.amazonaws.com/docsFile_1559124133664_dummy.pdf"
  frameborder="0">
</iframe>
</code>```

It works.

Here's a Working Sample StackBlitz for your ref.

Body:
How about stripping away the https://docs.google.com/gview?url= part from the src url?

<iframe
  src="https://subtreebucket.s3.amazonaws.com/docsFile_1559124133664_dummy.pdf"
  frameborder="0">
</iframe>

It works.

Here's a Working Sample StackBlitz for your ref.


问:
SvcConfigEditor not an option with web.config
When I right click on the web.config file it does not give me the option to edit it in SvcConfigEditor.  yet when I make a class library it does.  Why would this be?  What is the best way to use the editor when my main project has wcf services?</p>

答: You can start service configuration editor from the Tools menu -> WCF Service Configuration Editor.</p>

ContentLicense: CC BY-SA 3.0


问:
JPQL Named query parameter throwing exception with LEFT JOIN queries
I am new to spring data. I have a LEFT Join query using JPQL and am using named query params for the left table, but i get an exception "Parameter with that position [1] did not exist.

I have 2 entities Post and Comments with Many2One relation. I want to get all Post's based on named query params and the latest Comment associated with that Post. Below are the Entities and the JPQL

```<code>@Entity
public class Post{
  @Id
  @GeneratedValue
  private long id;
  private String authorId;
}

@Entity
public class Comment {
  @Id
  @GeneratedValue
  private long id;
  private long creationTime;
  @ManyToOne
  @JoinColumn(name="post_id")
  private Post post;
}

I have scala code for my repository:

@Repository
trait PostRepository extends PagingAndSortingRepository[Post,Long] {

  @Query("SELECT P, COM FROM Post P "
    + "LEFT JOIN FETCH  Comment COM on COM.creationTime = "
    + "(SELECT MAX(COM2.creationTime) from Comment COM2 "
    + "WHERE P.id = COM2.post_id GROUP BY COM2.post_id) "
    + "WHERE P.authorId = :authorId"
  )
  def getPosts(@Param("authorId") authorId:String) : List[Array[Object]]
}
</code>```

If I do not use the named query param, then there is no exception, but as soon I add the  "WHERE P.authorId = :authorId", I get the exception related to the named param. I am unable to figure out the problem.

If JPQL is not the way to go for the query I want, can you please suggest/provide an example of how I can do this using spring data (perhaps Specifications?). I am new to this and so any sample code is greatly appreciated.

```<code>Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

            at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:502) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]

            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_162]

            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_162]

            at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_162]

            at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372) ~[spring-orm-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at com.sun.proxy.$Proxy204.setParameter(Unknown Source) ~[na:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:141) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:101) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:76) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:161) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:152) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:123) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:87) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:492) ~[spring-data-commons-1.13.10.RELEASE.jar!/:na]

            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:475) ~[spring-data-commons-1.13.10.RELEASE.jar!/:na]

            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.10.RELEASE.jar!/:na]

            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            ... 152 common frames omitted
</code>```

答:
You can set the hibernate generation of query log level to FINEST and see the generated SQL. I think there is a problem in the sql that is being generated.

I ran the code in my project and the output query is like this :

```<code>select id, authorId, creationTime from post // creationTime comes from comment but is still generated as belonging to post
</code>```

Maybe this can help you Hibernate show real SQL.

The problem is that you want to retrieve 2 object entities as a response in an object while the good way would be, to retrieve a tuple/ mapEntry or something similar .

```<code>SELECT new java.util.AbstractMap.SimpleEntry(post, comment )
</code>```

Body:
I am new to spring data. I have a LEFT Join query using JPQL and am using named query params for the left table, but i get an exception "Parameter with that position [1] did not exist.

I have 2 entities Post and Comments with Many2One relation. I want to get all Post's based on named query params and the latest Comment associated with that Post. Below are the Entities and the JPQL

@Entity
public class Post{
  @Id
  @GeneratedValue
  private long id;
  private String authorId;
}

@Entity
public class Comment {
  @Id
  @GeneratedValue
  private long id;
  private long creationTime;
  @ManyToOne
  @JoinColumn(name="post_id")
  private Post post;
}

I have scala code for my repository:

@Repository
trait PostRepository extends PagingAndSortingRepository[Post,Long] {

  @Query("SELECT P, COM FROM Post P "
    + "LEFT JOIN FETCH  Comment COM on COM.creationTime = "
    + "(SELECT MAX(COM2.creationTime) from Comment COM2 "
    + "WHERE P.id = COM2.post_id GROUP BY COM2.post_id) "
    + "WHERE P.authorId = :authorId"
  )
  def getPosts(@Param("authorId") authorId:String) : List[Array[Object]]
}

If I do not use the named query param, then there is no exception, but as soon I add the  "WHERE P.authorId = :authorId", I get the exception related to the named param. I am unable to figure out the problem.

If JPQL is not the way to go for the query I want, can you please suggest/provide an example of how I can do this using spring data (perhaps Specifications?). I am new to this and so any sample code is greatly appreciated.

Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

            at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:502) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32) ~[hibernate-entitymanager-5.0.12.Final.jar!/:5.0.12.Final]

            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]

            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_162]

            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_162]

            at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_162]

            at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372) ~[spring-orm-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at com.sun.proxy.$Proxy204.setParameter(Unknown Source) ~[na:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:141) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:101) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:76) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:161) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:152) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:123) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:87) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.10.RELEASE.jar!/:na]

            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:492) ~[spring-data-commons-1.13.10.RELEASE.jar!/:na]

            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:475) ~[spring-data-commons-1.13.10.RELEASE.jar!/:na]

            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.10.RELEASE.jar!/:na]

            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]

            ... 152 common frames omitted

Body:
You can set the hibernate generation of query log level to FINEST and see the generated SQL. I think there is a problem in the sql that is being generated.

I ran the code in my project and the output query is like this :

select id, authorId, creationTime from post // creationTime comes from comment but is still generated as belonging to post

Maybe this can help you Hibernate show real SQL.

The problem is that you want to retrieve 2 object entities as a response in an object while the good way would be, to retrieve a tuple/ mapEntry or something similar .

SELECT new java.util.AbstractMap.SimpleEntry(post, comment )


问:
How desplay the number from the Code in blade Laravel
Show only the variable number in the blade from the $sum value

In Blade:

```<code>{{$sum}}
</code>```

In controller:

```<code>$sum = OrderPosition::select(DB::raw('sum(quantity*product_price) AS total_sales'))->where('quantity', '<>', 1)->get();
</code>```

the output is {"total_sales":"550.00"}

答:
You are trying to display the object. Try this in blade</p>

```<code>{{$sum->total_sales}}
</code>```

Body:
Show only the variable number in the blade from the $sum value

In Blade:

{{$sum}}

In controller:

$sum = OrderPosition::select(DB::raw('sum(quantity*product_price) AS total_sales'))->where('quantity', '<>', 1)->get();

the output is {"total_sales":"550.00"}

Body:
You are trying to display the object. Try this in blade

{{$sum->total_sales}}


答:
You cannot overrule that: as you can see in the response to the GET request for the url you are showing, there is a response header x-frame-options: SAMEORIGIN.

It means that the origin server does not authorize you to show this content inside an iframe.

You cannot circumvent this, this is a security protection: otherwise it would make session hijacking too easy.

The only way to go is to have the same resource with an URL that allows you to be viewed (such as the PDF url directly, here https://subtreebucket.s3.amazonaws.com/docsFile_1559124133664_dummy.pdf, or adding embedded=true to the URL might work, which is google docs specific).

Title: How to fix Refused to display in a frame because it set 'X-Frame-Options' to 'sameorigin

Body:
I'm getting an error while using an i-frame in angular. It refused to display in a frame because it set 'X-Frame-Options' to 'sameorigin'

Refused to display 'https://docs.google.com/gview?url=https://subtreebucket.s3.amazonaws.com/docsFile_1559124133664_dummy.pdf' in a frame because it set 'X-Frame-Options' to 'sameorigin'.


问:
Starting an embedded Cassandra instance for Unit tests
I need to start a Embedded cassandra instance to perform some operations on a Cassandra keyspace via Unit tests. Programming Language is Java. What are the options to start an embedded cassandra?

I used the mojo maven plugin, however after starting the instance using following command, I do not see the cassandra instance started at default port 9042 on localhost.
Plugin:http://www.mojohaus.org/cassandra-maven-plugin/usage.html
Command to start: mvn cassandra:run  -Dcassandra.nativeTransportPort=9042

Is there something missing in terms of usage or do I need to use something different?

Thanks
Jyothi

答:
You can also take a look at https://github.com/nosan/embedded-cassandra/wiki

e.g. If you want to start Cassandra using JUnit4 you can do this in one line:

public class CassandraRuleTests {

    @ClassRule
    public static final CassandraRule cassandra = new CassandraRule(CqlScript.classpath("init.cql"));

    @Test
    public void testMe() {

    }

}

```

Cassandra will be forked as a separate process. You can also set path to JAVA_HOME 8 via javaHome property in case if you use java 9 and higher.

Body:
You can also take a look at https://github.com/nosan/embedded-cassandra/wiki

e.g. If you want to start Cassandra using JUnit4 you can do this in one line:

public class CassandraRuleTests {

    @ClassRule
    public static final CassandraRule cassandra = new CassandraRule(CqlScript.classpath("init.cql"));

    @Test
    public void testMe() {

    }

}

Cassandra will be forked as a separate process. You can also set path to JAVA_HOME 8 via javaHome property in case if you use java 9 and higher.


问:
Is there any standard for the level or depth of JSON?
I usually make deep level JSON, but not sure if this is a good code.

I wrote down my code below.
I usually do this when I need to return value to client.

def nested_dict():
    return defaultdict(nested_dict)

result = defaultdict(nested_dict)
result["a"]["b"]["c"]["d"] = value
```

This comes in handy to make a dict(or JSON) that will be sent to client.

There is no harm to do this and works fine with json.dumps or flask.jsonify.

But it seems not really good to have a deep level of depth in JSON.

Is there any solution or recommended standard?

答: No, there isn't. Also, one can not even say that 4 looks too many in general: if they were three coordinates and some properties of the pointed position at the end (sparse data in 3D), you would not bat an eye.

Body:
I usually make deep level JSON, but not sure if this is a good code.

I wrote down my code below.
I usually do this when I need to return value to client.

def nested_dict():
    return defaultdict(nested_dict)

result = defaultdict(nested_dict)
result["a"]["b"]["c"]["d"] = value

This comes in handy to make a dict(or JSON) that will be sent to client.

There is no harm to do this and works fine with json.dumps or flask.jsonify.

But it seems not really good to have a deep level of depth in JSON.

Is there any solution or recommended standard?


问:
SQL if join doesn't match then join something else
Poorly worded because I'm new to these operations in SQL, suppose I have a table with territories that are eastern and western with another table that has a field called address_state. I want to be able to join on the UCASE of address_state being equal to either the state_abbreviation OR the state_name

EG:

```<code>SELECT orders.total_value, territories.territory FROM orders
INNER JOIN tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.state
OR
tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.name

WHERE UCASE(orders.technical_address_country) = "CANADA"
</code>```

EDIT:

Have come to two possible solutions:

```<code>SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer, tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON
UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
OR
UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
</code>```

OR

```<code>SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.state
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
UNION
SELECT so_order.id, so_order.date_entered,so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered;
</code>```

But they both seem to retrieve different results.

答:
Try this:

```<code>SELECT orders.total_value, territories.territory
    FROM orders AS so_order INNER JOIN tblCanadianTerritories
        ON (
            UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
            OR
            UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
             )
WHERE UCASE(so_order.technical_address_country) = "CANADA"
</code>```

If you want to use a UNION, try this:

```<code>SELECT orders.total_value, territories.territory
    FROM orders AS so_order  INNER JOIN tblCanadianTerritories
        ON UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
WHERE UCASE(so_order.technical_address_country) = "CANADA"
UNION
SELECT orders.total_value, territories.territory
    FROM orders AS so_order  INNER JOIN tblCanadianTerritories
        ON UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
</code>```

Body:
Poorly worded because I'm new to these operations in SQL, suppose I have a table with territories that are eastern and western with another table that has a field called address_state. I want to be able to join on the UCASE of address_state being equal to either the state_abbreviation OR the state_name

EG:

SELECT orders.total_value, territories.territory FROM orders
INNER JOIN tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.state
OR
tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.name

WHERE UCASE(orders.technical_address_country) = "CANADA"

EDIT:

Have come to two possible solutions:

SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer, tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON
UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
OR
UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC

OR

SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.state
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
UNION
SELECT so_order.id, so_order.date_entered,so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered;

But they both seem to retrieve different results.

Body:
Try this:

SELECT orders.total_value, territories.territory
    FROM orders AS so_order INNER JOIN tblCanadianTerritories
        ON (
            UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
            OR
            UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
             )
WHERE UCASE(so_order.technical_address_country) = "CANADA"

If you want to use a UNION, try this:

SELECT orders.total_value, territories.territory
    FROM orders AS so_order  INNER JOIN tblCanadianTerritories
        ON UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
WHERE UCASE(so_order.technical_address_country) = "CANADA"
UNION
SELECT orders.total_value, territories.territory
    FROM orders AS so_order  INNER JOIN tblCanadianTerritories
        ON UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"


问:
Unable to read json files in angular 5?
Hi I am developing web application in Angular 5. I am trying to read json file using http call as below. I am getting 404 error. Below is my service.ts file. Json file also remains in same folder so path may be correct.

```<code> public GetNodes() {
        return this.http.get('./json1.json');
    }
</code>```

Below is my component code.

```<code> ngOnInit() {
        this.nodeservice.GetNodes().subscribe(data =>
            console.log(data)
    );
</code>```

I have done one work around and found my static files supposed to be in assets folder. I moved my json1.json to assets folder and I tried to access. Still I am getting same 404 error. Below is the full path where my json file kept

Projectname\ClientApp\app\components\Utilities

I am using ./json1.json because my service and json files are in the same folder utilities.

Can someone help me to figure it out the issue? Any help would be appreciated. Thank you.

答:
To access any asset data like image or file, you need to put them in assets folder and access it from there as angular loads all the public data from assets folder so any asset will not be accessible from component's folder.

For file './json1.json' the URL will be HOST_Name/json1.json and it won't be there so better to put all files in assets folder and provide path for assets folder.

You can also change assets configuration in "angular.json" to point to your component's folder to access that json file.

Title: Unable to read json files in angular 5?

Body:
Hi I am developing web application in Angular 5. I am trying to read json file using http call as below. I am getting 404 error. Below is my service.ts file. Json file also remains in same folder so path may be correct.

 public GetNodes() {
        return this.http.get('./json1.json');
    }

Below is my component code.

 ngOnInit() {
        this.nodeservice.GetNodes().subscribe(data =>
            console.log(data)
    );

I have done one work around and found my static files supposed to be in assets folder. I moved my json1.json to assets folder and I tried to access. Still I am getting same 404 error. Below is the full path where my json file kept

Projectname\ClientApp\app\components\Utilities

I am using ./json1.json because my service and json files are in the same folder utilities.

Can someone help me to figure it out the issue? Any help would be appreciated. Thank you.


问:
write Data to a file in Formta Form
I have Data which is in this below format in FILE 1

```<code>NAME :  Ram
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14
</code>```

My Desired Output => In this Below Format I needed

I want to Write Data to the FILE 2 in this below Format like

```<code>NAME| AGE
Ram|12
Rahul|13
Raj|14
</code>```

My code :

```<code>head -2 file1.txt | nl | tr '\n' '|' >> file2.txt
</code>```

But my Above Code Prints Only in first Two line in File2.txt

```<code>1 NAME : Ram | 2 AGE : 12|
</code>```

it has to loop until the end and write to file 2

答:
The following script will do what you want</p>

```<code>#!/bin/bash
input="./file1.txt"
evenLine=0

# this will overwrite file2.txt
echo "Name|Age" > file2.txt

# loop over all lines
while IFS= read -r line
do
  if [ 0 -eq $evenLine ]
  then
    # -n to not append newline, remove string "Name: "
    echo -n "$line" | sed -e "s/Name: *//g" >> file2.txt
    evenLine=1
  else
    # replace "Age: " with " | "
    echo "$line" | sed -e "s/Age: */ | /g" >> file2.txt
    evenLine=0
  fi
done < "$input"
</code>```

Title: write Data to a file in Formta Form

Body:
I have Data which is in this below format in FILE 1

NAME :  Ram
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14

My Desired Output => In this Below Format I needed

I want to Write Data to the FILE 2 in this below Format like

NAME| AGE
Ram|12
Rahul|13
Raj|14

My code :

head -2 file1.txt | nl | tr '\n' '|' >> file2.txt

But my Above Code Prints Only in first Two line in File2.txt

1 NAME : Ram | 2 AGE : 12|

it has to loop until the end and write to file 2

Body:
The following script will do what you want

#!/bin/bash
input="./file1.txt"
evenLine=0

# this will overwrite file2.txt
echo "Name|Age" > file2.txt

# loop over all lines
while IFS= read -r line
do
  if [ 0 -eq $evenLine ]
  then
    # -n to not append newline, remove string "Name: "
    echo -n "$line" | sed -e "s/Name: *//g" >> file2.txt
    evenLine=1
  else
    # replace "Age: " with " | "
    echo "$line" | sed -e "s/Age: */ | /g" >> file2.txt
    evenLine=0
  fi
done < "$input"


问:
Using user input to search through a dictionary of various data-types?
I'm trying to take user input and check if it is in a dictionary.
The user is expected to input strings, floats and ints but only strings are comparing properly.

searching for '5' returns works but neither 10 nor 15.0 do as the input is being converted to a string.

other than implementing a check to see force the user to nominate what type of data they are searching for is there a way to do this?

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
print(search_term)
print(type(search_term))
for k,v in new_dict.items():
    print(v)
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)
```

Thanks in advance!!

答:
just convert both variables that you are comparing into string:

```<code>new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    if str(v) == str(search_term):
        do_something = True
        print ('yes')

print(do_something)
</code>```

another solution:

```<code>new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    try:
        search_term = float(search_term)
        v = float(v)
    except:
        pass
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)
</code>```

Body:
I'm trying to take user input and check if it is in a dictionary.
The user is expected to input strings, floats and ints but only strings are comparing properly.

searching for '5' returns works but neither 10 nor 15.0 do as the input is being converted to a string.

other than implementing a check to see force the user to nominate what type of data they are searching for is there a way to do this?

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
print(search_term)
print(type(search_term))
for k,v in new_dict.items():
    print(v)
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)

Thanks in advance!!

Body:
just convert both variables that you are comparing into string:

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    if str(v) == str(search_term):
        do_something = True
        print ('yes')

print(do_something)

another solution:

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    try:
        search_term = float(search_term)
        v = float(v)
    except:
        pass
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)


问:
Kotlin - How do I concatenate a String to an Int value?
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

```<code>for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}
</code>```

Expected Outcome

15 14 13 12 11 10

答:
You should use the $ . You can also use the + but it could get confusing in your case because the + has is also an operator which invokes the plus() method which is used to sum Integers.

```<code>for (i in 15 downTo 10){
  print("$i ");
}
</code>```

Body:
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}

Expected Outcome

15 14 13 12 11 10

Body:
You should use the $ . You can also use the + but it could get confusing in your case because the + has is also an operator which invokes the plus() method which is used to sum Integers.

for (i in 15 downTo 10){
  print("$i ");
}


问:
Overriding touchesBegan: Error - method does not override any method from superclass
I am trying to override touchesBegan in a custom subclass of UITapGestureRecognizer. Code is below. I got it from here: How to accelerate the identification of a single tap over a double tap?. It was the accepted answer, but i am getting an error: method does not override any method from its superclass. I have checked and this indeed seems to be the signature for touchesBegan. Help?</p>

```<code>import UIKit

class UIShortTapGestureRecognizer: UITapGestureRecognizer {
    let tapMaxDelay: Double = 0.3

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        delay(tapMaxDelay) {
        // Enough time has passed and the gesture was not recognized -> It has failed.
            if  self.state != UIGestureRecognizerState.Ended {
                self.state = UIGestureRecognizerState.Failed
            }
        }
    }

}
</code>```

答:
For Swift 4.2 and XCode 10.2 </p>

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

    }
</code>```

Body:
I am trying to override touchesBegan in a custom subclass of UITapGestureRecognizer. Code is below. I got it from here: How to accelerate the identification of a single tap over a double tap?. It was the accepted answer, but i am getting an error: method does not override any method from its superclass. I have checked and this indeed seems to be the signature for touchesBegan. Help?

import UIKit

class UIShortTapGestureRecognizer: UITapGestureRecognizer {
    let tapMaxDelay: Double = 0.3

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        delay(tapMaxDelay) {
        // Enough time has passed and the gesture was not recognized -> It has failed.
            if  self.state != UIGestureRecognizerState.Ended {
                self.state = UIGestureRecognizerState.Failed
            }
        }
    }

}

Body:
For Swift 4.2 and XCode 10.2

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

    }


问:
Developed a small app under winforms can I develop it under linux?
I have developed a small .Net WinForms app on Visual Studio 2017 using C#.
I used Gecko for that project.

It is basically an app that would open a full screen webpage using Gecko web browser object.

Now I want to run the same app, also using Gecko under Linux, hence a simple Gecko web browser object to open up the webpage, embedded into an app under Linux.

My question is how can I achieve this?

Are there any tools to compile the same project for Linux? Or is it better to start from scratch under Linux IDE?
Thanks a lot.

答: There has been a lot of developments with. Net core and Linux check this thread Is it possible to make desktop GUI application in .NET core? </p>


问:
Oracle Query [need subquery?]
assuming I have the following table:

```<code>NUM  TYPE  STAT   ERR
123   10      6    62
123   10      6    62
123   10      6    62
123   17      4     0
321   10      6    62
321   10      6    62
</code>```

I'm currently using the following query:

```<code>select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MIN(ERR) as ERROR
     , MIN(retry) as RETRY
 from TABLE_TB
where ERR=62
group by NUM
having count(ERR) > 1;
</code>```

The output will be:

```<code>NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
321   10      6    62      2
</code>```

That's ok, but what I need is that the query will output only NUM WITH ERR=62 but also with ERR = 0 excluding those who have ERR=62 but without ERR=0. Taking the first table as example, the query should output

```<code>NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
</code>```

This because NUM 123 has ERR=62 (3 occurrency) but also ERR=0. So, NUM 321 will be excluded because even if has ERR=62, it doesn't have ERR=0.

Hope is cliear :)

Thank you very much.
Lucas

答:
You can use a subquery:

```<code>SELECT num
     , MIN(type) AS type
     , MIN(stat) AS status
     , MIN(err) AS err
     , COUNT(*) AS retry
FROM table_tb
WHERE err != 0 AND
      num IN (SELECT num FROM tb WHERE err = 0)
GROUP BY num;
</code>```

or do without a subquery:

```<code>SELECT num
     , MIN(CASE WHEN err != 0 THEN type END) AS type
     , MIN(CASE WHEN err != 0 THEN stat END) AS stat
     , MIN(CASE WHEN err != 0 THEN err END) AS err
     , COUNT(CASE WHEN err != 0 THEN 1 END) AS retry
FROM table_tb
GROUP BY num
HAVING COUNT(DECODE(err, 0, 1)) > 0;
</code>```

Output:

```<code>+-----+------+------+-----+-------+
| NUM | TYPE | STAT | ERR | RETRY |
+-----+------+------+-----+-------+
| 123 |   10 |    6 |  62 |     3 |
+-----+------+------+-----+-------+
</code>```

Title: Oracle Query [need subquery?]

Body:
assuming I have the following table:

NUM  TYPE  STAT   ERR
123   10      6    62
123   10      6    62
123   10      6    62
123   17      4     0
321   10      6    62
321   10      6    62

I'm currently using the following query:

select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MIN(ERR) as ERROR
     , MIN(retry) as RETRY
 from TABLE_TB
where ERR=62
group by NUM
having count(ERR) > 1;

The output will be:

NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
321   10      6    62      2

That's ok, but what I need is that the query will output only NUM WITH ERR=62 but also with ERR = 0 excluding those who have ERR=62 but without ERR=0. Taking the first table as example, the query should output

NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3

This because NUM 123 has ERR=62 (3 occurrency) but also ERR=0. So, NUM 321 will be excluded because even if has ERR=62, it doesn't have ERR=0.

Hope is cliear :)

Thank you very much.
Lucas

Body:
You can use a subquery:

SELECT num
     , MIN(type) AS type
     , MIN(stat) AS status
     , MIN(err) AS err
     , COUNT(*) AS retry
FROM table_tb
WHERE err != 0 AND
      num IN (SELECT num FROM tb WHERE err = 0)
GROUP BY num;

or do without a subquery:

SELECT num
     , MIN(CASE WHEN err != 0 THEN type END) AS type
     , MIN(CASE WHEN err != 0 THEN stat END) AS stat
     , MIN(CASE WHEN err != 0 THEN err END) AS err
     , COUNT(CASE WHEN err != 0 THEN 1 END) AS retry
FROM table_tb
GROUP BY num
HAVING COUNT(DECODE(err, 0, 1)) > 0;

Output:

+-----+------+------+-----+-------+
| NUM | TYPE | STAT | ERR | RETRY |
+-----+------+------+-----+-------+
| 123 |   10 |    6 |  62 |     3 |
+-----+------+------+-----+-------+


问:
storing PDF files in mongoose using Node.js and Angular 6
I have to store large amount of data in mongoose collection and it is getting really big and hard to handle. I want to save PDF files in somewhere and link it in the mongoose collection, I am not really sure for the best solution. Since most links are about direct file upload where as I am using pdfmake library which then stores to collection.

Here is my current model

annual.js

```<code>customerReport: {
    createdBy: String,
    creationDate: String,
    hour: Number,
    waitingHour: Number,
    ccEmails: Array,
    sendToEmail: String,
    pdf: Schema.Types.Mixed,
    customerNotes: String
  },
</code>```

this pdf has whole pdf content inside.

and in my route when I save and store the data finally

```<code>router.post('/stage/complete', (req, res, next) => {
  var completed = new AnnualStage({
    specs: req.body.specs,
    contactDetails: req.body.contactDetails,
    CalculationData: req.body.calculationData,
    customersData req.body.customersData
    customerReport: req.body.customerReport,
  });
  completed
    .save()
    .then(result => {
      res.status(200).json({
        result: result
      });
    })
    .catch(err => {
      res.status(500).json({
        message: err.message
      });
    });
});
</code>```

All the front end is done by Angular 6 and generates all data and pdf and save it to mongo collection

you can see inside I have added GridFs inside the route but where it will store the files and how it will link back to DB?

答:
Disclaimer: This should be a comment but is too long for a comment.

Your code has a really serious flag that it's worth to mention:

You should under no circumstances call fs.readFileSync (or any synchronous method that involes I/O operations) inside an http controller.

This will block all of your users requests until the file has been read.If several users are calling this endpoint at the same time, most of them will get their request delayed for a lot of time.

Instead, you should call fs.readFile. With async/await and util.promisify the code will look almost the same, without blocking the main thread:

```<code>const util = require('util');
const readFile = util.promisify(fs.readFile.bind.fs); // not really sure the bind is really needed tbh, maybe util.promisify(fs.readFile) works too
router.post('/stage/complete', async (req, res, next) => {
  var completed = new AnnualStage({
    specialRequest: req.body.specialRequest,
    contactDetails: req.body.contactDetails,
    requestData: req.body.requestData,
    customerRequests: req.body.customers,
    customerReport: req.body.customerReport,
  });
  completed.customerReport.pdf.data = await readFile(req.body.customerReport);
  completed.customerReport.pdf.contentType = 'application/pdf';
  completed
    .save()
    .then(result => {
      res.status(200).json({
        message: 'Handling POST request to /completed',
        result: result
      });
    })
    .catch(err => {
      res.status(500).json({
        message: err.message
      });
    });
});
</code>```

This change will seriously improve your post handler.

Now, your question. I'm really not sure about what you're asking about. You say:

you can see inside I have added GridFs inside the route but where it will store the files and how it will link back to DB?

There is no reference to gridFs in your code snippets. Maybe you forgot to paste some code? It is not clear now AnnualStage.save() actually saves in mongo. Does it uses gridfs?

It is not clear if your code is not working, or if you're asking about your solution being good enough.

Body:
I have to store large amount of data in mongoose collection and it is getting really big and hard to handle. I want to save PDF files in somewhere and link it in the mongoose collection, I am not really sure for the best solution. Since most links are about direct file upload where as I am using pdfmake library which then stores to collection.

Here is my current model

annual.js

customerReport: {
    createdBy: String,
    creationDate: String,
    hour: Number,
    waitingHour: Number,
    ccEmails: Array,
    sendToEmail: String,
    pdf: Schema.Types.Mixed,
    customerNotes: String
  },

this pdf has whole pdf content inside.

and in my route when I save and store the data finally

router.post('/stage/complete', (req, res, next) => {
  var completed = new AnnualStage({
    specs: req.body.specs,
    contactDetails: req.body.contactDetails,
    CalculationData: req.body.calculationData,
    customersData req.body.customersData
    customerReport: req.body.customerReport,
  });
  completed
    .save()
    .then(result => {
      res.status(200).json({
        result: result
      });
    })
    .catch(err => {
      res.status(500).json({
        message: err.message
      });
    });
});

All the front end is done by Angular 6 and generates all data and pdf and save it to mongo collection

you can see inside I have added GridFs inside the route but where it will store the files and how it will link back to DB?

Body:
Disclaimer: This should be a comment but is too long for a comment.

Your code has a really serious flag that it's worth to mention:

You should under no circumstances call fs.readFileSync (or any synchronous method that involes I/O operations) inside an http controller.

This will block all of your users requests until the file has been read.If several users are calling this endpoint at the same time, most of them will get their request delayed for a lot of time.

Instead, you should call fs.readFile. With async/await and util.promisify the code will look almost the same, without blocking the main thread:

const util = require('util');
const readFile = util.promisify(fs.readFile.bind.fs); // not really sure the bind is really needed tbh, maybe util.promisify(fs.readFile) works too
router.post('/stage/complete', async (req, res, next) => {
  var completed = new AnnualStage({
    specialRequest: req.body.specialRequest,
    contactDetails: req.body.contactDetails,
    requestData: req.body.requestData,
    customerRequests: req.body.customers,
    customerReport: req.body.customerReport,
  });
  completed.customerReport.pdf.data = await readFile(req.body.customerReport);
  completed.customerReport.pdf.contentType = 'application/pdf';
  completed
    .save()
    .then(result => {
      res.status(200).json({
        message: 'Handling POST request to /completed',
        result: result
      });
    })
    .catch(err => {
      res.status(500).json({
        message: err.message
      });
    });
});

This change will seriously improve your post handler.

Now, your question. I'm really not sure about what you're asking about. You say:

you can see inside I have added GridFs inside the route but where it will store the files and how it will link back to DB?

There is no reference to gridFs in your code snippets. Maybe you forgot to paste some code? It is not clear now AnnualStage.save() actually saves in mongo. Does it uses gridfs?

It is not clear if your code is not working, or if you're asking about your solution being good enough.


答: Replacing if v == search_term: with if repr(v) == search_term: works, it will work on '5' as the input, but not on "5" as the input.

Title: Using user input to search through a dictionary of various data-types?


问:
Change tooltip's content to reflect those in html tags
I have the code below. What i want to achieve is when i hover those h1 and p. the contents are output correctly and dynamically to the tooltip(h1 ->This is heading,p -> this is paragraph). Now the tooltip output is fixed to span(id = "tooltip_content")

$(document).ready(function() {
  $('.tooltip').tooltipster();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/themes/tooltipster-light.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/js/jquery.tooltipster.min.js"></script>
<h1 class="tooltip" data-tooltip-content="#tooltip_content">This is a Heading</h1>
<p class="tooltip" data-tooltip-content="#tooltip_content">This is a paragraph.</p>

<div style="display:none" class="tooltip_templates">
  <span id="tooltip_content">
       <strong>This is the content of my tooltip!</strong>
    </span>
</div></code>```

答:
From the tooltipster documentation (5.):

Important: if you have two tooltips that have the same
  data-tooltip-content attribute (that is to say, want to both use the
  same HTML element), please set the contentCloning option to true when
  you initialize your tooltips:

```<code>$('.tooltip').tooltipster({
  contentCloning: true }
);
</code>```

Body:
I have the code below. What i want to achieve is when i hover those h1 and p. the contents are output correctly and dynamically to the tooltip(h1 ->This is heading,p -> this is paragraph). Now the tooltip output is fixed to span(id = "tooltip_content")

$(document).ready(function() {
  $('.tooltip').tooltipster();
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/themes/tooltipster-light.min.css" rel="stylesheet" />

This is a Heading

This is a paragraph.

       This is the content of my tooltip!

Body:
From the tooltipster documentation (5.):

Important: if you have two tooltips that have the same
  data-tooltip-content attribute (that is to say, want to both use the
  same HTML element), please set the contentCloning option to true when
  you initialize your tooltips:

$('.tooltip').tooltipster({
  contentCloning: true }
);


问:
How do I use NSConditionLock? Or NSCondition
I am try to make one function wait for another, and I would like to use NSCondionLock in order to accomplish this. I am not asking for help, but really hoping someone could show me a decent tutorial or example to explain NSConditionLock, or possibly suggest a better method.</p>

答:
Swift 5 version of @vilanovi answer from Playground:

let myCondition = NSCondition()

var someCheckIsTrue = false

func method1() {
    print("STARTING METHOD 1")

    print("WILL LOCK METHOD 1")
    myCondition.lock()
    print("DID LOCK METHOD 1")

    while (!someCheckIsTrue) {
        print("WILL WAIT METHOD 1")
        myCondition.wait()
        print("DID WAIT METHOD 1")
    }

    print("WILL UNLOCK METHOD 1")
    myCondition.unlock()
    print("DID UNLOCK METHOD 1")

    print("ENDING METHOD 1")
}

func method2() {
    print("STARTING METHOD 2")

    print("WILL LOCK METHOD 2")
    myCondition.lock()
    print("DID LOCK METHOD 2")

    someCheckIsTrue = true

    print("WILL SIGNAL METHOD 2")
    myCondition.signal()
    print("DID SIGNAL METHOD 2")

    print("WILL UNLOCK METHOD 2")
    myCondition.unlock()
    print("DID UNLOCK METHOD 2")

    print("ENDING METHOD 2")
}

DispatchQueue.global().async {
    method1()
}

DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.5) {
    method2()
}
```


问:
cURL + PHP: Submitting a form with duplicate forms of the same form names
I am trying to POST to a page that has two forms with duplicate name elements.  The problem is that one form gets the password value and the other form gets the login value. (I can see this by printing out curl_exec($ch);)  I will include my code for the target URL and the formdata.  How do I fix this?

```<code>// my target url and form data
$target = "http://www.example.com/login";
$formdata = "id=$login&password=$password&Submit=Log In";
</code>```

Forms:

```<code><form id="login" name="login" method="post" action="login">

            <label for="id">LOGIN ID</label>  <input type="text" value="" name="id" maxlength="50" size="30"><br>
            <label for="password">Password ID</label>  <input type="password" name="password" maxlength="12" size="30">
            <div align="center"><button class="siteSprite signInSm" value="Log In" name="Submit" type="submit"></button></div>
</form>

<form section="login" id="loginform" name="loginform" action="http://www.example.com/login" method="post">
<input type="text" size="20" value=" Log-in" onfocus="this.value=''" name="id"></td>
<input type="password" value="Password" maxlength="15" size="12" onfocus="this.value=''" name="password">
<input type="submit" class="siteSprite signInSm" value="Sign-In">
</form>
</code>```

答:
You'll have to do something to indicate which of the two forms got submitted. You can either submit a field with the same name but different values in each one, or use the submit button:

```<code><form ...>
    <input type="hidden" name="whichform" value="1" />
    <input type="submit" name="Submit" value="form 1" />
</form>

<form ...>
    <input type="hidden" name="whichform" value="2" />
    <input type="submit" name="Submit" value="form 2" />
</form>
</code>```

and then

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (($_POST['Submit'] == 'form 1') || ($_POST['whichform'] == '1')) {
        .... handle form #1 ....
    }
    if (($_POST['Submit'] == 'form 2') || ($_POST['whichform'] == '2')) {
        .... handle form #1 ....
    }
</code>```

using either method works the same, just pick the one that makes most sense/is easiest and go from there.

Body:
I am trying to POST to a page that has two forms with duplicate name elements.  The problem is that one form gets the password value and the other form gets the login value. (I can see this by printing out curl_exec($ch);)  I will include my code for the target URL and the formdata.  How do I fix this?

// my target url and form data
$target = "http://www.example.com/login";
$formdata = "id=$login&password=$password&Submit=Log In";

Forms:

<form id="login" name="login" method="post" action="login">

            LOGIN ID  <input type="text" value="" name="id" maxlength="50" size="30">

            Password ID  <input type="password" name="password" maxlength="12" size="30">

<button class="siteSprite signInSm" value="Log In" name="Submit" type="submit"></button>

</form>

<form section="login" id="loginform" name="loginform" action="http://www.example.com/login" method="post">
<input type="text" size="20" value=" Log-in" onfocus="this.value=''" name="id">
<input type="password" value="Password" maxlength="15" size="12" onfocus="this.value=''" name="password">
<input type="submit" class="siteSprite signInSm" value="Sign-In">
</form>

Body:
You'll have to do something to indicate which of the two forms got submitted. You can either submit a field with the same name but different values in each one, or use the submit button:

<form ...>
    <input type="hidden" name="whichform" value="1" />
    <input type="submit" name="Submit" value="form 1" />
</form>

<form ...>
    <input type="hidden" name="whichform" value="2" />
    <input type="submit" name="Submit" value="form 2" />
</form>

and then

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (($_POST['Submit'] == 'form 1') || ($_POST['whichform'] == '1')) {
        .... handle form #1 ....
    }
    if (($_POST['Submit'] == 'form 2') || ($_POST['whichform'] == '2')) {
        .... handle form #1 ....
    }

using either method works the same, just pick the one that makes most sense/is easiest and go from there.


问:
Is there a (better) way to find all references to a property setter?
Visual Studio's "Find All References" function works nicely for finding references to a property, and as it happens the "Call Hierarchy" does this too -  it's even better in fact, as it sorts them by calling method.

My problem however is that neither of these methods discriminate between the setter and getter, and so I'm reduced to using find-in-files for "PropertyName =".

That seems like a step backwards (and would obviously not find code using "PropertyName += value" or similar), so I was wondering if I'd missed a simple way of persuading the "Call Hierarchy" function of Visual Studio to work on a property setter or getter specifically?

答:
It is possible in Visual Studio 2019 to sort and filter by "Kind" using the "Find All References" function.
The feature was requested on Microsoft's developercommunity forum

The "references" window with the "Kind" column is displayed to the very right, highlighted by a orange box.


问:
Convert a list of images to grayscale using OpenCV
I have a pickled training dataset containing 32x32 RGB images. As a preprocessing step, I want to convert them to grayscale.
I read in the training dataset as -

```<code>import pickle
import cv2

training_file = "../data/train.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)

X_train, y_train = train['features'], train['labels']
</code>```

Then, I try using a for loop to convert each of the images to grayscale using the following code -

```<code>for i in range(0,len(X_train)-1):
    X_train[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2GRAY)
</code>```

But this throws the following error -

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-a920a94faefc> in <module>()
      1 for i in range(0,len(X_train)-1):
----> 2     X_train[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2GRAY)

ValueError: could not broadcast input array from shape (32,32) into shape (32,32,3)
</code>```

However, if I repeat this procedure using just a single image, I don't get any error. I did the following -

Can someone explain the reason for the error and how I could convert the entire list to grayscale?

答:
Your problem comes from the fact that you're trying to store grayscale images with shape (32, 32) in an array that stores RGB images with shapes (32, 32, 3).

X_train_grayscale = np.zeros(X_train.shape[:-1])
for i in range(X_train.shape[0]):
    X_train_grayscale[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2GRAY)
```

This creates a new array called X_train_grayscale that will contain your grayscale images after converting.

(Of course you need the usual import numpy as np at the top of your Python script to make it work.)

Body:
I have a pickled training dataset containing 32x32 RGB images. As a preprocessing step, I want to convert them to grayscale.
I read in the training dataset as -

import pickle
import cv2

training_file = "../data/train.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)

X_train, y_train = train['features'], train['labels']

Then, I try using a for loop to convert each of the images to grayscale using the following code -

for i in range(0,len(X_train)-1):
    X_train[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2GRAY)

But this throws the following error -

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-a920a94faefc> in <module>()
      1 for i in range(0,len(X_train)-1):
----> 2     X_train[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2GRAY)

ValueError: could not broadcast input array from shape (32,32) into shape (32,32,3)

However, if I repeat this procedure using just a single image, I don't get any error. I did the following -

Can someone explain the reason for the error and how I could convert the entire list to grayscale?

Body:
Your problem comes from the fact that you're trying to store grayscale images with shape (32, 32) in an array that stores RGB images with shapes (32, 32, 3).

X_train_grayscale = np.zeros(X_train.shape[:-1])
for i in range(X_train.shape[0]):
    X_train_grayscale[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2GRAY)

This creates a new array called X_train_grayscale that will contain your grayscale images after converting.

(Of course you need the usual import numpy as np at the top of your Python script to make it work.)


问:
Remove everything after a certain character
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

```<code>/Controller/Action?id=11112&value=4444
</code>```

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

```<code> $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }
</code>```

答:
May be very late party :p

You can use a back reference $'

```<code>$' - Inserts the portion of the string that follows the matched substring.
</code>```

let str = "/Controller/Action?id=11112&value=4444"

let output = str.replace(/\?.*/g,"$'")

console.log(output)```

Body:
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

/Controller/Action?id=11112&value=4444

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }

Body:
May be very late party :p

You can use a back reference $'

$' - Inserts the portion of the string that follows the matched substring.

let str = "/Controller/Action?id=11112&value=4444"

let output = str.replace(/\?.*/g,"$'")

console.log(output)


问:
Authorization Token is not being received by Django server from ios - React native
When I do a request using Fetch (in ios) from a react native app with a Django backend, the header Authorization Token is not being received, but the others headers are.

I try using nc -l 8090 just to check out if the app was correctly sending the header and it was there. Also, this just happens in the ios version, the android one works just fine.

At checking the Django backend, the Authorization Token is not being received ( I printed what i got in the authentication.py file )

I put the fetch code here:

```<code>let response = fetch('http://xxx.xxx.x.xxx:8000/' + 'users', {
      method: 'GET',
      headers: {
        'content-type': 'application/json',
        'x-app-key': xxxxxxxxxx,
        'Authorization': 'Token xxxxxxxxxxxxxxxxxxxx'
      }
    }).then((response) => {...}
</code>```

The error message that im getting in the response is "403 django standar not valid authentication".

I'm not using OAuth2. Any other information that could provide, please let me know and thank you for any help.

Something weird that I just noticed is that when I use the nc cmd (lc -l 8000), at the port 8000, it has the same behavior. The authorization token is not being received.

答:
I solved my problem added a slash at the end of the URL.

let response = fetch('http://xxx.xxx.x.xxx:8000/' + 'users/', {
      method: 'GET',
      headers: {
        'content-type': 'application/json',
        'x-app-key': xxxxxxxxxx,
        'Authorization': 'Token xxxxxxxxxxxxxxxxxxxx'
      }
    }).then((response) => {...}```

Body:
When I do a request using Fetch (in ios) from a react native app with a Django backend, the header Authorization Token is not being received, but the others headers are.

I try using nc -l 8090 just to check out if the app was correctly sending the header and it was there. Also, this just happens in the ios version, the android one works just fine.

At checking the Django backend, the Authorization Token is not being received ( I printed what i got in the authentication.py file )

I put the fetch code here:

let response = fetch('http://xxx.xxx.x.xxx:8000/' + 'users', {
      method: 'GET',
      headers: {
        'content-type': 'application/json',
        'x-app-key': xxxxxxxxxx,
        'Authorization': 'Token xxxxxxxxxxxxxxxxxxxx'
      }
    }).then((response) => {...}

The error message that im getting in the response is "403 django standar not valid authentication".

I'm not using OAuth2. Any other information that could provide, please let me know and thank you for any help.

Something weird that I just noticed is that when I use the nc cmd (lc -l 8000), at the port 8000, it has the same behavior. The authorization token is not being received.


问:
My Effect is called only once when I dispatch multiples
I dispatch a lot of event when I load a set of drones. I would like for each drones loaded, to dispatch connect to a SSE service so I do the following

```<code>      drones.forEach((drone) => {
        console.log('dispatch', drone.id)
        this.store$.dispatch(new UsedDronesStoreActions.OpenUsedDroneUpdatePositionChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      });
</code>```

My effect

```<code>  @Effect()
  startStatusUpdate$ = this.actions$.pipe(
    ofType<featureActions.OpenUsedDroneUpdateStatusChannelRequest>(featureActions.ActionTypes.OpenUsedDroneUpdateStatusChannelRequest),
    concatMap((action) =>
      this.droneDataService.openUsedDroneUpdateStatusChannel(action.payload).pipe(
        map(result => { console.log('there', action.payload.droneId);}),
        catchError((error: HttpErrorResponse) => { }),
      )
    )
  );
</code>```

is called only once

```<code>dispatch id1
dispatch id2
dispatch id3

there id1
===> no more
</code>```

I tried concatMap, and switchMap booth don7t do (concat only show the first value, switch the last)

switchMap do only the last cause he unsubscribe from the previous
concatMap will not subscribe to the other cause the first one isn't completed...

Is there one that subscribe to everyone and watch them one by one separately ?

答:
Aren't you getting any errors in the console? An Effect should always return an Action (unless dispatch: false is being used).

The line

```<code>  map(result => { console.log('there', action.payload.droneId);}),
</code>```

Does not return an action and causes the Effect to be destroyed.

Body:
I dispatch a lot of event when I load a set of drones. I would like for each drones loaded, to dispatch connect to a SSE service so I do the following

      drones.forEach((drone) => {
        console.log('dispatch', drone.id)
        this.store$.dispatch(new UsedDronesStoreActions.OpenUsedDroneUpdatePositionChannelRequest({ droneId: drone.id, projectId : environment.projectId }));
      });

My effect

  @Effect()
  startStatusUpdate$ = this.actions$.pipe(
    ofType<featureActions.OpenUsedDroneUpdateStatusChannelRequest>(featureActions.ActionTypes.OpenUsedDroneUpdateStatusChannelRequest),
    concatMap((action) =>
      this.droneDataService.openUsedDroneUpdateStatusChannel(action.payload).pipe(
        map(result => { console.log('there', action.payload.droneId);}),
        catchError((error: HttpErrorResponse) => { }),
      )
    )
  );

is called only once

dispatch id1
dispatch id2
dispatch id3

there id1
===> no more

I tried concatMap, and switchMap booth don7t do (concat only show the first value, switch the last)

switchMap do only the last cause he unsubscribe from the previous
concatMap will not subscribe to the other cause the first one isn't completed...

Is there one that subscribe to everyone and watch them one by one separately ?

Body:
Aren't you getting any errors in the console? An Effect should always return an Action (unless dispatch: false is being used).

The line

  map(result => { console.log('there', action.payload.droneId);}),

Does not return an action and causes the Effect to be destroyed.


问:
Dotnet upgrade - 2.0 to 3.5 - performance
We have a number of winforms apps that are written in dotnet 2.0.  Are there any performance upgrades that we would expect when taking transistion to 3.5 runtime?  Any particular benefits we will get, besides the language features?</p>

答: I get about a 10x performance increase on a simple app I wrote that makes heavy use of GetPixel() on drawing surfaces.  I can't be sure it was the framework, because the comparison was across two machines, but they were similar. </p>

OwnerDisplayName: mek

OwnerDisplayName: recursive

ContentLicense: CC BY-SA 2.5


问:
Drupal 6 batch not executing
Anyone able to offer some ideas on this? Basically the module I'm building has a form (as per function_email_solicitors_compose), and on submission we obviously route to form_emails_solicitors_compose_submit. Here I define a batch in $batch, and batch_set the aforementioned batch. The drupal documentation says I don't need to run batch_process() if it's called from within a form_submit, which this is, but I've tried with and without. All tests have shown that it gets as far as defining the batch but never goes any further than that. email_solicitors_batch_iteration never runs. Any ideas?

As an additional bit of info, batch_get then returns the following:

```<code>Array
(
    [sets] => Array
        (
            [0] => Array
                (
                    [sandbox] => Array
                        (
                        )

                    [results] => Array
                        (
                        )

                    [success] =>
                    [title] => Emailing.
                    [operations] => Array
                        (
                            [0] => Array
                                (
                                    [0] =>
</code>```

email_solicitors_batch_iteration
                                          [1] => Array
                                              (
                                                  [0] =>
                                                  [1] =>
                                              )

```<code>                                )

                        )

                    [finished] => my_finished_callback
                    [init_message] => Initializing.<br/>
                    [progress_message] => Remaining
</code>```

@remaining of @total.
                          [error_message] => An error has
  occurred.
                          [total] => 1
                      )

```<code>        )

)
</code>```

The code:

```<code>function email_solicitors_compose(){
    $form['email_solicitors_subject'] = array(
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#description' => t('Enter the subject of your email'),
        '#default_value' => 'Subject',
        '#size' => 30
    );
    $form['email_solicitors_message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#description' => t('Write your message here. <strong>Please note that we will automatically add "Dear #name", which will be personalised to the solicitor.</strong>'),
        '#default_value' => '',
    );
    $form['email_solicitors_submit'] = array(
        '#type' => 'submit',
        '#title' => t('Submit'),
        '#description' => t('Sumbit this form.'),
        '#default_value' => 'Submit',
    );
    return $form;
}//function email_solicitors_compose

function email_solicitors_compose_submit($form_state)
{
    $batch = array(
        'title' => t('Sending emails to solicitors'),
        'operations' => array(
            array('email_solicitors_batch_iteration', array())
        ),
        'finished' => 'email_solicitors_batch_finished', //run this when we're finished
        'init_message' => t('Preparing to send emails'), //initialisation message
        'progress_message' => t('Sent @current out of @total messages.'),
        'error_message' => t('Sorry, something went wrong when sending emails.'),
    );// create batch array
    $info=print_r($batch,TRUE);
    drupal_set_message($info);
    batch_set($batch);
    batch_process();
}//function email_solicitors_compose_submit

function email_solicitors_batch_iteration(&$context)
{
    // Initialize sandbox the first time through.
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_user_id'] = 0;
        $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT field_solicitor_email_value) FROM content_type_solicitor'));
    }
    $comment="On item ".$context['sandbox']['progress'];
    drupal_set_message ($comment);
}//function email_solicitors_batch_iteration

function email_solicitors_batch_finished (&$context)
{
    die ('woohoo we finished');
}
</code>```

答:
You do not need to call batch_process(), just batch_set() in a submit callback is everything you need. See for example http://api.worldempire.ch/api/privatemsg/privatemsg_filter--privatemsg_filter.admin.inc/function/privatemsg_filter_inbox_rebuid_form_submit/7-1.

And as Artusamak said, your batch implementation is incomplete and would result in a endless loop.

Title: Drupal 6 batch not executing

Body:
Anyone able to offer some ideas on this? Basically the module I'm building has a form (as per function_email_solicitors_compose), and on submission we obviously route to form_emails_solicitors_compose_submit. Here I define a batch in $batch, and batch_set the aforementioned batch. The drupal documentation says I don't need to run batch_process() if it's called from within a form_submit, which this is, but I've tried with and without. All tests have shown that it gets as far as defining the batch but never goes any further than that. email_solicitors_batch_iteration never runs. Any ideas?

As an additional bit of info, batch_get then returns the following:

Array
(
    [sets] => Array
        (
            [0] => Array
                (
                    [sandbox] => Array
                        (
                        )

                    [results] => Array
                        (
                        )

                    [success] =>
                    [title] => Emailing.
                    [operations] => Array
                        (
                            [0] => Array
                                (
                                    [0] =>

email_solicitors_batch_iteration
                                          [1] => Array
                                              (
                                                  [0] =>
                                                  [1] =>
                                              )

                                )

                        )

                    [finished] => my_finished_callback
                    [init_message] => Initializing.

                    [progress_message] => Remaining

@remaining of @total.
                          [error_message] => An error has
  occurred.
                          [total] => 1
                      )

        )

)

The code:

function email_solicitors_compose(){
    $form['email_solicitors_subject'] = array(
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#description' => t('Enter the subject of your email'),
        '#default_value' => 'Subject',
        '#size' => 30
    );
    $form['email_solicitors_message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#description' => t('Write your message here. Please note that we will automatically add "Dear #name", which will be personalised to the solicitor.'),
        '#default_value' => '',
    );
    $form['email_solicitors_submit'] = array(
        '#type' => 'submit',
        '#title' => t('Submit'),
        '#description' => t('Sumbit this form.'),
        '#default_value' => 'Submit',
    );
    return $form;
}//function email_solicitors_compose

function email_solicitors_compose_submit($form_state)
{
    $batch = array(
        'title' => t('Sending emails to solicitors'),
        'operations' => array(
            array('email_solicitors_batch_iteration', array())
        ),
        'finished' => 'email_solicitors_batch_finished', //run this when we're finished
        'init_message' => t('Preparing to send emails'), //initialisation message
        'progress_message' => t('Sent @current out of @total messages.'),
        'error_message' => t('Sorry, something went wrong when sending emails.'),
    );// create batch array
    $info=print_r($batch,TRUE);
    drupal_set_message($info);
    batch_set($batch);
    batch_process();
}//function email_solicitors_compose_submit

function email_solicitors_batch_iteration(&$context)
{
    // Initialize sandbox the first time through.
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_user_id'] = 0;
        $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT field_solicitor_email_value) FROM content_type_solicitor'));
    }
    $comment="On item ".$context['sandbox']['progress'];
    drupal_set_message ($comment);
}//function email_solicitors_batch_iteration

function email_solicitors_batch_finished (&$context)
{
    die ('woohoo we finished');
}


问:
How to run Scrapy from within a Python script
I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this:

http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/

http://snipplr.com/view/67006/using-scrapy-from-a-script/

I can't figure out where I should put my spider code and how to call it from the main function. Please help. This is the example code:

```<code># This snippet can be used to run scrapy spiders independent of scrapyd or the scrapy command line tool and use it from a script.
#
# The multiprocessing library is used in order to work around a bug in Twisted, in which you cannot restart an already running reactor or in this case a scrapy instance.
#
# [Here](http://groups.google.com/group/scrapy-users/browse_thread/thread/f332fc5b749d401a) is the mailing-list discussion for this snippet.

#!/usr/bin/python
import os
os.environ.setdefault('SCRAPY_SETTINGS_MODULE', 'project.settings') #Must be at the top before other imports

from scrapy import log, signals, project
from scrapy.xlib.pydispatch import dispatcher
from scrapy.conf import settings
from scrapy.crawler import CrawlerProcess
from multiprocessing import Process, Queue

class CrawlerScript():

    def __init__(self):
        self.crawler = CrawlerProcess(settings)
        if not hasattr(project, 'crawler'):
            self.crawler.install()
        self.crawler.configure()
        self.items = []
        dispatcher.connect(self._item_passed, signals.item_passed)

    def _item_passed(self, item):
        self.items.append(item)

    def _crawl(self, queue, spider_name):
        spider = self.crawler.spiders.create(spider_name)
        if spider:
            self.crawler.queue.append_spider(spider)
        self.crawler.start()
        self.crawler.stop()
        queue.put(self.items)

    def crawl(self, spider):
        queue = Queue()
        p = Process(target=self._crawl, args=(queue, spider,))
        p.start()
        p.join()
        return queue.get(True)

# Usage
if __name__ == "__main__":
    log.start()

    """
    This example runs spider1 and then spider2 three times.
    """
    items = list()
    crawler = CrawlerScript()
    items.append(crawler.crawl('spider1'))
    for i in range(3):
        items.append(crawler.crawl('spider2'))
    print items

# Snippet imported from snippets.scrapy.org (which no longer works)
# author: joehillen
# date  : Oct 24, 2010
</code>```

Thank you.

答:
Simply we can use

```<code>from scrapy.crawler import CrawlerProcess
from project.spiders.test_spider import SpiderName

process = CrawlerProcess()
process.crawl(SpiderName, arg1=val1,arg2=val2)
process.start()
</code>```

Use these arguments inside spider __init__ function with the global scope.

Body:
I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this:

http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/

http://snipplr.com/view/67006/using-scrapy-from-a-script/

I can't figure out where I should put my spider code and how to call it from the main function. Please help. This is the example code:

# This snippet can be used to run scrapy spiders independent of scrapyd or the scrapy command line tool and use it from a script.
#
# The multiprocessing library is used in order to work around a bug in Twisted, in which you cannot restart an already running reactor or in this case a scrapy instance.
#
# [Here](http://groups.google.com/group/scrapy-users/browse_thread/thread/f332fc5b749d401a) is the mailing-list discussion for this snippet.

#!/usr/bin/python
import os
os.environ.setdefault('SCRAPY_SETTINGS_MODULE', 'project.settings') #Must be at the top before other imports

from scrapy import log, signals, project
from scrapy.xlib.pydispatch import dispatcher
from scrapy.conf import settings
from scrapy.crawler import CrawlerProcess
from multiprocessing import Process, Queue

class CrawlerScript():

    def __init__(self):
        self.crawler = CrawlerProcess(settings)
        if not hasattr(project, 'crawler'):
            self.crawler.install()
        self.crawler.configure()
        self.items = []
        dispatcher.connect(self._item_passed, signals.item_passed)

    def _item_passed(self, item):
        self.items.append(item)

    def _crawl(self, queue, spider_name):
        spider = self.crawler.spiders.create(spider_name)
        if spider:
            self.crawler.queue.append_spider(spider)
        self.crawler.start()
        self.crawler.stop()
        queue.put(self.items)

    def crawl(self, spider):
        queue = Queue()
        p = Process(target=self._crawl, args=(queue, spider,))
        p.start()
        p.join()
        return queue.get(True)

# Usage
if __name__ == "__main__":
    log.start()

    """
    This example runs spider1 and then spider2 three times.
    """
    items = list()
    crawler = CrawlerScript()
    items.append(crawler.crawl('spider1'))
    for i in range(3):
        items.append(crawler.crawl('spider2'))
    print items

# Snippet imported from snippets.scrapy.org (which no longer works)
# author: joehillen
# date  : Oct 24, 2010

Thank you.

Body:
Simply we can use

from scrapy.crawler import CrawlerProcess
from project.spiders.test_spider import SpiderName

process = CrawlerProcess()
process.crawl(SpiderName, arg1=val1,arg2=val2)
process.start()

Use these arguments inside spider __init__ function with the global scope.