问:
sbt unable to create jar for scala version 2.11.12
I am trying to create .jar file for simple hello world project using scala in intellij IDE (2019.3.2 community edition) with sbt build tool (version 1.3.8). I can do this without any issues for scala version 2.13.1. But when I am changing this to 2.11.12, sbt package is breaking with below error.
I wanted to add spark-core dependency as well to this project. So I have to use 2.11.12 version since there is not compatible version for 2.13.1.
Please help me with this error.

[info] Loading global plugins from C:\Users\username.sbt\1.0\plugins
  [info] Loading project definition from
  C:\Users\username\IdeaProjects\scalawithsbt\project [info] Loading
  settings for project scalawithsbt from build.sbt ... [info] Set
  current project to scalawithsbt (in build
  file:/C:/Users/username/IdeaProjects/scalawithsbt/) [info] Compiling 1
  Scala source to
  C:\Users\username\IdeaProjects\scalawithsbt\target\scala-2.11\classes
  ... Feb 14, 2020 11:48:15 AM
  lmcoursier.internal.shaded.coursier.cache.shaded.org.jline.utils.Log
  logr WARNING: Unable to create a system terminal, creating a dumb
  terminal (enable debug logging for more information) [info] Attempting
  to fetch org.scala-sbt:compiler-bridge_2.11:1.3.4. [info] Updating
  [info] Resolved  dependencies [error] ## Exception when compiling 1
  sources to
  C:\Users\username\IdeaProjects\scalawithsbt\target\scala-2.11\classes
  [error] sbt.internal.inc.InvalidComponent: The compiler bridge sources
  CoursierModuleDescriptor(ModuleDescriptorConfiguration(false, None,
  org.scala-sbt.temp:temp-module-518b91374cbcb06003d475b7704c2316602396eb:1.3.4:co
  mpile,
  ModuleInfo(temp-module-518b91374cbcb06003d475b7704c2316602396eb, ,
  None, None, Vector(), , None, None, Vector()),
  Vector(org.scala-sbt:compiler-bridge_2.11:1.3.4:compile), Vector(),
  Vector(), , Vector(compile, ru ntime, test, provided, optional),
  Some(compile), ConflictManager(latest-revision, *,
  *)),CoursierConfiguration(Some(sbt.internal.util.ManagedLogger@7306a11a),
  Vector(Raw(ProjectResolver(inter-project, mapped: org.scala-
  sbt#global-plugins;0.0)), public: https://repo1.maven.org/maven2/,
  FileRepository(local,
  Patterns(ivyPatterns=Vector(///C:/Users/username/.ivy2//local/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersio
  n]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(///C:/Users/username/.ivy2//local/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch]/)[revision]
  /[type]s/artifact.[ext]), isMavenCompatible=false,
  descriptorOptional=false, skipConsistencyCheck=false),
  FileConfiguration(true, None)), URLRepository(sbt-plugin-releases,
  Patterns(ivyPatterns=Vector(h
  ttps://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(https://re
  po.scala-sbt.org/scalasbt/sbt-plugin-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, descriptorOptional
  =false, skipConsistencyCheck=false), false), URLRepository(typesafe-alt-ivy-releases,
  Patterns(ivyPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtV
  ersion]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch
  ]/)[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, descriptorOptional=false,
  skipConsistencyCheck=false), false), sbt-maven-releases:
  https://repo.scala-sbt.org/scalasbt/maven-releases/, sb
  t-maven-snapshots:
  https://repo.scala-sbt.org/scalasbt/maven-snapshots/,
  URLRepository(typesafe-ivy-releases,
  Patterns(ivyPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organization]/[module]/[revision
  ]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organization]/[module]/[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, d escriptorOptional=false,
  skipConsistencyCheck=false), false), URLRepository(sbt-ivy-snapshots,
  Patterns(ivyPatterns=Vector(https://repo.scala-sbt.org/scalasbt/ivy-snapshots/[organization]/[module]/[revision]/[type]s/ar
  tifact.[ext]),
  artifactPatterns=Vector(https://repo.scala-sbt.org/scalasbt/ivy-snapshots/[organization]/[module]/[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, descriptorOp tional=false,
  skipConsistencyCheck=false), false)), 6, 100, Some(org.scala-lang),
  Some(2.12.10),
  Vector(C:\Users\username.sbt\boot\scala-2.12.10\lib\jansi.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\ jline.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-compiler.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-library.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-reflect .jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-xml_2.12.jar),
  Vector(), Vector(), Vector(), true, false, Vector(), Vector(),
  Some(org.scala-lang), Some(2.11.12), Vector(), Vector(), None,
  Some(C:\Users\ username\AppData\Local\Coursier\cache\v1),
  Some(C:\Users\username.ivy2), None, None, Vector(), Vector(),
  Vector((ModuleMatchers(Set(), Set(), true),Relaxed)), true)) could not
  be retrieved. [error] [error]         Note: Unresolved dependencies
  path: [error]
  sbt.internal.inc.ZincLMHelper$.update(ZincComponentCompiler.scala:293)
  [error]
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$3(ZincComponentCompiler.scala:257)
  [error]
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$3$adapted(ZincComponentCompiler.scala:250)
  [error] sbt.io.IO$.withTemporaryDirectory(IO.scala:489) [error]
  sbt.io.IO$.withTemporaryDirectory(IO.scala:499) [error]
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$2(ZincComponentCompiler.scala:250)
  [error]
  scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
  [error]
  sbt.internal.util.BufferedLogger.bufferQuietly(BufferedLogger.scala:119)
  [error]
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$1(ZincComponentCompiler.scala:250)
  [error]
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$1$adapted(ZincComponentCompiler.scala:247)
  [error] sbt.io.IO$.withTemporaryDirectory(IO.scala:489) [error]
  sbt.io.IO$.withTemporaryDirectory(IO.scala:499) [error]
  sbt.internal.inc.ZincComponentCompiler.compileAndInstall(ZincComponentCompiler.scala:247)
  [error]
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compiledBridgeJar$1(ZincComponentCompiler.scala:215)
  [error] sbt.internal.inc.IfMissing$Define.run(IfMissing.scala:19)
  [error]
  sbt.internal.inc.ZincComponentManager.createAndCache$1(ZincComponentManager.scala:49)
  [error]
  sbt.internal.inc.ZincComponentManager.$anonfun$files$3(ZincComponentManager.scala:60)
  [error]
  sbt.internal.inc.ZincComponentManager.getOrElse$1(ZincComponentManager.scala:42)
  [error]
  sbt.internal.inc.ZincComponentManager.$anonfun$files$2(ZincComponentManager.scala:60)
  [error]
  sbt.internal.inc.ZincComponentManager$$anon$1.call(ZincComponentManager.scala:89)
  [error] xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95)
  [error]
  xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
  [error]
  xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
  [error] xsbt.boot.Using$.withResource(Using.scala:10) [error]
  xsbt.boot.Using$.apply(Using.scala:9) [error]
  xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
  [error] xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50) [error]
  xsbt.boot.Locks$.apply0(Locks.scala:31) [error]
  xsbt.boot.Locks$.apply(Locks.scala:28) [error]
  sbt.internal.inc.ZincComponentManager.lock(ZincComponentManager.scala:89)
  [error]
  sbt.internal.inc.ZincComponentManager.$anonfun$lockSecondaryCache$1(ZincComponentManager.scala:86)
  [error] scala.Option.map(Option.scala:230) [error]
  sbt.internal.inc.ZincComponentManager.lockSecondaryCache(ZincComponentManager.scala:86)
  [error]
  sbt.internal.inc.ZincComponentManager.fromSecondary$1(ZincComponentManager.scala:58)
  [error]
  sbt.internal.inc.ZincComponentManager.$anonfun$files$6(ZincComponentManager.scala:64)
  [error]
  sbt.internal.inc.ZincComponentManager.getOrElse$1(ZincComponentManager.scala:42)
  [error]
  sbt.internal.inc.ZincComponentManager.$anonfun$files$5(ZincComponentManager.scala:64)
  [error]
  sbt.internal.inc.ZincComponentManager$$anon$1.call(ZincComponentManager.scala:89)
  [error] xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95)
  [error]
  xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
  [error]
  xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
  [error] xsbt.boot.Using$.withResource(Using.scala:10) [error]
  xsbt.boot.Using$.apply(Using.scala:9) [error]
  xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
  [error] xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50) [error]
  xsbt.boot.Locks$.apply0(Locks.scala:31) [error]
  xsbt.boot.Locks$.apply(Locks.scala:28) [error]
  sbt.internal.inc.ZincComponentManager.lock(ZincComponentManager.scala:89)
  [error]
  sbt.internal.inc.ZincComponentManager.lockLocalCache(ZincComponentManager.scala:82)
  [error]
  sbt.internal.inc.ZincComponentManager.files(ZincComponentManager.scala:64)
  [error]
  sbt.internal.inc.ZincComponentManager.file(ZincComponentManager.scala:70)
  [error]
  sbt.internal.inc.ZincComponentCompiler.compiledBridgeJar(ZincComponentCompiler.scala:215)
  [error]
  sbt.internal.inc.ZincComponentCompiler$ZincCompilerBridgeProvider.compiledBridge(ZincComponentCompiler.scala:75)
  [error]
  sbt.internal.inc.ZincComponentCompiler$ZincCompilerBridgeProvider.fetchCompiledBridge(ZincComponentCompiler.scala:81)
  [error]
  sbt.internal.inc.AnalyzingCompiler.loader(AnalyzingCompiler.scala:260)
  [error]
  sbt.internal.inc.AnalyzingCompiler.getInterfaceClass(AnalyzingCompiler.scala:278)
  [error]
  sbt.internal.inc.AnalyzingCompiler.call(AnalyzingCompiler.scala:245)
  [error]
  sbt.internal.inc.AnalyzingCompiler.newCachedCompiler(AnalyzingCompiler.scala:145)
  [error]
  sbt.internal.inc.AnalyzingCompiler.newCachedCompiler(AnalyzingCompiler.scala:132)
  [error]
  sbt.internal.inc.FreshCompilerCache.apply(CompilerCache.scala:102)
  [error]
  sbt.internal.inc.AnalyzingCompiler.compile(AnalyzingCompiler.scala:92)
  [error]
  sbt.internal.inc.MixedAnalyzingCompiler.$anonfun$compile$4(MixedAnalyzingCompiler.scala:91)
  [error]
  scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
  [error]
  sbt.internal.inc.MixedAnalyzingCompiler.timed(MixedAnalyzingCompiler.scala:186)
  [error]
  sbt.internal.inc.MixedAnalyzingCompiler.$anonfun$compile$3(MixedAnalyzingCompiler.scala:82)
  [error]
  sbt.internal.inc.MixedAnalyzingCompiler.$anonfun$compile$3$adapted(MixedAnalyzingCompiler.scala:77)
  [error] sbt.internal.inc.JarUtils$.withPreviousJar(JarUtils.scala:215)
  [error]
  sbt.internal.inc.MixedAnalyzingCompiler.compileScala$1(MixedAnalyzingCompiler.scala:77)
  [error]
  sbt.internal.inc.MixedAnalyzingCompiler.compile(MixedAnalyzingCompiler.scala:146)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.$anonfun$compileInternal$1(IncrementalCompilerImpl.scala:343)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.$anonfun$compileInternal$1$adapted(IncrementalCompilerImpl.scala:343)
  [error] sbt.internal.inc.Incremental$.doCompile(Incremental.scala:120)
  [error]
  sbt.internal.inc.Incremental$.$anonfun$compile$4(Incremental.scala:100)
  [error]
  sbt.internal.inc.IncrementalCommon.recompileClasses(IncrementalCommon.scala:180)
  [error]
  sbt.internal.inc.IncrementalCommon.cycle(IncrementalCommon.scala:98)
  [error]
  sbt.internal.inc.Incremental$.$anonfun$compile$3(Incremental.scala:102)
  [error]
  sbt.internal.inc.Incremental$.manageClassfiles(Incremental.scala:155)
  [error] sbt.internal.inc.Incremental$.compile(Incremental.scala:92)
  [error] sbt.internal.inc.IncrementalCompile$.apply(Compile.scala:75)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.compileInternal(IncrementalCompilerImpl.scala:348)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.$anonfun$compileIncrementally$1(IncrementalCompilerImpl.scala:301)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.handleCompilationError(IncrementalCompilerImpl.scala:168)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.compileIncrementally(IncrementalCompilerImpl.scala:248)
  [error]
  sbt.internal.inc.IncrementalCompilerImpl.compile(IncrementalCompilerImpl.scala:74)
  [error] sbt.Defaults$.compileIncrementalTaskImpl(Defaults.scala:1762)
  [error]
  sbt.Defaults$.$anonfun$compileIncrementalTask$1(Defaults.scala:1735)
  [error] scala.Function1.$anonfun$compose$1(Function1.scala:49) [error]
  sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:62)
  [error] sbt.std.Transform$$anon$4.work(Transform.scala:67) [error]
  sbt.Execute.$anonfun$submit$2(Execute.scala:281) [error]
  sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:19)
  [error] sbt.Execute.work(Execute.scala:290) [error]
  sbt.Execute.$anonfun$submit$1(Execute.scala:281) [error]
  sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
  [error] sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
  [error] java.util.concurrent.FutureTask.run(FutureTask.java:266)
  [error]
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
  [error] java.util.concurrent.FutureTask.run(FutureTask.java:266)
  [error]
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  [error]
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  [error] java.lang.Thread.run(Thread.java:748) [error] [error]
  sbt.internal.inc.InvalidComponent: The compiler bridge sources
  CoursierModuleDescriptor(ModuleDescriptorConfiguration(false, None,
  org.scala-sbt.temp:temp-module-518b91374cbcb06003d475b7704c2316602396eb:1.3.4:co
  mpile,
  ModuleInfo(temp-module-518b91374cbcb06003d475b7704c2316602396eb, ,
  None, None, Vector(), , None, None, Vector()),
  Vector(org.scala-sbt:compiler-bridge_2.11:1.3.4:compile), Vector(),
  Vector(), , Vector(compile, ru ntime, test, provided, optional),
  Some(compile), ConflictManager(latest-revision, *,
  *)),CoursierConfiguration(Some(sbt.internal.util.ManagedLogger@7306a11a),
  Vector(Raw(ProjectResolver(inter-project, mapped: org.scala-
  sbt#global-plugins;0.0)), public: https://repo1.maven.org/maven2/,
  FileRepository(local,
  Patterns(ivyPatterns=Vector(///C:/Users/username/.ivy2//local/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersio
  n]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(///C:/Users/username/.ivy2//local/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch]/)[revision]
  /[type]s/artifact.[ext]), isMavenCompatible=false,
  descriptorOptional=false, skipConsistencyCheck=false),
  FileConfiguration(true, None)), URLRepository(sbt-plugin-releases,
  Patterns(ivyPatterns=Vector(h
  ttps://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(https://re
  po.scala-sbt.org/scalasbt/sbt-plugin-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, descriptorOptional
  =false, skipConsistencyCheck=false), false), URLRepository(typesafe-alt-ivy-releases,
  Patterns(ivyPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtV
  ersion]/)([branch]/)[revision]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)([branch
  ]/)[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, descriptorOptional=false,
  skipConsistencyCheck=false), false), sbt-maven-releases:
  https://repo.scala-sbt.org/scalasbt/maven-releases/, sb
  t-maven-snapshots:
  https://repo.scala-sbt.org/scalasbt/maven-snapshots/,
  URLRepository(typesafe-ivy-releases,
  Patterns(ivyPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organization]/[module]/[revision
  ]/[type]s/artifact.[ext]),
  artifactPatterns=Vector(https://repo.typesafe.com/typesafe/ivy-releases/[organization]/[module]/[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, d escriptorOptional=false,
  skipConsistencyCheck=false), false), URLRepository(sbt-ivy-snapshots,
  Patterns(ivyPatterns=Vector(https://repo.scala-sbt.org/scalasbt/ivy-snapshots/[organization]/[module]/[revision]/[type]s/ar
  tifact.[ext]),
  artifactPatterns=Vector(https://repo.scala-sbt.org/scalasbt/ivy-snapshots/[organization]/[module]/[revision]/[type]s/artifact.[ext]),
  isMavenCompatible=false, descriptorOp tional=false,
  skipConsistencyCheck=false), false)), 6, 100, Some(org.scala-lang),
  Some(2.12.10),
  Vector(C:\Users\username.sbt\boot\scala-2.12.10\lib\jansi.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\ jline.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-compiler.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-library.jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-reflect .jar,
  C:\Users\username.sbt\boot\scala-2.12.10\lib\scala-xml_2.12.jar),
  Vector(), Vector(), Vector(), true, false, Vector(), Vector(),
  Some(org.scala-lang), Some(2.11.12), Vector(), Vector(), None,
  Some(C:\Users\ username\AppData\Local\Coursier\cache\v1),
  Some(C:\Users\username.ivy2), None, None, Vector(), Vector(),
  Vector((ModuleMatchers(Set(), Set(), true),Relaxed)), true)) could not
  be retrieved. [error] [error]         Note: Unresolved dependencies
  path: [error]         at
  sbt.internal.inc.ZincLMHelper$.update(ZincComponentCompiler.scala:293)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$3(ZincComponentCompiler.scala:257)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$3$adapted(ZincComponentCompiler.scala:250)
  [error]         at sbt.io.IO$.withTemporaryDirectory(IO.scala:489)
  [error]         at sbt.io.IO$.withTemporaryDirectory(IO.scala:499)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$2(ZincComponentCompiler.scala:250)
  [error]         at
  scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
  [error]         at
  sbt.internal.util.BufferedLogger.bufferQuietly(BufferedLogger.scala:119)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$1(ZincComponentCompiler.scala:250)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compileAndInstall$1$adapted(ZincComponentCompiler.scala:247)
  [error]         at sbt.io.IO$.withTemporaryDirectory(IO.scala:489)
  [error]         at sbt.io.IO$.withTemporaryDirectory(IO.scala:499)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.compileAndInstall(ZincComponentCompiler.scala:247)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.$anonfun$compiledBridgeJar$1(ZincComponentCompiler.scala:215)
  [error]         at
  sbt.internal.inc.IfMissing$Define.run(IfMissing.scala:19) [error]

  at
  sbt.internal.inc.ZincComponentManager.createAndCache$1(ZincComponentManager.scala:49)
  [error]         at
  sbt.internal.inc.ZincComponentManager.$anonfun$files$3(ZincComponentManager.scala:60)
  [error]         at
  sbt.internal.inc.ZincComponentManager.getOrElse$1(ZincComponentManager.scala:42)
  [error]         at
  sbt.internal.inc.ZincComponentManager.$anonfun$files$2(ZincComponentManager.scala:60)
  [error]         at
  sbt.internal.inc.ZincComponentManager$$anon$1.call(ZincComponentManager.scala:89)
  [error]         at
  xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95) [error]

  at
  xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
  [error]         at
  xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
  [error]         at xsbt.boot.Using$.withResource(Using.scala:10)
  [error]         at xsbt.boot.Using$.apply(Using.scala:9) [error]

  at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
  [error]         at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50)
  [error]         at xsbt.boot.Locks$.apply0(Locks.scala:31) [error]

  at xsbt.boot.Locks$.apply(Locks.scala:28) [error]         at
  sbt.internal.inc.ZincComponentManager.lock(ZincComponentManager.scala:89)
  [error]         at
  sbt.internal.inc.ZincComponentManager.$anonfun$lockSecondaryCache$1(ZincComponentManager.scala:86)
  [error]         at scala.Option.map(Option.scala:230) [error]

  at
  sbt.internal.inc.ZincComponentManager.lockSecondaryCache(ZincComponentManager.scala:86)
  [error]         at
  sbt.internal.inc.ZincComponentManager.fromSecondary$1(ZincComponentManager.scala:58)
  [error]         at
  sbt.internal.inc.ZincComponentManager.$anonfun$files$6(ZincComponentManager.scala:64)
  [error]         at
  sbt.internal.inc.ZincComponentManager.getOrElse$1(ZincComponentManager.scala:42)
  [error]         at
  sbt.internal.inc.ZincComponentManager.$anonfun$files$5(ZincComponentManager.scala:64)
  [error]         at
  sbt.internal.inc.ZincComponentManager$$anon$1.call(ZincComponentManager.scala:89)
  [error]         at
  xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95) [error]

  at
  xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
  [error]         at
  xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
  [error]         at xsbt.boot.Using$.withResource(Using.scala:10)
  [error]         at xsbt.boot.Using$.apply(Using.scala:9) [error]

  at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
  [error]         at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50)
  [error]         at xsbt.boot.Locks$.apply0(Locks.scala:31) [error]

  at xsbt.boot.Locks$.apply(Locks.scala:28) [error]         at
  sbt.internal.inc.ZincComponentManager.lock(ZincComponentManager.scala:89)
  [error]         at
  sbt.internal.inc.ZincComponentManager.lockLocalCache(ZincComponentManager.scala:82)
  [error]         at
  sbt.internal.inc.ZincComponentManager.files(ZincComponentManager.scala:64)
  [error]         at
  sbt.internal.inc.ZincComponentManager.file(ZincComponentManager.scala:70)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler.compiledBridgeJar(ZincComponentCompiler.scala:215)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler$ZincCompilerBridgeProvider.compiledBridge(ZincComponentCompiler.scala:75)
  [error]         at
  sbt.internal.inc.ZincComponentCompiler$ZincCompilerBridgeProvider.fetchCompiledBridge(ZincComponentCompiler.scala:81)
  [error]         at
  sbt.internal.inc.AnalyzingCompiler.loader(AnalyzingCompiler.scala:260)
  [error]         at
  sbt.internal.inc.AnalyzingCompiler.getInterfaceClass(AnalyzingCompiler.scala:278)
  [error]         at
  sbt.internal.inc.AnalyzingCompiler.call(AnalyzingCompiler.scala:245)
  [error]         at
  sbt.internal.inc.AnalyzingCompiler.newCachedCompiler(AnalyzingCompiler.scala:145)
  [error]         at
  sbt.internal.inc.AnalyzingCompiler.newCachedCompiler(AnalyzingCompiler.scala:132)
  [error]         at
  sbt.internal.inc.FreshCompilerCache.apply(CompilerCache.scala:102)
  [error]         at
  sbt.internal.inc.AnalyzingCompiler.compile(AnalyzingCompiler.scala:92)
  [error]         at
  sbt.internal.inc.MixedAnalyzingCompiler.$anonfun$compile$4(MixedAnalyzingCompiler.scala:91)
  [error]         at
  scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
  [error]         at
  sbt.internal.inc.MixedAnalyzingCompiler.timed(MixedAnalyzingCompiler.scala:186)
  [error]         at
  sbt.internal.inc.MixedAnalyzingCompiler.$anonfun$compile$3(MixedAnalyzingCompiler.scala:82)
  [error]         at
  sbt.internal.inc.MixedAnalyzingCompiler.$anonfun$compile$3$adapted(MixedAnalyzingCompiler.scala:77)
  [error]         at
  sbt.internal.inc.JarUtils$.withPreviousJar(JarUtils.scala:215) [error]
  at
  sbt.internal.inc.MixedAnalyzingCompiler.compileScala$1(MixedAnalyzingCompiler.scala:77)
  [error]         at
  sbt.internal.inc.MixedAnalyzingCompiler.compile(MixedAnalyzingCompiler.scala:146)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.$anonfun$compileInternal$1(IncrementalCompilerImpl.scala:343)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.$anonfun$compileInternal$1$adapted(IncrementalCompilerImpl.scala:343)
  [error]         at
  sbt.internal.inc.Incremental$.doCompile(Incremental.scala:120) [error]
  at
  sbt.internal.inc.Incremental$.$anonfun$compile$4(Incremental.scala:100)
  [error]         at
  sbt.internal.inc.IncrementalCommon.recompileClasses(IncrementalCommon.scala:180)
  [error]         at
  sbt.internal.inc.IncrementalCommon.cycle(IncrementalCommon.scala:98)
  [error]         at
  sbt.internal.inc.Incremental$.$anonfun$compile$3(Incremental.scala:102)
  [error]         at
  sbt.internal.inc.Incremental$.manageClassfiles(Incremental.scala:155)
  [error]         at
  sbt.internal.inc.Incremental$.compile(Incremental.scala:92) [error]

  at sbt.internal.inc.IncrementalCompile$.apply(Compile.scala:75)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.compileInternal(IncrementalCompilerImpl.scala:348)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.$anonfun$compileIncrementally$1(IncrementalCompilerImpl.scala:301)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.handleCompilationError(IncrementalCompilerImpl.scala:168)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.compileIncrementally(IncrementalCompilerImpl.scala:248)
  [error]         at
  sbt.internal.inc.IncrementalCompilerImpl.compile(IncrementalCompilerImpl.scala:74)
  [error]         at
  sbt.Defaults$.compileIncrementalTaskImpl(Defaults.scala:1762) [error]
  at
  sbt.Defaults$.$anonfun$compileIncrementalTask$1(Defaults.scala:1735)
  [error]         at
  scala.Function1.$anonfun$compose$1(Function1.scala:49) [error]

  at

答:
This issue is fixed.
I have two versions of java 8 running on my local.
After uninstalling the older version, I am able to switch between scala version and run

sbt package

and create jars out of them.


来源: stackexchange

问:
jQuery animate scrollTop doesn't scroll on any browser
Im making a website, when the user clicks on a sort of button of the navbar the entire webpage should scroll to the section containing the information selected by the user.  But it just simply won’t work for some reason. It used to, but something broke.

navbar code:

    Infomratica

```

<p>The section code:</p>

<pre class="lang-html prettyprint-override"><code><section id="section0" class="sezione0">
    <div class="container-fluid" style="text-align: center;">
        <div id="heading" class="row" style="margin-top: 125px;">
            <div class="col-md" style="margin-bottom: 80px;">Infomatica</div>
        </div>
        <div class="row justify-content-center">
            <div class="button" id="button-3">
                <div id="circle"></div><a>Infomatica</a>
            </div>
        </div>
    </div>
</section>
</code>```

The code that should provide the scroll capability is this:

$('a[href*="#"]').on("click", function (e) {

        e.preventDefault();

        let target = $($(this).attr("href"));
        console.log(target.length);

        if (target.length) {
          $('html, body').animate({
            scrollTop: $(target).offset().top
          }, 1000);
        }

      });
```

I've tried all the possibilities, and none of them worked.

Do you have any idea of what caused it, and how to fix it ?

EDIT:

I have imported jQuery

答:
Have a look at the updated javascript for the scrolling effect.

You will unable to select element with attr() method. For this, you will need to use $(this). Also, I have added the temporary UL style for demo. you can remove it while implementation.

$('a[href*="#"]').on("click", function (e) {
    e.preventDefault();
    let target = $(this);
    console.log(target.length);

    if (target.length) {
        $('html, body').animate({
           scrollTop: $($(this).attr("href")).offset().top
        }, 1000);
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
height:100vh;
}</code>```

    Infomratica

Infomatica

Infomatica

```

ContentLicense: CC BY-SA 4.0

Body:
Im making a website, when the user clicks on a sort of button of the navbar the entire webpage should scroll to the section containing the information selected by the user.  But it just simply won’t work for some reason. It used to, but something broke.

navbar code:

    Infomratica

The section code:

Infomatica

Infomatica

The code that should provide the scroll capability is this:

$('a[href*="#"]').on("click", function (e) {

        e.preventDefault();

        let target = $($(this).attr("href"));
        console.log(target.length);

        if (target.length) {
          $('html, body').animate({
            scrollTop: $(target).offset().top
          }, 1000);
        }

      });

I've tried all the possibilities, and none of them worked.

Do you have any idea of what caused it, and how to fix it ?

EDIT:

I have imported jQuery

Body:
Have a look at the updated javascript for the scrolling effect.

You will unable to select element with attr() method. For this, you will need to use $(this). Also, I have added the temporary UL style for demo. you can remove it while implementation.

$('a[href*="#"]').on("click", function (e) {
    e.preventDefault();
    let target = $(this);
    console.log(target.length);

    if (target.length) {
        $('html, body').animate({
           scrollTop: $($(this).attr("href")).offset().top
        }, 1000);
    }
});

ul{
height:100vh;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="outJS">
 <li>
   <a href="#section0"> Infomratica </a>
 </li>
</ul>

<section id="section0" class="sezione0">
    <div class="container-fluid" style="text-align: center;">
        <div id="heading" class="row" style="margin-top: 125px;">
            <div class="col-md" style="margin-bottom: 80px;">Infomatica</div>
        </div>
        <div class="row justify-content-center">
            <div class="button" id="button-3">
                <div id="circle"></div><a>Infomatica</a>
            </div>
        </div>
    </div>
</section>


问:
How does ios::fmtflags works in C++?How setf() works?
I am trying to understand formatted flags of ios stream. Can anyone please explain how this cout.setf(ios::hex | ios::showbase) thing works? I mean how does the or (|) operator work between the two ios formatted flags?
Please pardon me for my bad english.

答:
std::ios_base::hex and std::ios_base::showbase are both enumerators of the BitmaskType std::ios_base::fmtflags.  A BitmaskType is typically an enumeration type whose enumerators are distinct powers of two, kinda like this: (1 << n means 2n)

```<code>// simplified; can also be implemented with integral types, std::bitset, etc.
enum fmtflags : unsigned {
    dec      = 1 << 0, // 1
    oct      = 1 << 1, // 2
    hex      = 1 << 2, // 4
    // ...
    showbase = 1 << 9, // 512
    // ...
};
</code>```

The | operator is the bit-or operator, which performs the or operation on the corresponding bits, so

hex             0000 0000 0000 0100
showbase        0000 0010 0000 0000
                -------------------
hex | showbase  0000 0010 0000 0100
```

This technique can be used to combine flags together, so every bit in the bitmask represents a separate flag (set or unset).  Then, each flag can be

queried: mask & flag;

set: mask | flag;

unset: mask & (~flag).

Body:
std::ios_base::hex and std::ios_base::showbase are both enumerators of the BitmaskType std::ios_base::fmtflags.  A BitmaskType is typically an enumeration type whose enumerators are distinct powers of two, kinda like this: (1 << n means 2n)

// simplified; can also be implemented with integral types, std::bitset, etc.
enum fmtflags : unsigned {
    dec      = 1 << 0, // 1
    oct      = 1 << 1, // 2
    hex      = 1 << 2, // 4
    // ...
    showbase = 1 << 9, // 512
    // ...
};

The | operator is the bit-or operator, which performs the or operation on the corresponding bits, so

hex             0000 0000 0000 0100
showbase        0000 0010 0000 0000
                -------------------
hex | showbase  0000 0010 0000 0100

This technique can be used to combine flags together, so every bit in the bitmask represents a separate flag (set or unset).  Then, each flag can be

queried: mask & flag;

set: mask | flag;

unset: mask & (~flag).


问:
Many to many relationship with the same entity in Entity Framework Core
When I implement many-to-many relationship between two classes, and configure its composite primary key using fluent api, then instead of creating 2 columns in the database, EF Core creates three columns.

UserReport.cs

```<code>public class UserReports
{
    public int ReporterId { get; set; }
    public User Reporter { get; set; }

    public int ReporteeId { get; set; }
    public User Reportee { get; set; }
}
</code>```

User.cs

```<code>public class User: IdentityUser<int>
{
    public DateTime DateOfBirth { get; set; }
    public string KnownAs { get; set; }
    public DateTime Created { get; set; }
    public DateTime LastActive { get; set; }

    public ICollection<UserReports> Reporters { get; set; } = new Collection<UserReports>();
    public ICollection<UserReports> Reportees { get; set; } = new Collection<UserReports>();
}
</code>```

ApplicatiobDbContext.cs

```<code>modelBuilder.Entity<UserReports>()
   .HasKey(ru => new { ru.ReporterId, ru.ReporteeId});

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reportee)
   .WithMany(u => u.Reporters)
   .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reporter)
   .WithMany(u => u.Reportees)
   .OnDelete(DeleteBehavior.Restrict);
</code>```

Migration

After the adding the migrations the EF core generating this type of migration, which is creating an extra columns

```<code>ReporterId1 = table.Column<int>(nullable: true)

migrationBuilder.CreateTable(
        name: "ReportUsers",
        columns: table => new
        {
           ReporterId = table.Column<int>(nullable: false),
           ReporteeId = table.Column<int>(nullable: false),
           ReporterId1 = table.Column<int>(nullable: true),
           Message = table.Column<string>(nullable: false)
        },
</code>```

答:
You are missing the mention of HasForeignKey in your configuration that's why the confusion for mapping the foreign key has been arisen as it is many-to-many with same the entity. Update your configuration as follows:

```<code>modelBuilder.Entity<UserReports>()
   .HasKey(ru => new { ru.ReporterId, ru.ReporteeId});

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reportee)
   .WithMany(u => u.Reporters)
   .HasForeignKey(ru => ru.ReporteeId); // <-- Here it is
   .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reporter)
   .WithMany(u => u.Reportees)
   .HasForeignKey(ru => ru.ReporterId); // <-- Here it is
   .OnDelete(DeleteBehavior.Restrict);
</code>```

Body:
When I implement many-to-many relationship between two classes, and configure its composite primary key using fluent api, then instead of creating 2 columns in the database, EF Core creates three columns.

UserReport.cs

public class UserReports
{
    public int ReporterId { get; set; }
    public User Reporter { get; set; }

    public int ReporteeId { get; set; }
    public User Reportee { get; set; }
}

User.cs

public class User: IdentityUser<int>
{
    public DateTime DateOfBirth { get; set; }
    public string KnownAs { get; set; }
    public DateTime Created { get; set; }
    public DateTime LastActive { get; set; }

    public ICollection<UserReports> Reporters { get; set; } = new Collection<UserReports>();
    public ICollection<UserReports> Reportees { get; set; } = new Collection<UserReports>();
}

ApplicatiobDbContext.cs

modelBuilder.Entity<UserReports>()
   .HasKey(ru => new { ru.ReporterId, ru.ReporteeId});

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reportee)
   .WithMany(u => u.Reporters)
   .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reporter)
   .WithMany(u => u.Reportees)
   .OnDelete(DeleteBehavior.Restrict);

Migration

After the adding the migrations the EF core generating this type of migration, which is creating an extra columns

ReporterId1 = table.Column<int>(nullable: true)

migrationBuilder.CreateTable(
        name: "ReportUsers",
        columns: table => new
        {
           ReporterId = table.Column<int>(nullable: false),
           ReporteeId = table.Column<int>(nullable: false),
           ReporterId1 = table.Column<int>(nullable: true),
           Message = table.Column<string>(nullable: false)
        },

Body:
You are missing the mention of HasForeignKey in your configuration that's why the confusion for mapping the foreign key has been arisen as it is many-to-many with same the entity. Update your configuration as follows:

modelBuilder.Entity<UserReports>()
   .HasKey(ru => new { ru.ReporterId, ru.ReporteeId});

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reportee)
   .WithMany(u => u.Reporters)
   .HasForeignKey(ru => ru.ReporteeId); // <-- Here it is
   .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reporter)
   .WithMany(u => u.Reportees)
   .HasForeignKey(ru => ru.ReporterId); // <-- Here it is
   .OnDelete(DeleteBehavior.Restrict);


问:
Import library from specific branch via variable in Jenkinsfile
I want to load shared-library implicity, and not dynamically, in Jenkinsfile, but select specific branch from per variable for shared-library.
For testing purpose, I tried to insert variable in @library statement per properties variable. It works, if I write the branch name directly inside.

```<code>#!/usr/bin/env groovy
properties([
    stringParam(name: 'BRANCH_NAME', defaultValue: 'master')
  ])
])

@Library("custom-shared-library@${params.BRANCH_NAME}")

import com.custom.test.utils.*

println("hello world!")
</code>```

Got following error message:

```<code>WorkflowScript: @Library value ‘custom-shared-library@$params.BRANCH_NAME’ was not a constant; did you mean to use the ‘library’ step instead?

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:131)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:125)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:560)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:521)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:319)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
</code>```

Is it possible to insert variable in @library() statement?

答:
For the scripted pipeline see the docs at  https://jenkins.io/doc/book/pipeline/shared-libraries/#loading-libraries-dynamically

```<code>properties([parameters([string(name: 'LIB_VERSION', defaultValue: 'master')])])
library "my-shared-library@${params.LIB_VERSION}"
</code>```

for the declarative pipeline use libraries directive like described here https://github.com/cloudbees/intro-to-declarative-pipeline/blob/master/Exercise-04.md

```<code>libraries {
  lib("my-shared-library@${params.LIB_VERSION}")
}
</code>```

The libraries directive was added in the version 1.1 of the pipeline model definition plugin. But for some reason I don't see it in the pipeline syntax documentation.

Body:
I want to load shared-library implicity, and not dynamically, in Jenkinsfile, but select specific branch from per variable for shared-library.
For testing purpose, I tried to insert variable in @library statement per properties variable. It works, if I write the branch name directly inside.

#!/usr/bin/env groovy
properties([
    stringParam(name: 'BRANCH_NAME', defaultValue: 'master')
  ])
])

@Library("custom-shared-library@${params.BRANCH_NAME}")

import com.custom.test.utils.*

println("hello world!")

Got following error message:

WorkflowScript: @Library value ‘custom-shared-library@$params.BRANCH_NAME’ was not a constant; did you mean to use the ‘library’ step instead?

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:131)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:125)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:560)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:521)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:319)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

Is it possible to insert variable in @library() statement?

Body:
For the scripted pipeline see the docs at  https://jenkins.io/doc/book/pipeline/shared-libraries/#loading-libraries-dynamically

properties([parameters([string(name: 'LIB_VERSION', defaultValue: 'master')])])
library "my-shared-library@${params.LIB_VERSION}"

for the declarative pipeline use libraries directive like described here https://github.com/cloudbees/intro-to-declarative-pipeline/blob/master/Exercise-04.md

libraries {
  lib("my-shared-library@${params.LIB_VERSION}")
}

The libraries directive was added in the version 1.1 of the pipeline model definition plugin. But for some reason I don't see it in the pipeline syntax documentation.


问:
PHP Constant Conventions
Greetings StackOverflow

I'm doing some house cleaning and thought I would ask for some suggested practices in PHP as I re-factor my classes.  In particular, I have some class constants which fall into categories and I would like to know some good ways to group the ones which share a common purpose.

An Example:

```<code>class MySquare {
  // Colors
  const COLOR_GREEN = "green";
  const COLOR_RED = "red";

  // Widths
  const WIDTH_SMALL = 100;
  const WIDTH_MEDIUM = 500;
  const WIDTH_BIG = 1000;

  // Heights
  const HEIGHT_SMALL = 100;
  const HEIGHT_MEDIUM = 300;
  const HEIGHT_BIG = 500;
}
</code>```

Obviously this works, but it seems like there are probably plenty of options when it comes to grouping related constants, and I bet this is inferior to most.  How would you do it?

答:
There are many PHP Conventions, and all of them contradict. But I do use a similar notation, although I like to group the constants per class, so I would have a class
Height (or MySquare_Height) which has the constants. This way, I can use it as a kind of Enum like you got in other languages. Especially when you use an editor with highlighting.

```<code><?
abstract class MySquare_Color
{
  const GREEN = 'Green';
  const RED = 'Red';
}

abstract class MySquare_Height
{
  const SMALL = 100;
  const MEDIUM = 300;
  const BIG = 500;
}
</code>```

If you'r using PHP 5.3, you can just name the classes Color and Height and put them in a MySquare namespace:

```<code><?php
// Namespace MySquare with subnamespace Width containing the constants.
namespace MySquare\Width
{
    const SMALL = 100;
    const MEDIUM = 300;
}

namespace
{
  // Refer to it fromout another namespace
  echo MySquare\Width\SMALL;
}

?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP Constant Conventions

Body:
Greetings StackOverflow

I'm doing some house cleaning and thought I would ask for some suggested practices in PHP as I re-factor my classes.  In particular, I have some class constants which fall into categories and I would like to know some good ways to group the ones which share a common purpose.

An Example:

class MySquare {
  // Colors
  const COLOR_GREEN = "green";
  const COLOR_RED = "red";

  // Widths
  const WIDTH_SMALL = 100;
  const WIDTH_MEDIUM = 500;
  const WIDTH_BIG = 1000;

  // Heights
  const HEIGHT_SMALL = 100;
  const HEIGHT_MEDIUM = 300;
  const HEIGHT_BIG = 500;
}

Obviously this works, but it seems like there are probably plenty of options when it comes to grouping related constants, and I bet this is inferior to most.  How would you do it?

Body:
There are many PHP Conventions, and all of them contradict. But I do use a similar notation, although I like to group the constants per class, so I would have a class
Height (or MySquare_Height) which has the constants. This way, I can use it as a kind of Enum like you got in other languages. Especially when you use an editor with highlighting.

<?
abstract class MySquare_Color
{
  const GREEN = 'Green';
  const RED = 'Red';
}

abstract class MySquare_Height
{
  const SMALL = 100;
  const MEDIUM = 300;
  const BIG = 500;
}

If you'r using PHP 5.3, you can just name the classes Color and Height and put them in a MySquare namespace:

<?php
// Namespace MySquare with subnamespace Width containing the constants.
namespace MySquare\Width
{
    const SMALL = 100;
    const MEDIUM = 300;
}

namespace
{
  // Refer to it fromout another namespace
  echo MySquare\Width\SMALL;
}

?>


问:
Why does sending data between activities not work?
I am currently using Kotlin. I am trying to change the colour of a box in main activity by going to another activity that is the colour setting activity. My code returns no errors but not working. I tried reading different result on this page but none answering my question. Thank u for your help.

mainactivity.kt

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button_box = findViewById<Button>(R.id.button_box)

        button_box.setOnClickListener {
            val intent = Intent(this, boxColor::class.java)
            startActivity(intent)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

            if (resultCode == RESULT_OK) {

                val returnColor = data!!.getStringExtra("colorName")

                val boxColorChoice = when (returnColor) {
                    "green" -> R.drawable.box_green
                    "grey" -> R.drawable.box_grey
                    "lblue" -> R.drawable.box_lblue
                    "purple" -> R.drawable.box_purple
                    "red" -> R.drawable.box_red
                    "white" -> R.drawable.box_white
                    "yellow" -> R.drawable.box_yellow
                    else -> R.drawable.box_white
                }
                button_box.setBackgroundResource(boxColorChoice)
            }
        }
</code>```

here is boxcolor.kt

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_box_color)

        val green = findViewById<Button>(R.id.green_box)
        val red = findViewById<Button>(R.id.red_box)
        val white = findViewById<Button>(R.id.white_box)
        val yellow = findViewById<Button>(R.id.yellow_box)
        val grey = findViewById<Button>(R.id.grey_box)
        val lblue = findViewById<Button>(R.id.lblue_box)

        green.setOnClickListener {
            val intent = Intent()
            intent.putExtra("colorName", "green")
            setResult(Activity.RESULT_OK, intent)
            finish()
        }

     (and the same onclicklistener for all the other colours)

</code>```

also I know this is small problem but thank you very much for helping. I am 14 year old boy from rajasthan and I want to be a programmer and learning

答:
Please use Request Code and startActivityForResult

Example:

private val RC = 101

val intent = Intent(this, boxColor::class.java)

startActivityForResult(intent, RC)

Body:
I am currently using Kotlin. I am trying to change the colour of a box in main activity by going to another activity that is the colour setting activity. My code returns no errors but not working. I tried reading different result on this page but none answering my question. Thank u for your help.

mainactivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button_box = findViewById<Button>(R.id.button_box)

        button_box.setOnClickListener {
            val intent = Intent(this, boxColor::class.java)
            startActivity(intent)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

            if (resultCode == RESULT_OK) {

                val returnColor = data!!.getStringExtra("colorName")

                val boxColorChoice = when (returnColor) {
                    "green" -> R.drawable.box_green
                    "grey" -> R.drawable.box_grey
                    "lblue" -> R.drawable.box_lblue
                    "purple" -> R.drawable.box_purple
                    "red" -> R.drawable.box_red
                    "white" -> R.drawable.box_white
                    "yellow" -> R.drawable.box_yellow
                    else -> R.drawable.box_white
                }
                button_box.setBackgroundResource(boxColorChoice)
            }
        }

here is boxcolor.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_box_color)

        val green = findViewById<Button>(R.id.green_box)
        val red = findViewById<Button>(R.id.red_box)
        val white = findViewById<Button>(R.id.white_box)
        val yellow = findViewById<Button>(R.id.yellow_box)
        val grey = findViewById<Button>(R.id.grey_box)
        val lblue = findViewById<Button>(R.id.lblue_box)

        green.setOnClickListener {
            val intent = Intent()
            intent.putExtra("colorName", "green")
            setResult(Activity.RESULT_OK, intent)
            finish()
        }

     (and the same onclicklistener for all the other colours)

also I know this is small problem but thank you very much for helping. I am 14 year old boy from rajasthan and I want to be a programmer and learning


问:
2 divs inline side by side and one can be grow when one in invisible
Please consider this image:

I can create such these divs but the problem is when one of these divs being invisible other can fill entire line.

How can i do this?

```<code><div id="container">
   <div id="left"> left</div>
   <div id="right"> right</div>
</div>
</code>```

CSS:

```<code>#left {
   background: #aaa;
   display: inline-block;
   width: 49%;
}

#right {
   background: cyan;
   display: inline-block;
   width: 49%;
}

#container {
  background: red;
  width: 100%
}
</code>```

Demo: https://jsfiddle.net/ynuL2za5/

答:
You can achieve this with display: flex, making each div flex-grow:1  to fill the parent container. I have added a button to demonstrate that when the left div is hidden (by adding a hidden class) - that allows the right side to expand to fill the container.

var leftDiv = document.querySelector('#left-div');
function toggleDiv(){
 leftDiv.classList.toggle('hidden');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
display: flex;
}

.wrapper div {
 flex-grow: 1;

 height: 300px;
}

#left-div { background: lime;}
#right-div { background: aqua;}

.hidden {display: none}</code>```

<button type="button" onclick="toggleDiv()"> Toggle left Div </button>

 Lorem ipsum left

 Lorem ipsum right

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

<p>Conversely if the right side is hidden - the left will fill the container .</p>

<p><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 rightDiv = document.querySelector('#right-div');
function toggleDiv(){
 rightDiv.classList.toggle('hidden');
}</code>```

.wrapper {
display: flex;
}

.wrapper div {
 flex-grow: 1;

 height: 300px;
}

#left-div { background: lime;}
#right-div { background: aqua;}

.hidden {display: none}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="toggleDiv()"> Toggle right Div </button>

<hr/>

<div class="wrapper">
 <div id="left-div"> Lorem ipsum left</div>
 <div id="right-div"> Lorem ipsum right</div>
</div></code>```

Body:
Please consider this image:

I can create such these divs but the problem is when one of these divs being invisible other can fill entire line.

How can i do this?

 left

 right

CSS:

#left {
   background: #aaa;
   display: inline-block;
   width: 49%;
}

#right {
   background: cyan;
   display: inline-block;
   width: 49%;
}

#container {
  background: red;
  width: 100%
}

Demo: https://jsfiddle.net/ynuL2za5/

Body:
You can achieve this with display: flex, making each div flex-grow:1  to fill the parent container. I have added a button to demonstrate that when the left div is hidden (by adding a hidden class) - that allows the right side to expand to fill the container.

var leftDiv = document.querySelector('#left-div');
function toggleDiv(){
 leftDiv.classList.toggle('hidden');
}

.wrapper {
display: flex;
}

.wrapper div {
 flex-grow: 1;

 height: 300px;
}

#left-div { background: lime;}
#right-div { background: aqua;}

.hidden {display: none}

<button type="button" onclick="toggleDiv()"> Toggle left Div </button>

<hr/>

<div class="wrapper">
 <div id="left-div"> Lorem ipsum left</div>
 <div id="right-div"> Lorem ipsum right</div>
</div>

Conversely if the right side is hidden - the left will fill the container .

var rightDiv = document.querySelector('#right-div');
function toggleDiv(){
 rightDiv.classList.toggle('hidden');
}

.wrapper {
display: flex;
}

.wrapper div {
 flex-grow: 1;

 height: 300px;
}

#left-div { background: lime;}
#right-div { background: aqua;}

.hidden {display: none}

<button type="button" onclick="toggleDiv()"> Toggle right Div </button>

<hr/>

<div class="wrapper">
 <div id="left-div"> Lorem ipsum left</div>
 <div id="right-div"> Lorem ipsum right</div>
</div>


答:
you need to use startActivityForResult your code must change to these :

mainactivity.kt

```<code>...
val mRequestCode = 101  //ADD THIS LINE
...
button_box.setOnClickListener {
            val intent = Intent(this, boxColor::class.java)
            startActivityForResult(intent, mRequestCode) //ADD THIS LINE
        }
...
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

            if (resultCode == mRequestCode) { //CHANGE THIS LINE
                ...
            }
        }
</code>```

and in your   boxcolor.kt:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_box_color)
        val mRequestCode = 101  //ADD THIS LINE

        ...

        green.setOnClickListener {
            val intent = Intent()
            intent.putExtra("colorName", "green")
            setResult(mRequestCode, intent)  //CHANGE THIS LINE
            finish()
        }

     (and the same onclicklistener for all the other colours)
</code>```

Note that don't use Activity.RESULT_OK as requestCode

Title: Why does sending data between activities not work?

Body:
you need to use startActivityForResult your code must change to these :

mainactivity.kt

...
val mRequestCode = 101  //ADD THIS LINE
...
button_box.setOnClickListener {
            val intent = Intent(this, boxColor::class.java)
            startActivityForResult(intent, mRequestCode) //ADD THIS LINE
        }
...
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

            if (resultCode == mRequestCode) { //CHANGE THIS LINE
                ...
            }
        }

and in your   boxcolor.kt:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_box_color)
        val mRequestCode = 101  //ADD THIS LINE

        ...

        green.setOnClickListener {
            val intent = Intent()
            intent.putExtra("colorName", "green")
            setResult(mRequestCode, intent)  //CHANGE THIS LINE
            finish()
        }

     (and the same onclicklistener for all the other colours)

Note that don't use Activity.RESULT_OK as requestCode


答:
I would recommend you use display: flex

CSS:

```<code>#container {
  display: flex;
  background: red;
  width: 100%;
  height: 300px; // <== as per your requirement
}

#left, #right {
  flex: 1   // <= to make them take equal space in container
}

#left {
   background: #aaa;
}

#right {
   background: cyan;
}
</code>```

Now if any of div is hidden display:none the other one will automatically span to take up full available width to fill container space.

Also for better performance, I would recommend you to use classes instead of id.

Title: 2 divs inline side by side and one can be grow when one in invisible

Body:
I would recommend you use display: flex

CSS:

#container {
  display: flex;
  background: red;
  width: 100%;
  height: 300px; // <== as per your requirement
}

#left, #right {
  flex: 1   // <= to make them take equal space in container
}

#left {
   background: #aaa;
}

#right {
   background: cyan;
}

Now if any of div is hidden display:none the other one will automatically span to take up full available width to fill container space.

Also for better performance, I would recommend you to use classes instead of id.


问:
why i'm getting Run time exception while cloning an object in java
I'm trying to perform shallow cloning of an object My dog class has a primitive variable i=10 and also a reference variable point to an object  j=20 and also I define a clone method as public however I'm getting a runtime error saying Exception in thread "main" java.lang.CloneNotSupportedException

```<code>package com.objectclasscoding.practice;

import com.objectclasscoding.practice.Cat.Dog;

class Cat {
    int j;

    public Cat(int j) {

        this.j = j;
    }

    class Dog implements Cloneable {
        Cat c;
        int i;

        public Dog(Cat c, int i) {
            this.c = c;
            this.i = i;
        }

    }

    public Object clone() throws CloneNotSupportedException {
        return (Dog) super.clone();
    }
}

public class ShallowCloningDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        Cat c = new Cat(20);
        Dog d1 = c.new Dog(c, 10);
        System.out.println(d1.i + ".." + c.j);

        Dog d2 = (Dog) d1.c.clone();
        d1.i = 888;
        d1.c.j = 999;
        System.out.println(d2.i + ".." + d2.c.j);

    }

}
</code>```

After running this code I'm getting runtime error saying Exception in thread "main" java.lang.CloneNotSupportedException

答:
You seem to be calling clone on d1.c, an instance of Cat, which does not implement Cloneable.

For some reason you've added a clone() method to Cat rather than Dog. Inside that method, you tried to cast the result to Dog, as if a cloned Cat would be an instance of Dog. That does not make sense. Cats are notoriously not the same as dogs.

Body:
I'm trying to perform shallow cloning of an object My dog class has a primitive variable i=10 and also a reference variable point to an object  j=20 and also I define a clone method as public however I'm getting a runtime error saying Exception in thread "main" java.lang.CloneNotSupportedException

package com.objectclasscoding.practice;

import com.objectclasscoding.practice.Cat.Dog;

class Cat {
    int j;

    public Cat(int j) {

        this.j = j;
    }

    class Dog implements Cloneable {
        Cat c;
        int i;

        public Dog(Cat c, int i) {
            this.c = c;
            this.i = i;
        }

    }

    public Object clone() throws CloneNotSupportedException {
        return (Dog) super.clone();
    }
}

public class ShallowCloningDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        Cat c = new Cat(20);
        Dog d1 = c.new Dog(c, 10);
        System.out.println(d1.i + ".." + c.j);

        Dog d2 = (Dog) d1.c.clone();
        d1.i = 888;
        d1.c.j = 999;
        System.out.println(d2.i + ".." + d2.c.j);

    }

}

After running this code I'm getting runtime error saying Exception in thread "main" java.lang.CloneNotSupportedException


问:
Add rows to UITableView when scrolled to bottom
Is there a way to trigger an event, such as with an IBAction, when a user scrolls to the bottom of a UITableView? I would like to add more rows if this happens. How do I do this?

答: I'm not sure why you'd want to do this, but I imagine you could add some code to your cellForRowAtIndexPath method so that if indexPath.row == the last row, call the method to add more rows...


问:
Laravel Route Model Binding Reusability
I'm creating a like feature for my application where users can like posts, events, products etc.

I have a LikeController and a Trait which handles the like functionality

```<code>public function store(Post $post)
{
    $post->like();
    return back();
}
</code>```

The code above is to like a post

I don't want to duplicate code and create separate functions to perfrom the same exact thing on events or products and I was wondering how to perform route model binding and get the application to just execute the one function, passing model information depending on what is being liked post, event or product.

The following code works fine but does not implement the DRY principle

```<code>public function store(Post $post)
{
    $post->like();
    return back();
}

public function store_event(Event $event)
{
    $event->like();
    return back();
}
</code>```

The followinf is the trait

```<code>trait LikeTrait
{

    public function getLikesCountAtrribute()
    {
        return $this->likes->count();
    }

    public function like()
    {
        if (!$this->likes()->where(['user_id' => auth()->id()])->exists()) {
            $this->likes()->create(['user_id' => auth()->id()]);
        }
    }

    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable');
    }

    public function isLiked()
    {
        return !!$this->likes->where('user_id', auth()->id())->count();
    }
}
</code>```

My web routes file is as follows

```<code>Route::post('post/{post}/likes', 'LikeController@store');
Route::post('event/{event}/likes', 'LikeController@store_event');
</code>```

So the outcome I want is to call the same method and pass the relevant model.

Thanks in advance

答:
I don't know whether this is gonna work, but please have a go.

You could try explicit binding. Lets define explicit bindings in the App\Providers\RouteServiceProvider:

```<code>public function boot()
{
    parent::boot();

    Route::model('post', App\Post::class);

    Route::model('event', App\Event::class);
}
</code>```

Then defining the routes:

```<code>Route::post('/posts/{post}/likes', 'LikesController@store');
Route::post('/events/{event}/likes', 'LikesController@store');
</code>```

Finally in the controller:

```<code>class LikesController extends Controller
{
    public function store($object)
    {
        $object->like();
    }
}
</code>```

Title: Laravel Route Model Binding Reusability

Body:
I'm creating a like feature for my application where users can like posts, events, products etc.

I have a LikeController and a Trait which handles the like functionality

public function store(Post $post)
{
    $post->like();
    return back();
}

The code above is to like a post

I don't want to duplicate code and create separate functions to perfrom the same exact thing on events or products and I was wondering how to perform route model binding and get the application to just execute the one function, passing model information depending on what is being liked post, event or product.

The following code works fine but does not implement the DRY principle

public function store(Post $post)
{
    $post->like();
    return back();
}

public function store_event(Event $event)
{
    $event->like();
    return back();
}

The followinf is the trait

trait LikeTrait
{

    public function getLikesCountAtrribute()
    {
        return $this->likes->count();
    }

    public function like()
    {
        if (!$this->likes()->where(['user_id' => auth()->id()])->exists()) {
            $this->likes()->create(['user_id' => auth()->id()]);
        }
    }

    public function likes()
    {
        return $this->morphMany(Like::class, 'likeable');
    }

    public function isLiked()
    {
        return !!$this->likes->where('user_id', auth()->id())->count();
    }
}

My web routes file is as follows

Route::post('post/{post}/likes', 'LikeController@store');
Route::post('event/{event}/likes', 'LikeController@store_event');

So the outcome I want is to call the same method and pass the relevant model.

Thanks in advance

Body:
I don't know whether this is gonna work, but please have a go.

You could try explicit binding. Lets define explicit bindings in the App\Providers\RouteServiceProvider:

public function boot()
{
    parent::boot();

    Route::model('post', App\Post::class);

    Route::model('event', App\Event::class);
}

Then defining the routes:

Route::post('/posts/{post}/likes', 'LikesController@store');
Route::post('/events/{event}/likes', 'LikesController@store');

Finally in the controller:

class LikesController extends Controller
{
    public function store($object)
    {
        $object->like();
    }
}


问:
Flutter firebase messaging push notification format 3 lines
I am working on firebase push notification for my project. I am receiving notification on all my devices.

My problem is iOS devices showing notifications in below format.

```<code>Title  :
Subtitle :
text/body:
</code>```

My android devices showing notifications in below format.

```<code>Title :
text/body:
</code>```

below is the payload i am using for sending notification.

```<code> var payload = {   "notification":{
          "title":"New Price Alert! "+ clientDataAfter.productname,
"subtitle":"Get before its gone",
          "body":"Old Price "+clientDataAfter.oldprice+" || New Price "+ clientDataAfter.newprice,
          "click_action":"FLUTTER_NOTIFICATION_CLICK",
        },
        "data" : {
          "id":ID,
          "name": Name,
          "newprice":newprice
        }, }
</code>```

I want to show notifications in 3 line format on both iOS and android.
How can i achieve this?

Thanks in advance.

答: Add "subtitle" to "data" with "id", "name", ...</p>

Body:
I am working on firebase push notification for my project. I am receiving notification on all my devices.

My problem is iOS devices showing notifications in below format.

Title  :
Subtitle :
text/body:

My android devices showing notifications in below format.

Title :
text/body:

below is the payload i am using for sending notification.

 var payload = {   "notification":{
          "title":"New Price Alert! "+ clientDataAfter.productname,
"subtitle":"Get before its gone",
          "body":"Old Price "+clientDataAfter.oldprice+" || New Price "+ clientDataAfter.newprice,
          "click_action":"FLUTTER_NOTIFICATION_CLICK",
        },
        "data" : {
          "id":ID,
          "name": Name,
          "newprice":newprice
        }, }

I want to show notifications in 3 line format on both iOS and android.
How can i achieve this?

Thanks in advance.


问:
How to check for the existence of values after splitting in object, and then assign them if only the last one does not exist
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

```<code>for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/
</code>```

that is, each scroll is added as long as i is less than the length of the array
it should work like this

```<code>obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};
</code>```

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5

答:
I'm not sure why you really need to check if nested property already exists, because it certainly won't be in an empty object, so I avoided this check.

const buildObjectFromPath = splitter => path => {
  path = path.split(splitter)
  const obj = {}
  let current = obj
  for (const prop of path) {
    current = current[prop] = {}
  }
  return obj
}

const path = 'a1/b1/c1/d1'
console.log(buildObjectFromPath('/')(path))```

:)

Body:
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/

that is, each scroll is added as long as i is less than the length of the array
it should work like this

obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5

Body:
I'm not sure why you really need to check if nested property already exists, because it certainly won't be in an empty object, so I avoided this check.

const buildObjectFromPath = splitter => path => {
  path = path.split(splitter)
  const obj = {}
  let current = obj
  for (const prop of path) {
    current = current[prop] = {}
  }
  return obj
}

const path = 'a1/b1/c1/d1'
console.log(buildObjectFromPath('/')(path))

:)


问:
How to mock Files.copy method in JUnit
I am using some of the methods of Files class like (delete, copy methods) to do upload and delete of file. Below is the code to perform these operations.

```<code>public String uploadFile(MultipartFile file) {
    try {
    String fileName = file.getOriginalFilename()
        // Copy file to the target location (Replacing existing file with the same name)
        Path targetLocation = Paths.get("uploadPath" + File.separator + StringUtils.cleanPath(fileName));
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Not able to upload", ex);
    }
}
</code>```

But for this source code I am not able to write JUnit tests because not able to mock Files class. For mocking final classes we can use PowerMock which supports to mock static and final methods. But here if I do using PowerMock still it is not mocking. I am using Spring Framework 5.2.1.RELEASE , Is there any change in JUnit with this version to mock final classes or methods? Or can any one help me on writing the unit tests for this code (versions I am using Spring Framework 5.2.1 and JUnit4.12).

答:
Mocking static and final classes is indeed possible only with tools like PowerMock or PowerMockito, and its not related to JUnit or Spring frameworks.

I think you should not Mock Files.copy operation.
Instead consider the following strategy:

Define an interface for working with files, a kind of DAO but for file system:

```<code>public interface FileSystemDAO {
   void copy(InputStream is, Path target, StandardCopyOption ... options);
}

public class FileSystemDAOImpl implements FileSystemDAO {
    void copy(InputStream is, Path target, StandatadCopyOption ... options) {
      Files.copy(...)
    }
}

</code>```

Now use dependency injection in all the places that work with files (if you're using spring as you've said - define FileSystemDAOImpl as a bean).

```<code>class MySampleUploadService {

 private final FileSystemDAO fileSystemDao;

 public MySampleUploadService(FileSystemDAO dao) {
      this.fileSystemDao = dao;
 }
 public String uploadFile(MultipartFile file) {
     try {
     String fileName = file.getOriginalFilename()
         // Copy file to the target location (Replacing existing file with the same name)
         Path targetLocation = Paths.get("uploadPath" + File.separator +
 StringUtils.cleanPath(fileName));
         fileSystemDao.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Not able to upload", ex);
    }
 }

}
</code>```

Now with this approach you can easily test the Upload service by mocking the FileSystemDao interface.

Title: How to mock Files.copy method in JUnit

Body:
I am using some of the methods of Files class like (delete, copy methods) to do upload and delete of file. Below is the code to perform these operations.

public String uploadFile(MultipartFile file) {
    try {
    String fileName = file.getOriginalFilename()
        // Copy file to the target location (Replacing existing file with the same name)
        Path targetLocation = Paths.get("uploadPath" + File.separator + StringUtils.cleanPath(fileName));
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Not able to upload", ex);
    }
}

But for this source code I am not able to write JUnit tests because not able to mock Files class. For mocking final classes we can use PowerMock which supports to mock static and final methods. But here if I do using PowerMock still it is not mocking. I am using Spring Framework 5.2.1.RELEASE , Is there any change in JUnit with this version to mock final classes or methods? Or can any one help me on writing the unit tests for this code (versions I am using Spring Framework 5.2.1 and JUnit4.12).

Body:
Mocking static and final classes is indeed possible only with tools like PowerMock or PowerMockito, and its not related to JUnit or Spring frameworks.

I think you should not Mock Files.copy operation.
Instead consider the following strategy:

Define an interface for working with files, a kind of DAO but for file system:

public interface FileSystemDAO {
   void copy(InputStream is, Path target, StandardCopyOption ... options);
}

public class FileSystemDAOImpl implements FileSystemDAO {
    void copy(InputStream is, Path target, StandatadCopyOption ... options) {
      Files.copy(...)
    }
}

Now use dependency injection in all the places that work with files (if you're using spring as you've said - define FileSystemDAOImpl as a bean).

class MySampleUploadService {

 private final FileSystemDAO fileSystemDao;

 public MySampleUploadService(FileSystemDAO dao) {
      this.fileSystemDao = dao;
 }
 public String uploadFile(MultipartFile file) {
     try {
     String fileName = file.getOriginalFilename()
         // Copy file to the target location (Replacing existing file with the same name)
         Path targetLocation = Paths.get("uploadPath" + File.separator +
 StringUtils.cleanPath(fileName));
         fileSystemDao.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Not able to upload", ex);
    }
 }

}

Now with this approach you can easily test the Upload service by mocking the FileSystemDao interface.


问:
I cannot take a value from EditText and work with that value
I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.

```<code>public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
        Pattern.compile("^" + "(?=.*[0-9])" +
                "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");

public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;

public String Mess = null;

public String jmeno, prijmeni, email, heslo, heslo2;
 Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_registrace);

    TextView login = (TextView) findViewById(R.id.lnkLogin);
    login.setMovementMethod(LinkMovementMethod.getInstance());
    login.setOnClickListener(this);

    editJmeno = (EditText) findViewById(R.id.txtJmeno);
    jmeno = editJmeno.getText().toString().trim();

    editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
    prijmeni = editPrijmeni.getEditableText().toString().trim();

    editEmail = (EditText) findViewById(R.id.txtEmail);
    email = editEmail.getEditableText().toString().trim();

    editPwd = (EditText) findViewById(R.id.txtPassword);
    heslo = editPwd.getEditableText().toString().trim();

    editPwd2 = (EditText) findViewById(R.id.txtPassword2);
    heslo2 = editPwd2.getEditableText().toString().trim();

    btn = (Button) findViewById(R.id.btnRegistrace);
    btn.setOnClickListener(this);

}

public boolean validujPrijmeni() {
     if(prijmeni.isEmpty()) {
         Mess = "Příjmení" + "\n";
         return false;

     } else {
         return true;
     }

}

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.lnkLogin:
            Intent intent = new Intent(Registrace.this, Login.class);
            startActivity(intent);
            break;
        case R.id.btnRegistrace:
            Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

            if(!prijmeni.isEmpty()) {
                Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
            }
            break;
    }

}
}
</code>```

To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.

Here is layout.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">

<TextView
    android:id="@+id/loginscrn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:text="Registrace"
    android:textSize="20dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/fstTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Příjmení" />
<EditText
    android:id="@+id/txtPrijmeni"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/secTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Jméno"/>
<EditText
    android:id="@+id/txtJmeno"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10"/>
<TextView
    android:id="@+id/thirdTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/fourTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />

<TextView
    android:id="@+id/fiveTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo, znova pro kontrolu"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />
<Button
    android:id="@+id/btnRegistrace"
    android:onClick="Registrace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:text="Registrovat" />
<TextView android:id="@+id/lnkLogin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:text="Jste již registrován?? Přihlaste se zde."
    android:gravity="center"
    android:textSize="20dp"
    android:textColor="#3F51B5"
    android:onClick="test"/>
</code>```

答:
Do this: prijmeni = editPrijmeni.getEditableText().toString().trim(); in the onClick() method.

You are doing it at the creation of the Activity so the EditText control is empty. It won't automatically update the prijmeni string on change.

Here is how your code could look like with some small improvements.

It could also be further refined but it seems you just begin so it's already fine.

```<code>public class Registrace extends AppCompatActivity implements View.OnClickListener {
    private static final Pattern PASSWORD_PATTERN =
        Pattern.compile("^" + "(?=.*[0-9])" +
                "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");

    private EditText editPrijmeni;
    private EditText editJmeno;
    private EditText editEmail;
    private EditText editPwd;
    private EditText editPwd2;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_registrace);

        // Shouldn't you use a button instead of a text view?
        // It seems you want a "Login" button to go to a LoginActivity
        final TextView login = (TextView) findViewById(R.id.lnkLogin);
        login.setMovementMethod(LinkMovementMethod.getInstance());
        login.setOnClickListener(this);

        // You could use https://jakewharton.github.io/butterknife which simplifies this boilerplate code a lot
        editJmeno = (EditText) findViewById(R.id.txtJmeno);
        editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
        editEmail = (EditText) findViewById(R.id.txtEmail);
        editPwd = (EditText) findViewById(R.id.txtPassword);
        editPwd2 = (EditText) findViewById(R.id.txtPassword2);
        btn = (Button) findViewById(R.id.btnRegistrace);
        btn.setOnClickListener(this);
    }

    public boolean validujPrijmeni() {
        // if 'Mess' was for a validation message don't set it in the validation method.
        // define a string in your resources.
        // show/hide a TextView with that message from where you use the validation method.
        final String prijmeni = editPrijmeni.getEditableText().toString().trim();
        return !prijmeni.isEmpty();
    }

    // I would not declare the activity as a OnClickListener but use anonymous classes in the onCreate method
    // calling method on this class.
    // or if you use ButterKnife you can do so with OnClick annotations.
    // This is to prevent the use of switch which is not great code.
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lnkLogin:
                Intent intent = new Intent(Registrace.this, Login.class);
                startActivity(intent);
                break;
        case R.id.btnRegistrace:
            Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

            final String prijmeni = editPrijmeni.getEditableText().toString().trim();
            if (this.validujPrijmeni()) {
                Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }

}
</code>```

Body:
I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.

public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
        Pattern.compile("^" + "(?=.*[0-9])" +
                "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");

public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;

public String Mess = null;

public String jmeno, prijmeni, email, heslo, heslo2;
 Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_registrace);

    TextView login = (TextView) findViewById(R.id.lnkLogin);
    login.setMovementMethod(LinkMovementMethod.getInstance());
    login.setOnClickListener(this);

    editJmeno = (EditText) findViewById(R.id.txtJmeno);
    jmeno = editJmeno.getText().toString().trim();

    editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
    prijmeni = editPrijmeni.getEditableText().toString().trim();

    editEmail = (EditText) findViewById(R.id.txtEmail);
    email = editEmail.getEditableText().toString().trim();

    editPwd = (EditText) findViewById(R.id.txtPassword);
    heslo = editPwd.getEditableText().toString().trim();

    editPwd2 = (EditText) findViewById(R.id.txtPassword2);
    heslo2 = editPwd2.getEditableText().toString().trim();

    btn = (Button) findViewById(R.id.btnRegistrace);
    btn.setOnClickListener(this);

}

public boolean validujPrijmeni() {
     if(prijmeni.isEmpty()) {
         Mess = "Příjmení" + "\n";
         return false;

     } else {
         return true;
     }

}

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.lnkLogin:
            Intent intent = new Intent(Registrace.this, Login.class);
            startActivity(intent);
            break;
        case R.id.btnRegistrace:
            Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

            if(!prijmeni.isEmpty()) {
                Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
            }
            break;
    }

}
}

To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.

Here is layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">

<TextView
    android:id="@+id/loginscrn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:text="Registrace"
    android:textSize="20dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/fstTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Příjmení" />
<EditText
    android:id="@+id/txtPrijmeni"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/secTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Jméno"/>
<EditText
    android:id="@+id/txtJmeno"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10"/>
<TextView
    android:id="@+id/thirdTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/fourTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />

<TextView
    android:id="@+id/fiveTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo, znova pro kontrolu"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />
<Button
    android:id="@+id/btnRegistrace"
    android:onClick="Registrace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:text="Registrovat" />
<TextView android:id="@+id/lnkLogin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:text="Jste již registrován?? Přihlaste se zde."
    android:gravity="center"
    android:textSize="20dp"
    android:textColor="#3F51B5"
    android:onClick="test"/>

Body:
Do this: prijmeni = editPrijmeni.getEditableText().toString().trim(); in the onClick() method.

You are doing it at the creation of the Activity so the EditText control is empty. It won't automatically update the prijmeni string on change.

Here is how your code could look like with some small improvements.

It could also be further refined but it seems you just begin so it's already fine.

public class Registrace extends AppCompatActivity implements View.OnClickListener {
    private static final Pattern PASSWORD_PATTERN =
        Pattern.compile("^" + "(?=.*[0-9])" +
                "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");

    private EditText editPrijmeni;
    private EditText editJmeno;
    private EditText editEmail;
    private EditText editPwd;
    private EditText editPwd2;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_registrace);

        // Shouldn't you use a button instead of a text view?
        // It seems you want a "Login" button to go to a LoginActivity
        final TextView login = (TextView) findViewById(R.id.lnkLogin);
        login.setMovementMethod(LinkMovementMethod.getInstance());
        login.setOnClickListener(this);

        // You could use https://jakewharton.github.io/butterknife which simplifies this boilerplate code a lot
        editJmeno = (EditText) findViewById(R.id.txtJmeno);
        editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
        editEmail = (EditText) findViewById(R.id.txtEmail);
        editPwd = (EditText) findViewById(R.id.txtPassword);
        editPwd2 = (EditText) findViewById(R.id.txtPassword2);
        btn = (Button) findViewById(R.id.btnRegistrace);
        btn.setOnClickListener(this);
    }

    public boolean validujPrijmeni() {
        // if 'Mess' was for a validation message don't set it in the validation method.
        // define a string in your resources.
        // show/hide a TextView with that message from where you use the validation method.
        final String prijmeni = editPrijmeni.getEditableText().toString().trim();
        return !prijmeni.isEmpty();
    }

    // I would not declare the activity as a OnClickListener but use anonymous classes in the onCreate method
    // calling method on this class.
    // or if you use ButterKnife you can do so with OnClick annotations.
    // This is to prevent the use of switch which is not great code.
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lnkLogin:
                Intent intent = new Intent(Registrace.this, Login.class);
                startActivity(intent);
                break;
        case R.id.btnRegistrace:
            Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

            final String prijmeni = editPrijmeni.getEditableText().toString().trim();
            if (this.validujPrijmeni()) {
                Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }

}


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
You can't do that. This is not allowed in SQL. You should write all fields and then say null for id.

SELECT a,b,c,d,e, id as NULL from table

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!