问:
Slick: I have a simple joinLeft going kaboom ... why?
I'm using Slick 3.3.0 to build an application and have the following simple (I believe) use case where there is an Auth2InfoRow and it's dependent Auth2InfoParamRow these are Slick mapped case classes that correspond to the model:

```<code>package com.mohiva.play.silhouette.impl.providers

case class OAuth2Info(
  accessToken: String,
  tokenType: Option[String] = None,
  expiresIn: Option[Int] = None,
  refreshToken: Option[String] = None,
  params: Option[Map[String, String]] = None) extends AuthInfo
</code>```

In essence the query uses Silhouette's LoginInfo to look up the master OAuth2Info including its params which resides in another OAuth2InfoParam detail table.

```<code>import com.mohiva.play.silhouette.api.{ LoginInfo => ExtLoginInfo }
import com.mohiva.play.silhouette.impl.providers.{ OAuth2Info => ExtOAuth2Info }

/**
 * Returns the matching Silhouette [[ExtOAuth2Info]] used for social
 * (e.g. the Facebook) authentication provider given a Silhouette [[ExtLoginInfo]].
 * The [[ExtLoginInfo]] is looked up using the `providerId` and `providerKey` and
 * then the result's `userId` used as look up key.
 *
 * @param extLoginInfo The linked Silhouette login info instance.
 * @return the matching Silhouette [[ExtOAuth2Info]] used for social.
 */
def find(extLoginInfo: ExtLoginInfo): Future[Option[ExtOAuth2Info]] = {
  val action = (for {
    loginInfo <- LoginInfo if loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey
    (oauth2Info, oauth2InfoParam) <- OAuth2Info.filter(_.userId === loginInfo.userId).joinLeft(OAuth2InfoParam).on(_.userId === _.userId)
  } yield (oauth2Info, oauth2InfoParam)).result
  db.run(action).map {
    case results => {
      val params = results.map(_._2).map {
        case Some(param) => Some(param.key -> param.value)
        case _ => None.asInstanceOf[Option[(String, String)]]
      }.filterNot(_.isEmpty).map(_.get) match {
        case seq if (seq.nonEmpty) => Some(seq.toMap)
        case _ => None
      }

      results.headOption.map {
        case (oauth2Info, _) => oauth2Info.toExt(params)
      }
    }
  }
}
</code>```

To break it down, the first part before db.run(action) issues in a single query and looks up for OAuth2Infos and OAuth2InfoParams and if no rows of the later are found then it should be (oauth2Info, None).

The second part after db.run(action) reconstructs a OAuth2Info by collecting the master from the first element and then the details corresponding to the possible params OAuth2InfoParam.

This is what I get:

```<code>play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[SlickTreeException: Unreachable reference to s2 after resolving monadic joins
| Join Inner : Vector[(@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>, (t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>))]
|   left s2: < Table > myappdb.login_info : Vector[@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>]
|   right s15: Join Left : Vector[(t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>)]
|     left s28: Bind : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|       from s30: Filter s31 : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         from s31: Table myappdb.o_auth2_info : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         where: Apply Function = : Boolean
|           0: Path s31.user_id : Long'
|           1: < Path > s2.user_id : Long'
|       select: Pure t17 : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|         value: StructNode : {s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}
|           s18: Path s30.access_token : String'
|           s19: Path s30.expires_in : Option[Int']
|           s20: Path s30.modified : Option[org.joda.time.DateTime']
|           s21: Path s30.token_type : Option[String']
|           s22: Path s30.refresh_token : Option[String']
|           s23: Path s30.user_id : Long'
|     right s29: Bind : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|       from s33: Table myappdb.o_auth2_info_param : Vector[@t34<{user_id: Long', key: String', value: String'}>]
|       select: Pure t24 : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|         value: StructNode : {s25: Long', s26: String', s27: String'}
|           s25: Path s33.user_id : Long'
|           s26: Path s33.key : String'
|           s27: Path s33.value : String'
|     on: Apply Function = : Boolean
|       0: Path s28.s23 : Long'
|       1: Path s29.s25 : Long'
|   on: Apply Function and : Boolean
|     0: Apply Function and : Boolean
|       0: Apply Function = : Boolean
|         0: Path s2.provider_id : String'
|         1: LiteralNode facebook (volatileHint=false) : String'
|       1: Apply Function = : Boolean
|         0: Path s2.provider_key : String'
|         1: LiteralNode 123456789 (volatileHint=false) : String'
|     1: LiteralNode true (volatileHint=false) : Boolean
]]
    at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:351)
    at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:267)
    at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:382)
    at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:380)
    at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:417)
    at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:41)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:64)
    at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
    at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:92)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
Caused by: slick.SlickTreeException: Unreachable reference to s2 after resolving monadic joins
| Join Inner : Vector[(@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>, (t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>))]
|   left s2: < Table > myappdb.login_info : Vector[@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>]
|   right s15: Join Left : Vector[(t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>)]
|     left s28: Bind : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|       from s30: Filter s31 : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         from s31: Table myappdb.o_auth2_info : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         where: Apply Function = : Boolean
|           0: Path s31.user_id : Long'
|           1: < Path > s2.user_id : Long'
|       select: Pure t17 : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|         value: StructNode : {s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}
|           s18: Path s30.access_token : String'
|           s19: Path s30.expires_in : Option[Int']
|           s20: Path s30.modified : Option[org.joda.time.DateTime']
|           s21: Path s30.token_type : Option[String']
|           s22: Path s30.refresh_token : Option[String']
|           s23: Path s30.user_id : Long'
|     right s29: Bind : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|       from s33: Table myappdb.o_auth2_info_param : Vector[@t34<{user_id: Long', key: String', value: String'}>]
|       select: Pure t24 : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|         value: StructNode : {s25: Long', s26: String', s27: String'}
|           s25: Path s33.user_id : Long'
|           s26: Path s33.key : String'
|           s27: Path s33.value : String'
|     on: Apply Function = : Boolean
|       0: Path s28.s23 : Long'
|       1: Path s29.s25 : Long'
|   on: Apply Function and : Boolean
|     0: Apply Function and : Boolean
|       0: Apply Function = : Boolean
|         0: Path s2.provider_id : String'
|         1: LiteralNode facebook (volatileHint=false) : String'
|       1: Apply Function = : Boolean
|         0: Path s2.provider_key : String'
|         1: LiteralNode 123456789 (volatileHint=false) : String'
|     1: LiteralNode true (volatileHint=false) : Boolean

    at slick.compiler.VerifySymbols.verifyScoping$1(VerifySymbols.scala:17)
    at slick.compiler.VerifySymbols.$anonfun$apply$6(VerifySymbols.scala:38)
    at slick.compiler.VerifySymbols.$anonfun$apply$6$adapted(VerifySymbols.scala:38)
    at slick.util.ConstArray.foreach(ConstArray.scala:29)
    at slick.ast.Node.childrenForeach(Node.scala:59)
    at slick.ast.Node.childrenForeach$(Node.scala:58)
    at slick.ast.Apply.childrenForeach(Node.scala:546)
    at slick.compiler.VerifySymbols.verifyScoping$1(VerifySymbols.scala:38)
    at slick.compiler.VerifySymbols.$anonfun$apply$5(VerifySymbols.scala:29)
    at slick.compiler.VerifySymbols.$anonfun$apply$5$adapted(VerifySymbols.scala:29)
</code>```

PS: Slick is like this mean girlfriend that treats you horribly but you love her anyways :D

答:
Ok thanks to @Dmytro Mitin comments and the workarounds proposed in https://github.com/slick/slick/issues/1316 I tried couple of variantions until found this one that worked, basically doing the left join on the first enumerator:</p>

```<code>def find(extLoginInfo: ExtLoginInfo): Future[Option[ExtOAuth2Info]] = {
    val action = (for {
        (loginInfo, oauth2InfoParam) <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey ===   extLoginInfo.providerKey }.joinLeft(OAuth2InfoParam).on(_.userId === _.userId)
        oauth2Info <- OAuth2Info.filter(_.userId === loginInfo.userId)
    } yield (oauth2Info, oauth2InfoParam)).result
    db.run(action).map {
        case results => {
        val params = results.map(_._2).map {
            case Some(param) => Some(param.key -> param.value)
            case _ => None.asInstanceOf[Option[(String, String)]]
        }.filterNot(_.isEmpty).map(_.get) match {
            case seq if (seq.nonEmpty) => Some(seq.toMap)
            case _ => None
        }

        results.headOption.map {
            case (oauth2Info, _) => oauth2Info.toExt(params)
        }
    }
}
</code>```

Body:
I'm using Slick 3.3.0 to build an application and have the following simple (I believe) use case where there is an Auth2InfoRow and it's dependent Auth2InfoParamRow these are Slick mapped case classes that correspond to the model:

package com.mohiva.play.silhouette.impl.providers

case class OAuth2Info(
  accessToken: String,
  tokenType: Option[String] = None,
  expiresIn: Option[Int] = None,
  refreshToken: Option[String] = None,
  params: Option[Map[String, String]] = None) extends AuthInfo

In essence the query uses Silhouette's LoginInfo to look up the master OAuth2Info including its params which resides in another OAuth2InfoParam detail table.

import com.mohiva.play.silhouette.api.{ LoginInfo => ExtLoginInfo }
import com.mohiva.play.silhouette.impl.providers.{ OAuth2Info => ExtOAuth2Info }

/**
 * Returns the matching Silhouette [[ExtOAuth2Info]] used for social
 * (e.g. the Facebook) authentication provider given a Silhouette [[ExtLoginInfo]].
 * The [[ExtLoginInfo]] is looked up using the `providerId` and `providerKey` and
 * then the result's `userId` used as look up key.
 *
 * @param extLoginInfo The linked Silhouette login info instance.
 * @return the matching Silhouette [[ExtOAuth2Info]] used for social.
 */
def find(extLoginInfo: ExtLoginInfo): Future[Option[ExtOAuth2Info]] = {
  val action = (for {
    loginInfo <- LoginInfo if loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey
    (oauth2Info, oauth2InfoParam) <- OAuth2Info.filter(_.userId === loginInfo.userId).joinLeft(OAuth2InfoParam).on(_.userId === _.userId)
  } yield (oauth2Info, oauth2InfoParam)).result
  db.run(action).map {
    case results => {
      val params = results.map(_._2).map {
        case Some(param) => Some(param.key -> param.value)
        case _ => None.asInstanceOf[Option[(String, String)]]
      }.filterNot(_.isEmpty).map(_.get) match {
        case seq if (seq.nonEmpty) => Some(seq.toMap)
        case _ => None
      }

      results.headOption.map {
        case (oauth2Info, _) => oauth2Info.toExt(params)
      }
    }
  }
}

To break it down, the first part before db.run(action) issues in a single query and looks up for OAuth2Infos and OAuth2InfoParams and if no rows of the later are found then it should be (oauth2Info, None).

The second part after db.run(action) reconstructs a OAuth2Info by collecting the master from the first element and then the details corresponding to the possible params OAuth2InfoParam.

This is what I get:

play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[SlickTreeException: Unreachable reference to s2 after resolving monadic joins
| Join Inner : Vector[(@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>, (t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>))]
|   left s2:
 myappdb.login_info : Vector[@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>]
|   right s15: Join Left : Vector[(t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>)]
|     left s28: Bind : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|       from s30: Filter s31 : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         from s31: Table myappdb.o_auth2_info : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         where: Apply Function = : Boolean
|           0: Path s31.user_id : Long'
|           1: < Path > s2.user_id : Long'
|       select: Pure t17 : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|         value: StructNode : {s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}
|           s18: Path s30.access_token : String'
|           s19: Path s30.expires_in : Option[Int']
|           s20: Path s30.modified : Option[org.joda.time.DateTime']
|           s21: Path s30.token_type : Option[String']
|           s22: Path s30.refresh_token : Option[String']
|           s23: Path s30.user_id : Long'
|     right s29: Bind : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|       from s33: Table myappdb.o_auth2_info_param : Vector[@t34<{user_id: Long', key: String', value: String'}>]
|       select: Pure t24 : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|         value: StructNode : {s25: Long', s26: String', s27: String'}
|           s25: Path s33.user_id : Long'
|           s26: Path s33.key : String'
|           s27: Path s33.value : String'
|     on: Apply Function = : Boolean
|       0: Path s28.s23 : Long'
|       1: Path s29.s25 : Long'
|   on: Apply Function and : Boolean
|     0: Apply Function and : Boolean
|       0: Apply Function = : Boolean
|         0: Path s2.provider_id : String'
|         1: LiteralNode facebook (volatileHint=false) : String'
|       1: Apply Function = : Boolean
|         0: Path s2.provider_key : String'
|         1: LiteralNode 123456789 (volatileHint=false) : String'
|     1: LiteralNode true (volatileHint=false) : Boolean
]]
    at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:351)
    at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:267)
    at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:382)
    at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:380)
    at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:417)
    at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:41)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:64)
    at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
    at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:92)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
Caused by: slick.SlickTreeException: Unreachable reference to s2 after resolving monadic joins
| Join Inner : Vector[(@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>, (t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>))]
|   left s2:
 myappdb.login_info : Vector[@t16<{user_id: Long', provider_id: String', provider_key: String', modified: Option[org.joda.time.DateTime']}>]
|   right s15: Join Left : Vector[(t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>, t24<{s25: Long', s26: String', s27: String'}>)]
|     left s28: Bind : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|       from s30: Filter s31 : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         from s31: Table myappdb.o_auth2_info : Vector[@t32<{access_token: String', expires_in: Option[Int'], modified: Option[org.joda.time.DateTime'], token_type: Option[String'], refresh_token: Option[String'], user_id: Long'}>]
|         where: Apply Function = : Boolean
|           0: Path s31.user_id : Long'
|           1: < Path > s2.user_id : Long'
|       select: Pure t17 : Vector[t17<{s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}>]
|         value: StructNode : {s18: String', s19: Option[Int'], s20: Option[org.joda.time.DateTime'], s21: Option[String'], s22: Option[String'], s23: Long'}
|           s18: Path s30.access_token : String'
|           s19: Path s30.expires_in : Option[Int']
|           s20: Path s30.modified : Option[org.joda.time.DateTime']
|           s21: Path s30.token_type : Option[String']
|           s22: Path s30.refresh_token : Option[String']
|           s23: Path s30.user_id : Long'
|     right s29: Bind : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|       from s33: Table myappdb.o_auth2_info_param : Vector[@t34<{user_id: Long', key: String', value: String'}>]
|       select: Pure t24 : Vector[t24<{s25: Long', s26: String', s27: String'}>]
|         value: StructNode : {s25: Long', s26: String', s27: String'}
|           s25: Path s33.user_id : Long'
|           s26: Path s33.key : String'
|           s27: Path s33.value : String'
|     on: Apply Function = : Boolean
|       0: Path s28.s23 : Long'
|       1: Path s29.s25 : Long'
|   on: Apply Function and : Boolean
|     0: Apply Function and : Boolean
|       0: Apply Function = : Boolean
|         0: Path s2.provider_id : String'
|         1: LiteralNode facebook (volatileHint=false) : String'
|       1: Apply Function = : Boolean
|         0: Path s2.provider_key : String'
|         1: LiteralNode 123456789 (volatileHint=false) : String'
|     1: LiteralNode true (volatileHint=false) : Boolean

    at slick.compiler.VerifySymbols.verifyScoping$1(VerifySymbols.scala:17)
    at slick.compiler.VerifySymbols.$anonfun$apply$6(VerifySymbols.scala:38)
    at slick.compiler.VerifySymbols.$anonfun$apply$6$adapted(VerifySymbols.scala:38)
    at slick.util.ConstArray.foreach(ConstArray.scala:29)
    at slick.ast.Node.childrenForeach(Node.scala:59)
    at slick.ast.Node.childrenForeach$(Node.scala:58)
    at slick.ast.Apply.childrenForeach(Node.scala:546)
    at slick.compiler.VerifySymbols.verifyScoping$1(VerifySymbols.scala:38)
    at slick.compiler.VerifySymbols.$anonfun$apply$5(VerifySymbols.scala:29)
    at slick.compiler.VerifySymbols.$anonfun$apply$5$adapted(VerifySymbols.scala:29)

PS: Slick is like this mean girlfriend that treats you horribly but you love her anyways :D

Body:
Ok thanks to @Dmytro Mitin comments and the workarounds proposed in https://github.com/slick/slick/issues/1316 I tried couple of variantions until found this one that worked, basically doing the left join on the first enumerator:

def find(extLoginInfo: ExtLoginInfo): Future[Option[ExtOAuth2Info]] = {
    val action = (for {
        (loginInfo, oauth2InfoParam) <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey ===   extLoginInfo.providerKey }.joinLeft(OAuth2InfoParam).on(_.userId === _.userId)
        oauth2Info <- OAuth2Info.filter(_.userId === loginInfo.userId)
    } yield (oauth2Info, oauth2InfoParam)).result
    db.run(action).map {
        case results => {
        val params = results.map(_._2).map {
            case Some(param) => Some(param.key -> param.value)
            case _ => None.asInstanceOf[Option[(String, String)]]
        }.filterNot(_.isEmpty).map(_.get) match {
            case seq if (seq.nonEmpty) => Some(seq.toMap)
            case _ => None
        }

        results.headOption.map {
            case (oauth2Info, _) => oauth2Info.toExt(params)
        }
    }
}


来源: stackexchange

问:
class or interface expected error for service declaration in manifest file
I have tried all solution on stack but nothing worked for this problem

Manifest file

```<code>  <application
   android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="Screen"
    android:theme="@style/AppTheme">
    <service
        android:name=".LocalService"
        android:enabled="true"
        android:exported="true"></service>

    <activity
        android:name=".MainActivity"
        android:configChanges="orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait"></activity>
    </application>
</code>```

MainActivity where service is called

```<code>    startService(new Intent(this,LocalService.class));
</code>```

Service class

```<code>     public class LocalService extends Service {
      public LocalService() {
      }

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}
 }
</code>```

答:
remove ' in your code</p>

```<code><application
   android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="Screen"
    android:theme="@style/AppTheme">
    <service
        android:name=".LocalService"
        android:enabled="true"
        android:exported="true"></service>

    <activity
        android:name=".MainActivity"
        android:configChanges="orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait"></activity>
    </application>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have tried all solution on stack but nothing worked for this problem

Manifest file

  <application
   android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="Screen"
    android:theme="@style/AppTheme">
    <service
        android:name=".LocalService"
        android:enabled="true"
        android:exported="true"></service>

    <activity
        android:name=".MainActivity"
        android:configChanges="orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait"></activity>
    </application>

MainActivity where service is called

    startService(new Intent(this,LocalService.class));

Service class

     public class LocalService extends Service {
      public LocalService() {
      }

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}
 }

Body:
remove ' in your code

<application
   android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="Screen"
    android:theme="@style/AppTheme">
    <service
        android:name=".LocalService"
        android:enabled="true"
        android:exported="true"></service>

    <activity
        android:name=".MainActivity"
        android:configChanges="orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait"></activity>
    </application>


问:
Error Adding Angular Material to Existing Angular 7 App
I am attempting to add Angular Material to my existing Angular 7 app so that I can use the MatDialogModule.  I keep getting the following error:

WARNING in ./node_modules/@angular/cdk/esm5/a11y.es5.js
  2324:55-73 export 'ɵɵdefineInjectable' was not found in '@angular/core'

Below are the relevant portions of my app.module.ts and package.json

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MatDialogModule } from '@angular/material/dialog';

 ...

@NgModule({

  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    [BrowserAnimationsModule],
    MatDialogModule,
  ],

```json

  "dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/material": "^8.0.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "hammerjs": "^2.0.8",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.5",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
```

答:
Delete your ./nodule_modules folder and run</p>

```<code> npm init
</code>```

Body:
I am attempting to add Angular Material to my existing Angular 7 app so that I can use the MatDialogModule.  I keep getting the following error:

WARNING in ./node_modules/@angular/cdk/esm5/a11y.es5.js
  2324:55-73 export 'ɵɵdefineInjectable' was not found in '@angular/core'

Below are the relevant portions of my app.module.ts and package.json

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MatDialogModule } from '@angular/material/dialog';

 ...

@NgModule({

  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    [BrowserAnimationsModule],
    MatDialogModule,
  ],

```json

  "dependencies": {
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/material": "^8.0.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "hammerjs": "^2.0.8",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.5",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }

Body:
Delete your ./nodule_modules folder and run

 npm init


问:
iOS: isMovingToParentViewController is not working as expected
My setup is simple, and my issue is not very different from this one. However to better explain it I have posted it here:

```<code>NavController -> VC1 -> VC2
</code>```

VC1 is root view controller of NavController.
VC2 is accessible via Push segue from VC1.

I want to detect, within VC1, whether:

It appeared directly as root view controller (via Push)
It appeared as a result of VC2 being popped

I read the docs which says following should tell me if later is true.

```<code>isMovingToParentViewController == NO
</code>```

However that is not the case, and above condition ALWAYS turns out to be TRUE.
Which means that, (self.isMovingToParentViewController == NO) is always happening.

Here is my code:

```<code>- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;

    //pushed to stack
    if (self.isMovingToParentViewController == YES)
    {
        //First time
      }
    else
    //popped off
    {
        //via Pop from VC2
    }
}
</code>```

Same is the case for viewDidAppear, too.

For a matter of fact check, I put breakpoint at the start, and checked that all of the following are FALSE, in both cases:

```<code>([self isMovingFromParentViewController])
([self isMovingToParentViewController])
([self isBeingPresented])
([self isBeingDismissed])
</code>```

What is happening?
Is there anything I goofed up in my storyboard?
Please help...

答: You have to check isMovingFromParentViewController in VC2’s viewWillDissapear and call a delegate method implemented in VC1. I.e. VC2 is being removed from its parent nav controller because of being popped.</p>

ContentLicense: CC BY-SA 3.0

Body:
My setup is simple, and my issue is not very different from this one. However to better explain it I have posted it here:

NavController -> VC1 -> VC2

VC1 is root view controller of NavController.
VC2 is accessible via Push segue from VC1.

I want to detect, within VC1, whether:

It appeared directly as root view controller (via Push)
It appeared as a result of VC2 being popped

I read the docs which says following should tell me if later is true.

isMovingToParentViewController == NO

However that is not the case, and above condition ALWAYS turns out to be TRUE.
Which means that, (self.isMovingToParentViewController == NO) is always happening.

Here is my code:

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;

    //pushed to stack
    if (self.isMovingToParentViewController == YES)
    {
        //First time
      }
    else
    //popped off
    {
        //via Pop from VC2
    }
}

Same is the case for viewDidAppear, too.

For a matter of fact check, I put breakpoint at the start, and checked that all of the following are FALSE, in both cases:

([self isMovingFromParentViewController])
([self isMovingToParentViewController])
([self isBeingPresented])
([self isBeingDismissed])

What is happening?
Is there anything I goofed up in my storyboard?
Please help...


问:
Delay triggers wrong element to click
I have an example where button named both exclusively triggers a click of two separate elements (first and second buttons). Under normal circumstances each of the element listeners is triggered correctly, but when there is any kind of delay (for example an AJAX call) added to the listener function, the second element is triggered twice, even though there is an explicit trigger by id to call first and then second.

In the example click button named both and see that only second button is triggered twice.

$('#buttons').on('click', '.allow', function() {
  id = $(this).attr('id');
  setTimeout(function() {
    console.log(id);
  }, 2000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  first = $('#first');
  second = $('#second');

  first.addClass('allow');
  first.click();
  first.removeClass('allow');

  second.addClass('allow');
  second.click();
  second.removeClass('allow');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="buttons" style="display:inline-block;">
  <button id="first">FIRST</button>
  <button id="second">SECOND</button>
</div>
<button id="both">BOTH</button><br>
<div id="result"></div></code>```

JSFIDDLE: https://jsfiddle.net/126zkugo/8/

答:
You overwriting your id because its updated by the same function call.
You could save them in an ids array or use let.

var ids = [];

$('#buttons').on('click', '.allow', function() {
  console.log('clicked', $(this));
  ids.push($(this).attr('id'));
  setTimeout(function() {
    console.log(ids);
  }, 1000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  first = $('#first');
  second = $('#second');

  first.addClass('allow');
  first.click();
  first.removeClass('allow');

  second.addClass('allow');
  second.click();
  second.removeClass('allow');
}
```

Title: Delay triggers wrong element to click

Body:
I have an example where button named both exclusively triggers a click of two separate elements (first and second buttons). Under normal circumstances each of the element listeners is triggered correctly, but when there is any kind of delay (for example an AJAX call) added to the listener function, the second element is triggered twice, even though there is an explicit trigger by id to call first and then second.

In the example click button named both and see that only second button is triggered twice.

$('#buttons').on('click', '.allow', function() {
  id = $(this).attr('id');
  setTimeout(function() {
    console.log(id);
  }, 2000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  first = $('#first');
  second = $('#second');

  first.addClass('allow');
  first.click();
  first.removeClass('allow');

  second.addClass('allow');
  second.click();
  second.removeClass('allow');
}

  <button id="first">FIRST</button>
  <button id="second">SECOND</button>

<button id="both">BOTH</button>

JSFIDDLE: https://jsfiddle.net/126zkugo/8/


问:
Is there a way to move a channel to a category based of category name using a custom bot
I am new to to Discord.Net API and got quite a hang of it. But i am having issues moving a channel created by a bot, to an existing category channel. If i can just use the channel ID that would be ok, but ideal it would find a category named 'user-reports' and get the ID from that to set the channel parent or position.

//This is what i have to create a channel for testing purposes
var test = await Context.Guild.CreateTextChannelAsync("HI");

//I used this previously to find if a message was sent in a specific channel then it would act
 if (Context.Channel.Name != "report-user")
            {
                await Context.User.SendMessageAsync(Context.User + " You have tried to send a ticket to the wrong channel. Please use the report-user channel");
                return;
            }
```

答:
<pre class="lang-cs prettyprint-override"><code>    //Find the ID for the desired category
    var categoryId = Context.Guild.CategoryChannels.FirstOrDefault(category => category.Name.Equals("user-reports"))?.Id;

    //Set channel category during channel creation
    await Context.Guild.CreateTextChannelAsync("Hi", prop => prop.CategoryId = categoryId);

    //Set channel category after channel creation
    var channel = await Context.Guild.CreateTextChannelAsync("Hello");
    await channel.ModifyAsync(prop => prop.CategoryId = categoryId);
</code>```


问:
multiple buttons on a form
I have a clear button that I want to tie into some php coding. how do I detect if the clear button is pressed. When the user press clear, i'm going to have it update a sql table to clear out entries. but first I need to know when the button is pressed.</p>

```<code><input name="Reset1" type="reset" value="clear" />
</code>```

答:
```<code><form action="" method="post" >

    <input type="submit" name="btn_submit" value="Button 1" />
    <input type="submit" name="btn_submit" value="Button 2" />
    <input type="submit" name="btn_submit" value="Button 3" />
<form>
</code>```

The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE ,you can use $_POST instead as the form's method is POST

```<code><?php

    if (isset($_REQUEST['btn_submit'])) {

        switch ($_REQUEST['btn_submit']) {
           case "Button 1":
                 echo "You pressed Button 1";
                 break;
           case "Button 2":
                 print "You pressed Button 2";
                 break;
           case "Button 3":
                 print "You pressed Button 3";
                 break;
        }
    }
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: multiple buttons on a form

Body:
I have a clear button that I want to tie into some php coding. how do I detect if the clear button is pressed. When the user press clear, i'm going to have it update a sql table to clear out entries. but first I need to know when the button is pressed.

<input name="Reset1" type="reset" value="clear" />

Body:
<form action="" method="post" >

    <input type="submit" name="btn_submit" value="Button 1" />
    <input type="submit" name="btn_submit" value="Button 2" />
    <input type="submit" name="btn_submit" value="Button 3" />
<form>

The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE ,you can use $_POST instead as the form's method is POST

<?php

    if (isset($_REQUEST['btn_submit'])) {

        switch ($_REQUEST['btn_submit']) {
           case "Button 1":
                 echo "You pressed Button 1";
                 break;
           case "Button 2":
                 print "You pressed Button 2";
                 break;
           case "Button 3":
                 print "You pressed Button 3";
                 break;
        }
    }
?>


问:
Scala list with same adjacent values
I have this list:

```<code>List("Black","Black","Green","White")
</code>```

How can I check if a list has two adjacent values which are the same? Like so:

```<code>List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false
</code>```

答:
In addition to Valy Dia's solution, you can also write:

```<code>list.sliding(2).exists(_.distinct.size == 1)
</code>```

REPL Session

```<code>scala> def check[A](l: Seq[A]): Boolean = l.sliding(2).exists(_.distinct.size == 1)
check: [A](l: Seq[A])Boolean

scala> check("A" :: "B" :: Nil)
res0: Boolean = false

scala> check("A" :: "B" :: "B" ::Nil)
res1: Boolean = true

scala> check("A" :: "B" :: "C":: "B" ::Nil)
res2: Boolean = false
</code>```

Title: Scala list with same adjacent values

Body:
I have this list:

List("Black","Black","Green","White")

How can I check if a list has two adjacent values which are the same? Like so:

List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false

Body:
In addition to Valy Dia's solution, you can also write:

list.sliding(2).exists(_.distinct.size == 1)

REPL Session

scala> def check[A](l: Seq[A]): Boolean = l.sliding(2).exists(_.distinct.size == 1)
check: [A](l: Seq[A])Boolean

scala> check("A" :: "B" :: Nil)
res0: Boolean = false

scala> check("A" :: "B" :: "B" ::Nil)
res1: Boolean = true

scala> check("A" :: "B" :: "C":: "B" ::Nil)
res2: Boolean = false


问:
How to toggle mat-sidenav in another component?
I want to toggle side-nav(in the drawer component)by clicking menu icon (in the header component). I've tried using service; but the service state didn't share between these two components.

The demo is here https://stackblitz.com/edit/angular-11pdkj

答:
I solved this problem by not setting the sidenav in the service but turning the service into a notifier when the sidenav needs to toggle. So when you click the button the service tells a behaviour subject to emit it's change to the DrawerComponent. This component subscribes to the behaviour subject in the ngOnInit. And toggles the sidenav when the service notifies the component of the toggle.

The following StackBlitz shows how I fixed your code: https://stackblitz.com/edit/angular-mgm4xn


问:
unable to use custom cell
I am not able to make out whatrs wrong with this piece of code all I am trying to do is use custom table cell 'AlertCell' when device is in portrait mode and 'AlertCellLandScape' if device is in 'landscape' mode.

its saying cell is undeclared and inside the condition check its saying unused cell

```<code>static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell;

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
}

if (cell == nil) {
   // cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (isPortraitMode) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }
    else {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }
}
</code>```

Please shed some light on this.

Thanks in advance

答:
You could do this instead, you have issues with how you declared the types of the cell, but this should work unless you are accessing the cell-reference outside if-else portrait block.</p>

```<code>static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";

if (isPortraitMode) {
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

    if (cell == nil) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }

    return cell;

} else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

    if (cell == nil) {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }

    return cell;
}
</code>```

Title: unable to use custom cell

Body:
I am not able to make out whatrs wrong with this piece of code all I am trying to do is use custom table cell 'AlertCell' when device is in portrait mode and 'AlertCellLandScape' if device is in 'landscape' mode.

its saying cell is undeclared and inside the condition check its saying unused cell

static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell;

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
}

if (cell == nil) {
   // cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (isPortraitMode) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }
    else {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }
}

Please shed some light on this.

Thanks in advance

Body:
You could do this instead, you have issues with how you declared the types of the cell, but this should work unless you are accessing the cell-reference outside if-else portrait block.

static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";

if (isPortraitMode) {
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

    if (cell == nil) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }

    return cell;

} else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

    if (cell == nil) {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }

    return cell;
}


问:
Apply CSS when all dropdown is changed Jquery
I have to apply some css when all dropdown is changed. Please help me with this.

$("select").change(function() {
  alert('test');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="company1" class="dropdown">
  <option value="1">Group 1</option>
  <option value="2">Group 2</option>
</select>
<select name="company2" class="dropdown">
  <option value="1">Group 1</option>
  <option value="2">Group 2</option>
</select>
<select name="company3" class="dropdown">
  <option value="1">Group 1</option>
  <option value="2">Group 2</option>
</select></code>```

答:
```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var cnt1=0,cnt2=0,cnt3=0;
$(".one").change(function(){
    cnt1=1;
    if((cnt1==1) && (cnt2==1) && (cnt3==1)){
        alert('test');
    }
});
$(".two").change(function(){
    cnt2=1;
    if((cnt1==1) && (cnt2==1) && (cnt3==1)){
        alert('test');
    }
});
$(".three").change(function(){
    cnt3=1;
    if((cnt1==1) && (cnt2==1) && (cnt3==1)){
        alert('test');
    }
});</code>```

    <select name="company1" class="dropdown one">
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
    </select>
    <select name="company2" class="dropdown two">
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
    </select>
    <select name="company3" class="dropdown three">
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
    </select>```
</div>
</div>

</code>```

Body:
I have to apply some css when all dropdown is changed. Please help me with this.

$("select").change(function() {
  alert('test');
});

<select name="company1" class="dropdown">
  <option value="1">Group 1</option>
  <option value="2">Group 2</option>
</select>
<select name="company2" class="dropdown">
  <option value="1">Group 1</option>
  <option value="2">Group 2</option>
</select>
<select name="company3" class="dropdown">
  <option value="1">Group 1</option>
  <option value="2">Group 2</option>
</select>

Body:
var cnt1=0,cnt2=0,cnt3=0;
$(".one").change(function(){
    cnt1=1;
    if((cnt1==1) && (cnt2==1) && (cnt3==1)){
        alert('test');
    }
});
$(".two").change(function(){
    cnt2=1;
    if((cnt1==1) && (cnt2==1) && (cnt3==1)){
        alert('test');
    }
});
$(".three").change(function(){
    cnt3=1;
    if((cnt1==1) && (cnt2==1) && (cnt3==1)){
        alert('test');
    }
});

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select name="company1" class="dropdown one">
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
    </select>
    <select name="company2" class="dropdown two">
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
    </select>
    <select name="company3" class="dropdown three">
        <option value="1">Group 1</option>
        <option value="2">Group 2</option>
    </select>


问:
XSLT 1.0 replacing tab character with a HTML element containing a tab
I've been bashing my head against XSLT character replacement with HTML elements to no avail and can't for the life of me figure out how to get XSLT to replace a tab with a span element containing a tab.

What I have within an XHTML document is a pre element that contains tab characters, and I found an XSLT string replace template function which I'm using to try to replace the tabs with tabs surrounded by spans:

```<code>    <xsl:template match="xhtml:pre">
        <xsl:element name="{local-name()}">

            <xsl:variable name="BodyText"><span class="tabspan">	</span></xsl:variable>

            <xsl:call-template name="replace">
                <xsl:with-param name="text" select="@*|node()"/>
                <xsl:with-param name="search" select="'	'"/>
                <xsl:with-param name="replace" select="$BodyText"/>
            </xsl:call-template>

        </xsl:element>
    </xsl:template>

    <!-- Replacement template function for XSLT 1.0 -->
    <xsl:template name="replace">
        <xsl:param name="text"/>
        <xsl:param name="search"/>
        <xsl:param name="replace"/>
        <xsl:choose>
            <xsl:when test="contains($text, $search)">
                <xsl:variable name="replace-next">
                    <xsl:call-template name="replace">
                        <xsl:with-param name="text" select="substring-after($text, $search)"/>
                        <xsl:with-param name="search" select="$search"/>
                        <xsl:with-param name="replace" select="$replace"/>
                    </xsl:call-template>
                </xsl:variable>
                <xsl:value-of select="concat(substring-before($text, $search),$replace, $replace-next)"/>
            </xsl:when>
            <xsl:otherwise>
                <span class="tabspan">
                    <xsl:value-of select="$text"/>
                </span>
            </xsl:otherwise>
        </xsl:choose>
</code>```

However, no matter how I change the code, the span elements are either missing in the output (if I try to assign it via an xsl:variable like above) or it doesn't properly convert the XML escaped characters representing the angular brackets

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

Despite bizarrely converting

```<code>"
</code>```

To a quotation mark. I'm admittedly confused and don't know enough about XSLT 1.0. XSLT 2.0, 3.0 and EXSLT are not an option due to the limitations of the converting system.

答:
Consider the following minimal example:

Input

```<code><html xmlns="http://www.w3.org/1999/xhtml">
    <head/>
    <body>
    <p>This is an example.</p>
    ```Text before    text in the middle  text after```
    </body>
</html>
</code>```

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="xhtml:pre">
    <xsl:copy>
        <xsl:call-template name="replace-tabs">
            <xsl:with-param name="text" select="."/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="replace-tabs">
    <xsl:param name="text"/>
    <xsl:choose>
        <xsl:when test="contains($text, '	')">
            <xsl:value-of select="substring-before($text, '	')"/>
            <span class="tabspan">
                <xsl:text>	</xsl:text>
            </span>
            <xsl:call-template name="replace-tabs">
                <xsl:with-param name="text" select="substring-after($text, '	')"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head/>
  <body>
    <p>This is an example.</p>
    ```Text before  text in the middle text after```
  </body>
</html>
</code>```

To make this closer to your attempt:

```<code><xsl:variable name="BodyText">
    <span class="tabspan">
        <xsl:text>	</xsl:text>
    </span>
</xsl:variable>

<xsl:template match="xhtml:pre">
    <xsl:copy>
        <xsl:call-template name="replace">
            <xsl:with-param name="text" select="."/>
            <xsl:with-param name="searchString" select="'	'"/>
            <xsl:with-param name="replacement" select="$BodyText"/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="replace">
    <xsl:param name="text"/>
    <xsl:param name="searchString"/>
    <xsl:param name="replacement"/>
    <xsl:choose>
        <xsl:when test="contains($text, $searchString)">
            <xsl:value-of select="substring-before($text, $searchString)"/>
            <xsl:copy-of select="$replacement"/>
            <xsl:call-template name="replace">
                <xsl:with-param name="text" select="substring-after($text, $searchString)"/>
                <xsl:with-param name="searchString" select="$searchString"/>
                <xsl:with-param name="replacement" select="$replacement"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

Body:
I've been bashing my head against XSLT character replacement with HTML elements to no avail and can't for the life of me figure out how to get XSLT to replace a tab with a span element containing a tab.

What I have within an XHTML document is a pre element that contains tab characters, and I found an XSLT string replace template function which I'm using to try to replace the tabs with tabs surrounded by spans:

    <xsl:template match="xhtml:pre">
        <xsl:element name="{local-name()}">

            <xsl:variable name="BodyText">	</xsl:variable>

            <xsl:call-template name="replace">
                <xsl:with-param name="text" select="@*|node()"/>
                <xsl:with-param name="search" select="'	'"/>
                <xsl:with-param name="replace" select="$BodyText"/>
            </xsl:call-template>

        </xsl:element>
    </xsl:template>

    <xsl:template name="replace">
        <xsl:param name="text"/>
        <xsl:param name="search"/>
        <xsl:param name="replace"/>
        <xsl:choose>
            <xsl:when test="contains($text, $search)">
                <xsl:variable name="replace-next">
                    <xsl:call-template name="replace">
                        <xsl:with-param name="text" select="substring-after($text, $search)"/>
                        <xsl:with-param name="search" select="$search"/>
                        <xsl:with-param name="replace" select="$replace"/>
                    </xsl:call-template>
                </xsl:variable>
                <xsl:value-of select="concat(substring-before($text, $search),$replace, $replace-next)"/>
            </xsl:when>
            <xsl:otherwise>

                    <xsl:value-of select="$text"/>

            </xsl:otherwise>
        </xsl:choose>

However, no matter how I change the code, the span elements are either missing in the output (if I try to assign it via an xsl:variable like above) or it doesn't properly convert the XML escaped characters representing the angular brackets

>
<

Despite bizarrely converting

"

To a quotation mark. I'm admittedly confused and don't know enough about XSLT 1.0. XSLT 2.0, 3.0 and EXSLT are not an option due to the limitations of the converting system.

Body:
Consider the following minimal example:

Input

<html xmlns="http://www.w3.org/1999/xhtml">
    <head/>
    <body>
    <p>This is an example.</p>
    <pre>Text before    text in the middle  text after</pre>
    </body>
</html>

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="xhtml:pre">
    <xsl:copy>
        <xsl:call-template name="replace-tabs">
            <xsl:with-param name="text" select="."/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="replace-tabs">
    <xsl:param name="text"/>
    <xsl:choose>
        <xsl:when test="contains($text, '&#9;')">
            <xsl:value-of select="substring-before($text, '&#9;')"/>
            <span class="tabspan">
                <xsl:text>&#9;</xsl:text>
            </span>
            <xsl:call-template name="replace-tabs">
                <xsl:with-param name="text" select="substring-after($text, '&#9;')"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head/>
  <body>
    <p>This is an example.</p>
    <pre>Text before<span class="tabspan">  </span>text in the middle<span class="tabspan"> </span>text after</pre>
  </body>
</html>

To make this closer to your attempt:

<xsl:variable name="BodyText">
    <span class="tabspan">
        <xsl:text>&#9;</xsl:text>
    </span>
</xsl:variable>

<xsl:template match="xhtml:pre">
    <xsl:copy>
        <xsl:call-template name="replace">
            <xsl:with-param name="text" select="."/>
            <xsl:with-param name="searchString" select="'&#9;'"/>
            <xsl:with-param name="replacement" select="$BodyText"/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="replace">
    <xsl:param name="text"/>
    <xsl:param name="searchString"/>
    <xsl:param name="replacement"/>
    <xsl:choose>
        <xsl:when test="contains($text, $searchString)">
            <xsl:value-of select="substring-before($text, $searchString)"/>
            <xsl:copy-of select="$replacement"/>
            <xsl:call-template name="replace">
                <xsl:with-param name="text" select="substring-after($text, $searchString)"/>
                <xsl:with-param name="searchString" select="$searchString"/>
                <xsl:with-param name="replacement" select="$replacement"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>


问:
InvalidOperation: (:) [Start-Process], InvalidOperationException
I am getting the following error :

This command cannot be run due to the error: The system cannot find the file specified.
      + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
      + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
      + PSComputerName        : XXXXXX.yyy.com

Here is the snippet of the code:

```<code>if (($ToolsStatus -eq 'toolsOk' -OR $ToolsStatus -eq 'toolsOld') -AND $VMVSSStatus -eq $null -AND $OperatingSystem -match "64-bit" ) {
            try{
                Copy-Item -Path ".\64bit\$ToolsVersion.exe" -Destination "\\$FQDN\c$\"  -Container -Recurse -Force -ErrorAction Stop
                "File $ToolsVersion.exe copied on $vmName" | Do-Log
                try {
                    Invoke-Command -ComputerName $FQDN -ScriptBlock {
                        Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=all"' -Wait
                        Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r REMOVE=VSS"' -Wait
                        Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=VSS"' -Wait
                        "Installation completed on $vmName" | Do-Log
                        taskkill /IM vmtoolsd.exe /F
                        "VMtools process killed on $vmName" | Do-Log
                        Start-Service -Name VMTools
                        "VMware Tools service was started on $vmName" | Do-Log
                    }
                }
                catch [System.Management.Automation.RuntimeException]#PSRemotingTransportException
                {
                     "Unable to install on $vmName. Following error was encountered:" +$_.Exception.GetType().FullName | Do-Log
                }
</code>```

Please help.

答:
I guess the $ToolsVersion variable is undefined in the scope of Invoke-Command, since the scope is executed on the remote machine.

Try:

```<code>Start-Process "C:\$Using:ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=all"' -Wait

</code>```

instead.

From about_Remote_Variables:

USING LOCAL VARIABLES

You can also use local variables in remote commands, but you must indicate that the variable is defined in the local session.

Beginning in Windows PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command. ...

UPDATE 1:

To retrieve the logs from the remote you've to change your code to:

```<code> Invoke-Command -ComputerName $FQDN -ScriptBlock {
                    $computerName = $env:COMPUTERNAME
                    Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=all"' -Wait
                    Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r REMOVE=VSS"' -Wait
                    Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=VSS"' -Wait
                    $logging =  @()
                    $logging = "$computerName: Installation completed on $vmName"
                    taskkill /IM vmtoolsd.exe /F
                    $logging += "$computerName: VMtools process killed on $vmName"
                    Start-Service -Name VMTools
                    $logging += "$computerName: VMware Tools service was started on $vmName"
                    $logging
                } | Do-Log
</code>```

Here the array $logging will be serialized over the network. On your machine, it's deserialized, and every entry of the array is sent to your local pipeline.

Hope that helps.

Body:
I am getting the following error :

This command cannot be run due to the error: The system cannot find the file specified.
      + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
      + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
      + PSComputerName        : XXXXXX.yyy.com

Here is the snippet of the code:

if (($ToolsStatus -eq 'toolsOk' -OR $ToolsStatus -eq 'toolsOld') -AND $VMVSSStatus -eq $null -AND $OperatingSystem -match "64-bit" ) {
            try{
                Copy-Item -Path ".\64bit\$ToolsVersion.exe" -Destination "\\$FQDN\c$\"  -Container -Recurse -Force -ErrorAction Stop
                "File $ToolsVersion.exe copied on $vmName" | Do-Log
                try {
                    Invoke-Command -ComputerName $FQDN -ScriptBlock {
                        Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=all"' -Wait
                        Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r REMOVE=VSS"' -Wait
                        Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=VSS"' -Wait
                        "Installation completed on $vmName" | Do-Log
                        taskkill /IM vmtoolsd.exe /F
                        "VMtools process killed on $vmName" | Do-Log
                        Start-Service -Name VMTools
                        "VMware Tools service was started on $vmName" | Do-Log
                    }
                }
                catch [System.Management.Automation.RuntimeException]#PSRemotingTransportException
                {
                     "Unable to install on $vmName. Following error was encountered:" +$_.Exception.GetType().FullName | Do-Log
                }

Please help.

Body:
I guess the $ToolsVersion variable is undefined in the scope of Invoke-Command, since the scope is executed on the remote machine.

Try:

Start-Process "C:\$Using:ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=all"' -Wait

instead.

From about_Remote_Variables:

USING LOCAL VARIABLES

You can also use local variables in remote commands, but you must indicate that the variable is defined in the local session.

Beginning in Windows PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command. ...

UPDATE 1:

To retrieve the logs from the remote you've to change your code to:

 Invoke-Command -ComputerName $FQDN -ScriptBlock {
                    $computerName = $env:COMPUTERNAME
                    Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=all"' -Wait
                    Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r REMOVE=VSS"' -Wait
                    Start-Process "C:\$ToolsVersion.exe" -ArgumentList '/s /v "/qn reboot=r ADDLOCAL=VSS"' -Wait
                    $logging =  @()
                    $logging = "$computerName: Installation completed on $vmName"
                    taskkill /IM vmtoolsd.exe /F
                    $logging += "$computerName: VMtools process killed on $vmName"
                    Start-Service -Name VMTools
                    $logging += "$computerName: VMware Tools service was started on $vmName"
                    $logging
                } | Do-Log

Here the array $logging will be serialized over the network. On your machine, it's deserialized, and every entry of the array is sent to your local pipeline.

Hope that helps.


问:
document.hasOwnProperty("hidden") returns false but document has the property hidden
I'm trying to check if document has 'hidden' property using document.hasOwnProperty but it always returns false in Chrome (74).

I've tried Object.prototype.hasOwnProperty but that too returns false. When I tried to stringify and parse back document I got back Location object as a property.

console.log(document.hasOwnProperty("hidden"));
console.log(Object.prototype.hasOwnProperty.call(document, "false"));
console.log(JSON.parse(JSON.stringify(document)));
console.log(typeof document.hidden !== "undefined");
console.log(document.hidden);
console.log(Document.prototype.hasOwnProperty.call(document, "hidden"));
console.log(Document.prototype.hasOwnProperty.call(document, "location"));```

Shouldn't hasOwnProperty check if an object has a property irrespective of the object type? I apologize if the question has already been answered.

答:
The purpose of hasOwnProperty() is to check whether a certain property is defined on the instance itself and is not inherited through its prototype.

In the case of document, it rightfully returns false since the hidden property is actually defined on the Document interface and not on the instance itself.

(thanks to @Jonas Wilms for clarification)

Body:
I'm trying to check if document has 'hidden' property using document.hasOwnProperty but it always returns false in Chrome (74).

I've tried Object.prototype.hasOwnProperty but that too returns false. When I tried to stringify and parse back document I got back Location object as a property.

console.log(document.hasOwnProperty("hidden"));
console.log(Object.prototype.hasOwnProperty.call(document, "false"));
console.log(JSON.parse(JSON.stringify(document)));
console.log(typeof document.hidden !== "undefined");
console.log(document.hidden);
console.log(Document.prototype.hasOwnProperty.call(document, "hidden"));
console.log(Document.prototype.hasOwnProperty.call(document, "location"));

Shouldn't hasOwnProperty check if an object has a property irrespective of the object type? I apologize if the question has already been answered.


答:
This is quite complicated.  I would suggest:

Backup the tables!

Update the id in the transactions table to be the maximum id .

Fix the players table.

Fix your data model.

That is:

```<code>update transactions t join
       players p
       on t.player_id = p.id join
       (select p2.name, max(p2.id) as max_id
        from players p2
        group by p2.name
        having count(*) > 1
       ) p2
       on p2.name = p.name  -- or should this be "base_id"
    set t.player_id = p2.max_id
    where t.player_id <> p2.max_id;
</code>```

Then, to update the table, I recommend emptying it and recreating it:

```<code>create table players_temp as
    select max(id) as id,  base_id, name,
           sum(total_searches) as total_searches,
           sum(auctions_found) as auctions_found,
           sum(auctions_won) as auctions_won,
           min(created_at) as created_at
    from players
    group by base_id, name;  -- or whatever

truncate table players;

insert into players (id, base_id, name, total_searches, auctions_found, auctions_won, created_at)
    select id, base_id, name, total_searches, auctions_found, auctions_won, created_at
    from players_temp;
</code>```

Then fix the data model:

```<code>alter table players add constraint unq_players_name
    unique (name);

alter table players add constraint unq_players_base_id
    unique (base_id);
</code>```

Title: Merge MYSQL rows, totalling some columns, updating ID's in another table

Body:
I have a MySQL database with several tables, two of which look like this:

players

+-----+---------+-------------------+----------------+----------------+--------------+---------------------+
| id  | base_id |       name        | total_searches | auctions_found | auctions_won |     created_at      |
+-----+---------+-------------------+----------------+----------------+--------------+---------------------+
| 283 |  177683 | Christian Eriksen |             12 |              2 |            1 | 2019-05-29 11:25:08 |
| 160 |  177683 | Christian Eriksen |             24 |              4 |            1 | 2019-05-29 11:25:08 |
|  76 |  345345 | Yan Sommer        |             12 |              1 |            3 | 2019-05-29 11:25:08 |
| 712 |    4353 | Yannick Carrasco  |             42 |              5 |           12 | 2019-05-29 11:25:08 |
+-----+---------+-------------------+----------------+----------------+--------------+---------------------+

transactions

+----+-----------+---------------------+
| id | player_id |     updated_at      |
+----+-----------+---------------------+
|  1 |       283 | 2019-05-29 11:25:08 |
|  2 |       160 | 2019-05-29 11:25:08 |
|  3 |        76 | 2019-05-29 11:25:08 |
+----+-----------+---------------------+

As you can see, there are duplicates in the players table (Christian Eriksen). I would like to merge these rows, totalling the total_searches, auctions_found and auctions_won columns. There are several other columns in this table (some omitted here for brevity) which are either the same (eg. base_id) or it's not hugely important which value is retained (eg. created_at).

What is important is the id. Either a new id should be created or, ideally, one of the existing ids retained. The transactions table would then need to be updated with the new player_id.

+-----+---------+-------------------+----------------+----------------+--------------+---------------------+
| id  | base_id |       name        | total_searches | auctions_found | auctions_won |     created_at      |
+-----+---------+-------------------+----------------+----------------+--------------+---------------------+
| 160 |  177683 | Christian Eriksen |             36 |              6 |            2 | 2019-05-29 11:25:08 |
|  76 |  345345 | Yan Sommer        |             12 |              1 |            3 | 2019-05-29 11:25:08 |
| 712 |    4353 | Yannick Carrasco  |             42 |              5 |           12 | 2019-05-29 11:25:08 |
+-----+---------+-------------------+----------------+----------------+--------------+---------------------+

+----+-----------+---------------------+
| id | player_id |     updated_at      |
+----+-----------+---------------------+
|  1 |       160 | 2019-05-29 11:25:08 |
|  2 |       160 | 2019-05-29 11:25:08 |
|  3 |        76 | 2019-05-29 11:25:08 |
+----+-----------+---------------------+

I don't have any knowledge of SQL so I haven't tried anything yet. Some pointers or ideally a complete solution would be appreciated.

Body:
This is quite complicated.  I would suggest:

Backup the tables!

Update the id in the transactions table to be the maximum id .

Fix the players table.

Fix your data model.

That is:

update transactions t join
       players p
       on t.player_id = p.id join
       (select p2.name, max(p2.id) as max_id
        from players p2
        group by p2.name
        having count(*) > 1
       ) p2
       on p2.name = p.name  -- or should this be "base_id"
    set t.player_id = p2.max_id
    where t.player_id <> p2.max_id;

Then, to update the table, I recommend emptying it and recreating it:

create table players_temp as
    select max(id) as id,  base_id, name,
           sum(total_searches) as total_searches,
           sum(auctions_found) as auctions_found,
           sum(auctions_won) as auctions_won,
           min(created_at) as created_at
    from players
    group by base_id, name;  -- or whatever

truncate table players;

insert into players (id, base_id, name, total_searches, auctions_found, auctions_won, created_at)
    select id, base_id, name, total_searches, auctions_found, auctions_won, created_at
    from players_temp;

Then fix the data model:

alter table players add constraint unq_players_name
    unique (name);

alter table players add constraint unq_players_base_id
    unique (base_id);


问:
format of number on downloading in csv format
Following code returns hours for given seconds, which is working.

```<code><?php

$hrs = seconds_to_dezi(278280);
echo $hrs;
$filename = "test";
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");

function seconds_to_dezi($s) {
    $n = false;
    if ($s < 0) {
        $n = true;
        $s = -$s;
    }
    $h = round($s / 3600,2);
    $h = number_format($h,2, ',', ' ');
    $h = str_replace(".",",",$h);

    if ($n == true) {
        return ("-" . $h);
    } else {
        return ($h);
    }
}

?>
</code>```

Actual output in excel:- 77,3

Expected output is:- 77,30

i.e on downloading values in csv format, the trailing zero after decimal is truncated. I want to have that zero in excel.

答: You cannot explicitly set the number of decimals in a CSV file. If you need to show 77,30 you can use ="70,30". It will show up in the file correct, but it will be text then. So you can no longer use it as a number in excel.</p>

Body:
Following code returns hours for given seconds, which is working.

<?php

$hrs = seconds_to_dezi(278280);
echo $hrs;
$filename = "test";
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");

function seconds_to_dezi($s) {
    $n = false;
    if ($s < 0) {
        $n = true;
        $s = -$s;
    }
    $h = round($s / 3600,2);
    $h = number_format($h,2, ',', ' ');
    $h = str_replace(".",",",$h);

    if ($n == true) {
        return ("-" . $h);
    } else {
        return ($h);
    }
}

?>

Actual output in excel:- 77,3

Expected output is:- 77,30

i.e on downloading values in csv format, the trailing zero after decimal is truncated. I want to have that zero in excel.


问:
Selenium - Maven/TestNG: How to add "testng.xml" and log4j2.xml path in pom.xml so executable .jar file can be executed on other machine as well?
I am working with Maven/TestNG/Log4j2.

Our aim is to create an executable .jar file which will run testng.xml via pom.xml file.

So right now, I am able to create an executable .jar file and able to run it successfully on my machine as well. But when I try to run same .jar file on another machine then It's throwing an "Filenotfoundexception" as it is trying to access testng.xml and log4j2.xml with my local path.

Also, executable .Jar file has testng.xml and log4j2.xml file in it's root level only.

Here is my project structure:

I have used "maven assembly, surefire, compiler plugins" and resources tag for .xml files.

This is how my build looks like:

```<code><build>
<sourceDirectory>src</sourceDirectory>
 <plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
     <configuration>
      <release>10</release>
     </configuration>
  </plugin>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
     <execution>
      <id>make-assembly</id>
    <!-- bind to the packaging phase -->
      <phase>package</phase>
      <goals>
       <goal>single</goal>
      </goals>
      <configuration>
    <!-- get all project dependencies -->
       <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
       </descriptorRefs>
        <!-- MainClass in mainfest make a executable jar -->
       <archive>
       <manifest>
        <mainClass>test.FirstTest</mainClass>
       </manifest>
       </archive>
     </configuration>
    </execution>
   </executions>
  </plugin>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
     <version>3.0.0-M3</version>
      <configuration>
       <suiteXmlFiles>
      <suiteXmlFile>.//src/main/java/resources/testng.xml</suiteXmlFile>
       </suiteXmlFiles>
      </configuration>
   </plugin>
  </plugins>
 <resources>
  <resource>
   <directory>src/main/java/resources</directory>
    <includes>
     <include>*.xml</include>
    </includes>
   </resource>
  </resources>
</build>
</code>```

And this is how my testNG main method looks like:

```<code>public static void main(String[] args) {
 TestNG testng = new TestNG();
 List<String> suites = Lists.newArrayList();
 suites.add(".//src/main/java/resources/testng.xml");
 testng.setTestSuites(suites);
 testng.run();
}
</code>```

We are aiming to create an executable .jar file bundled with testng.xml and log4j2.xml. So we can share it with other teams as well.

Please let me know if you need any more info.

答:
It is very simple to include and exclude the files in the build process. I provide below the code snippet for you understand.

```<code><build>
        <resources>
          <resource>
            <directory>src/resources</directory>
<!-- To include the files -->
             <includes>
                 <include>**/*.properties</include>
                 <include>**/*.xml</include>
            </includes>
<!-- To exclude -->
            <excludes>
              <exclude>**/*.jpeg</exclude>
              <exclude>**/*.gif</exclude>
            </excludes>
          </resource>
    </resources>
.....
.....
</build>
</code>```

To create a a runnable jar file, refer below the very simple and small project in github.

https://github.com/debjava/runnableJar

Body:
I am working with Maven/TestNG/Log4j2.

Our aim is to create an executable .jar file which will run testng.xml via pom.xml file.

So right now, I am able to create an executable .jar file and able to run it successfully on my machine as well. But when I try to run same .jar file on another machine then It's throwing an "Filenotfoundexception" as it is trying to access testng.xml and log4j2.xml with my local path.

Also, executable .Jar file has testng.xml and log4j2.xml file in it's root level only.

Here is my project structure:

I have used "maven assembly, surefire, compiler plugins" and resources tag for .xml files.

This is how my build looks like:

<build>
<sourceDirectory>src</sourceDirectory>
 <plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
     <configuration>
      <release>10</release>
     </configuration>
  </plugin>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
     <execution>
      <id>make-assembly</id>

      <phase>package</phase>
      <goals>
       <goal>single</goal>
      </goals>
      <configuration>

       <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
       </descriptorRefs>

       <archive>
       <manifest>
        <mainClass>test.FirstTest</mainClass>
       </manifest>
       </archive>
     </configuration>
    </execution>
   </executions>
  </plugin>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
     <version>3.0.0-M3</version>
      <configuration>
       <suiteXmlFiles>
      <suiteXmlFile>.//src/main/java/resources/testng.xml</suiteXmlFile>
       </suiteXmlFiles>
      </configuration>
   </plugin>
  </plugins>
 <resources>
  <resource>
   <directory>src/main/java/resources</directory>
    <includes>
     <include>*.xml</include>
    </includes>
   </resource>
  </resources>
</build>

And this is how my testNG main method looks like:

public static void main(String[] args) {
 TestNG testng = new TestNG();
 List<String> suites = Lists.newArrayList();
 suites.add(".//src/main/java/resources/testng.xml");
 testng.setTestSuites(suites);
 testng.run();
}

We are aiming to create an executable .jar file bundled with testng.xml and log4j2.xml. So we can share it with other teams as well.

Please let me know if you need any more info.

Body:
It is very simple to include and exclude the files in the build process. I provide below the code snippet for you understand.

<build>
        <resources>
          <resource>
            <directory>src/resources</directory>
<!-- To include the files -->
             <includes>
                 <include>**/*.properties</include>
                 <include>**/*.xml</include>
            </includes>
<!-- To exclude -->
            <excludes>
              <exclude>**/*.jpeg</exclude>
              <exclude>**/*.gif</exclude>
            </excludes>
          </resource>
    </resources>
.....
.....
</build>

To create a a runnable jar file, refer below the very simple and small project in github.

https://github.com/debjava/runnableJar


问:
rxjs observable.pipe(take(1)) vs toPromise
Recently I've been moved to a new project which uses angular 6 as frontend framework and spring for REST services.

The project is in development for 2 years now and what I've observed was that almost all HTTP request made with angular HttpClient is then piped to take filter from rxjs. All REST APIs emit only one value. There's no need for manual cancellation and the laziness property of observables.

My intuition is that using toPromise() would be a better way to code.

What are your thoughts?

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() {
     return http.get('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().pipe(take(1)).subscribe((customers) => {
           //do some stuff
      })
  }
```

<p>My proposed approach:</p>

<pre class="lang-js prettyprint-override"><code>  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() : Promise<Array<Customer>> {
     return http.get('/customers').toPromise();
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().then((customers: Array<Customer>) => {
         //do some stuff
      })
  }
</code>```

I think that my approach is better because it is strongly typed and it's cleaner.

答:
Going from observables to promises is a step back.

It's like going from a Porsche 911 to a Fiat multipla.

So no, you shouldn't use toPromise(), and no, your way isn't "better" (that's some ego there buddy !)

I think that my approach is better because it is strongly typed and it's cleaner.

Typing an HTTP answer isn't depending on pormises or observables, but on the developer himself. And cleaner is a matter of perspective, personally I hate seeing toPromise()s.

And the major drawback of your solution is that once converted to a promise, you can't pipe anything anymore, making your functions less versatile.

But their code isn't the best either. Usually this kind of behavior is used for stores and caches, are you sure you didn't omit something ?

Anyway, if not, and I only rely on the code provided, this would be the right code :

```<code>public getCustomers() {
  return http.get<Customer[]>('/customers');
}

....

public ngOnInit() {
  this.customerService.getCustomers()
    .subscribe((customers) => {...})
}
</code>```

Body:
Recently I've been moved to a new project which uses angular 6 as frontend framework and spring for REST services.

The project is in development for 2 years now and what I've observed was that almost all HTTP request made with angular HttpClient is then piped to take filter from rxjs. All REST APIs emit only one value. There's no need for manual cancellation and the laziness property of observables.

My intuition is that using toPromise() would be a better way to code.

What are your thoughts?

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() {
     return http.get('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().pipe(take(1)).subscribe((customers) => {
           //do some stuff
      })
  }

My proposed approach:

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() : Promise<Array<Customer>> {
     return http.get('/customers').toPromise();
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().then((customers: Array<Customer>) => {
         //do some stuff
      })
  }

I think that my approach is better because it is strongly typed and it's cleaner.

Body:
Going from observables to promises is a step back.

It's like going from a Porsche 911 to a Fiat multipla.

So no, you shouldn't use toPromise(), and no, your way isn't "better" (that's some ego there buddy !)

I think that my approach is better because it is strongly typed and it's cleaner.

Typing an HTTP answer isn't depending on pormises or observables, but on the developer himself. And cleaner is a matter of perspective, personally I hate seeing toPromise()s.

And the major drawback of your solution is that once converted to a promise, you can't pipe anything anymore, making your functions less versatile.

But their code isn't the best either. Usually this kind of behavior is used for stores and caches, are you sure you didn't omit something ?

Anyway, if not, and I only rely on the code provided, this would be the right code :

public getCustomers() {
  return http.get<Customer[]>('/customers');
}

....

public ngOnInit() {
  this.customerService.getCustomers()
    .subscribe((customers) => {...})
}


问:
Google-chart trendline not showing
Google-chart trend-line not showing. Tried to put the code in vAxis, hAxis and only in options but no luck. I know that the first column must be a number or date and so on and my first column is a date.

```<code> <script type="text/javascript">
  data.sort([{column: 0}]);
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Sum'],
       <?php while($row = mysqli_fetch_assoc($result)) { ?>

      [<?php echo $row['date'] ?>,  <?php echo $row['col2'] ?> ],

    <?php } ?>
    ]);

    var options = {
         legend: { position: 'bottom' },
        title: 'Sum per day',
         hAxis : { textStyle : { fontSize: 10 } },
    vAxis: { viewWindowMode: 'explicit', viewWindow: { min: 0 } },
    trendlines: { 0: {} }
    };

    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, options);
  }
</script>
</code>```

答:
when loading the data, the first column needs to be converted from a string to a date.

place the value from php in quotes and inside a date constructor.

e.g.

```<code>[new Date('<?php echo $row['date'] ?>'),  <?php echo $row['col2'] ?> ],
</code>```

if you still have problems with the squiggly line,

sort the data before drawing...

```<code>data.sort([{column: 0}]);
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
</code>```

Title: Google-chart trendline not showing

Body:
when loading the data, the first column needs to be converted from a string to a date.

place the value from php in quotes and inside a date constructor.

e.g.

[new Date('<?php echo $row['date'] ?>'),  <?php echo $row['col2'] ?> ],

if you still have problems with the squiggly line,

sort the data before drawing...

data.sort([{column: 0}]);
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);


问:
Add labels on X-axis
Simple question.

I'd like to add custom characters to label the X-axis in R Histogram.

As can be seen on the image belov, the only labeling for the units is 0,50,100 but I'd like to have 0,5,10,15,etc (or 0:5,5:10,10:15,15:20,etc written perpendicular to the axis)

Is there a variable I've overlooked in customizing the addition of labels or do i need to use another lib than Hist, perhaps ggplot2?

答:
Replying to someone who might be making a histogram without using ggplot2:</p>

```<code>set.seed(0)
hist(runif(250, 0, 100), cex.axis = 0.6, xaxt = "n",
     col = rgb(0,0, 0.8, 0.35), border = FALSE, xlab = "x", main = "")

myseq <- as.character(seq(0,100, by = 5))
axis(1, at = myseq, labels = myseq, cex.axis = 0.6)
title(main = "Using of the graphics package", xlab = "x")
</code>```

Title: Add labels on X-axis

Body:
Replying to someone who might be making a histogram without using ggplot2:

set.seed(0)
hist(runif(250, 0, 100), cex.axis = 0.6, xaxt = "n",
     col = rgb(0,0, 0.8, 0.35), border = FALSE, xlab = "x", main = "")

myseq <- as.character(seq(0,100, by = 5))
axis(1, at = myseq, labels = myseq, cex.axis = 0.6)
title(main = "Using of the graphics package", xlab = "x")


问:
How to share a CSV file on Android Pie?
On Android Pie, I want to share my CSV file to any sharing app such as Bluetooth or email, etc... it runs in lower version but in 9.0 it won't</p>

```<code>  final String test = "content://" + Environment.getExternalStorageDirectory()
                                   + "/Download" + "/" + "ProgressivePayment.csv";
  Intent sharingIntent = new Intent();
  sharingIntent.setAction(Intent.ACTION_SEND);
  sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(test));
  sharingIntent.setType("text/csv");
  startActivity(Intent.createChooser(sharingIntent, "share file with"));
</code>```

答:
it runs in lower version

It is possible that there is some poorly-written app that incorrectly handles EXTRA_STREAM and accidentally handles that broken Uri. Or, as Martin Zeitler points out, perhaps there is a strange pre-installed ContentProvider on the device that happens to honor your broken Uri. Most apps on most devices will crash when attempting to use that Uri, as there will be no matching ContentProvider.

You can use FileProvider to correctly create a content Uri that will serve up some file that you control.

Title: How to share a CSV file on Android Pie?

Body:
On Android Pie, I want to share my CSV file to any sharing app such as Bluetooth or email, etc... it runs in lower version but in 9.0 it won't

  final String test = "content://" + Environment.getExternalStorageDirectory()
                                   + "/Download" + "/" + "ProgressivePayment.csv";
  Intent sharingIntent = new Intent();
  sharingIntent.setAction(Intent.ACTION_SEND);
  sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(test));
  sharingIntent.setType("text/csv");
  startActivity(Intent.createChooser(sharingIntent, "share file with"));