text:
Q: CALayer flattening sublayers I am creating a UI where we have a deck of cards that you can swipe off the screen.
What I had hoped to be able to do was create a subclass of UIView which would represent each card and then to modify the transform property to move them back (z-axis) and a little up (y-axis) to get the look of a deck of cards.
Reading up on it I found I needed to use a CATransformLayer instead of the normal CALayer in order for the z-axis to not get flattened.  I prototyped this by creating a CATransformLayer which I added to the CardDeckView's layer, and then all my cards are added to that CATransformLayer.  The code looks a little bit like this:
In init:
// Initialize the CATransformSublayer
_rootTransformLayer = [self constructRootTransformLayer];
[self.layer addSublayer:_rootTransformLayer];

constructRootTransformLayer (the angle method is redundant, was going to angle the deck but later decided not to):
    CATransformLayer* transformLayer = [CATransformLayer layer];
transformLayer.frame = self.bounds;

// Angle the transform layer so we an see all of the cards
CATransform3D rootRotateTransform =  [self transformWithZRotation:0.0];
transformLayer.transform = rootRotateTransform;
return transformLayer;

Then the code to add the cards looks like:
// Set up a CardView as a wrapper for the contentView
RVCardView* cardView = [[RVCardView alloc] initWithContentView:contentView];

cardView.layer.cornerRadius = 6.0;
if (cardView != nil) {
    [_cardArray addObject:cardView];
    //[self addSubview:cardView];
    [_rootTransformLayer addSublayer:cardView.layer];
    [self setNeedsLayout];
}

Note that what I originally wanted was to simply add the RVCardView directly as a subview - I want to preserve touch events which adding just the layer doesn't do.  Unfortunately what ends up happening is the following:

If I add the cards to the rootTransformLayer I end up with the right look which is:

Note that I tried using the layerClass on the root view (CardDeckView) which looks like this:
+ (Class) layerClass
{
    return [CATransformLayer class];
}

I've confirmed that the root layer type is now CATransformLayer but I still get the flattened look.  What else do I need to do in order to prevent the flattening?

A: When you use views, you see a flat scene because there is no perspective set in place. To make a comparison with 3D graphics, like OpenGL, in order to render a scene you must set the camera matrix, the one that transforms the 3D world into a 2D image.
This is the same: sublayers content are transformed using CATransform3D in 3D space but then, when the parent CALayer displays them, by default it projects them on x and y ignoring the z coordinate.
See Adding Perspective to Your Animations on Apple documentation. This is the code you are missing:
CATransform3D perspective = CATransform3DIdentity;
perspective.m34 = -1.0 / eyePosition; // ...on the z axis

myParentDeckView.layer.sublayerTransform = perspective;

Note that for this, you don't need to use CATransformLayer, a simple CALayer would suffice:

here is the transformation applied to the subviews in the picture (eyePosition = -0.1):
// (from ViewController-viewDidLoad)
for (UIView *v in self.view.subviews) {
    CGFloat dz = (float)(arc4random() % self.view.subviews.count);
    CATransform3D t = CATransform3DRotate(CATransform3DMakeTranslation(0.f, 0.f, dz),
                                          0.02,
                                          1.0, 0.0, 0.0);
    v.layer.transform = t;
}

The reason for using CATransformLayer is pointed out in this question. CALayer "rasterizes" its transformed sublayers and then applies its own transformation, while CATransformLayer preserves the full hierarchy and draws each sublayer independently; it is useful only if you have more than one level of 3D-transformed sublayers. In your case, the scene tree has only one level: the deck view (which itself has the identity matrix as transformation) and the card views, the children (which are instead moved in the 3D space). So CATransformLayer is superfluous in this case.


text:
Q: Textarea doesn't resize properly I was making a function to auto resize a <textarea> with jQuery. You can try the snippet below.

$(document).ready(function(){
  $('textarea').autoresize()
})

$.fn.autoresize = function(minRows=1, maxRows=5) {
  var e = $(this)
  e.attr('rows', minRows).css({'resize':'none'}).on('input', function(){ resize(e) })

  var state = 0
  function resize(e) {
    if (e.attr('rows') <= maxRows) {
      e.attr('overflow', 'hidden')
      if (e[0].scrollHeight>e.innerHeight() && e.attr('rows') < maxRows) {
        e.attr('rows', +e.attr('rows')+1)

        if (state) {
          state = 2
        }

        resize(e)
      } else if (e.attr('rows') > minRows) {
        if (state == 2) {
          state = 0
        } else {
          state = 1
          e.attr('rows', +e.attr('rows')-1)
          resize(e)
        }
      }
    } else {
      e.attr('overflow', 'auto')
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea style="width: 200px"></textarea>

If you type on the first row, the <textarea> will add a new row when its value needs to be overflowed. But when you type on the second row and so on, <textarea> will  add a new row even if it doesn't have to be overflowed.
At first I thought it's because the scrollbar, but I already set the overflow to hidden and it will only change to overflow: scroll when <textarea> rows equal to maxRows.

A: something like:

$(document).ready(function() {

  $("#text").focus(function() {
    $("#text").attr("row", "10");
    $("#text").attr("style", "width: 100px");
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="text" style="width: 200px" row="5"></textarea>

A: Accidentally, I set the overflow to hidden as an attribute, not a style.
So this one e.attr('overflow', 'hidden') should be e.css('overflow', 'hidden')
Here is the working code

$(document).ready(function(){
    $('textarea').autoresize()
  })

  $.fn.autoresize = function(minRows=1, maxRows=5) {
    var e = $(this)
    e.attr('rows', minRows).css({'resize':'none'}).on('input', function(){ resize(e) })

    var state = 0
    function resize(e) {
      if (e.attr('rows') <= maxRows) {
        e.css('overflow', 'hidden')
        if (e[0].scrollHeight>e.innerHeight() && e.attr('rows') < maxRows) {
          e.attr('rows', +e.attr('rows')+1)

          if (state) {
            state = 2
          }

          resize(e)
        } else if (e.attr('rows') > minRows) {
          if (e.attr('rows') == maxRows && e[0].scrollHeight>e.innerHeight()) {
            e.css('overflow', 'auto')
          }

          if (state == 2) {
            state = 0
          } else {
            state = 1
            e.attr('rows', minRows)
            resize(e)
          }
        }
      }
    }
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea style="width: 200px"></textarea>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use similar, derived property names in multiple Typescript interfaces or create new interfaces based on interface property names I am searching for a solution how to create two interfaces that have somewhat similar named properties like this:
interface Int1 {
  propOne: string;
  propTwo?: number;
  propThree?: Date;
}

interface Int2 {
  propOneIndex: number;
  propTwoIndex?: number;
  propThreeIndex?: number;
}

You can see that the properties' names in Int2 are extended from Int1 with the postfix "Index". Is there a way to approach this?
I found this answer, where someone uses an enum and key remapping via as but that requires Typescript version ^4.1 which I don't have. I thought there might be a simpler solution as I expect this to be a common use case.


text:
Q: Kotlin native protobuf problems Whenever I try to run gradle task runDebugExecutableLinux, the following happens...
    ./gradlew runDebugExecutableLinux -Dorg.gradle.java.home=$JAVA_HOME

> Configure project :
Kotlin Multiplatform Projects are an experimental feature.

> Task :linkDebugExecutableLinux FAILED
e: Compilation failed: Protocol message tag had invalid wire type.

 * Source files: Main.kt
 * Compiler version info: Konan: 1.3.1 / Kotlin: 1.3.40
 * Output kind: PROGRAM

e: org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
        at org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:99)
        at org.jetbrains.kotlin.protobuf.CodedInputStream.skipField(CodedInputStream.java:262)
        at org.jetbrains.kotlin.protobuf.GeneratedMessageLite.parseUnknownField(GeneratedMessageLite.java:73)
        at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment.<init>(KonanProtoBuf.java:1074)
        at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment.<init>(KonanProtoBuf.java:1033)
        at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment$1.parsePartialFrom(KonanProtoBuf.java:1167)
        at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment$1.parsePartialFrom(KonanProtoBuf.java:1162)
        at org.jetbrains.kotlin.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:137)
        at org.jetbrains.kotlin.protobuf.AbstractParser.parseFrom(AbstractParser.java:168)
        at org.jetbrains.kotlin.protobuf.AbstractParser.parseFrom(AbstractParser.java:180)
        at org.jetbrains.kotlin.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
        at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment.parseFrom(KonanProtoBuf.java:1453)
        at org.jetbrains.kotlin.serialization.konan.KonanDeserializationUtilsKt.parsePackageFragment(KonanDeserializationUtils.kt:6)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$protoForNames$2.invoke(KonanPackageFragment.kt:57)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$protoForNames$2.invoke(KonanPackageFragment.kt:35)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getProtoForNames(KonanPackageFragment.kt)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getProto(KonanPackageFragment.kt:61)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$_memberScope$2.invoke(KonanPackageFragment.kt:75)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$_memberScope$2.invoke(KonanPackageFragment.kt:35)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.get_memberScope(KonanPackageFragment.kt)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getMemberScope(KonanPackageFragment.kt:82)
        at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getMemberScope(KonanPackageFragment.kt:35)
        at org.jetbrains.kotlin.descriptors.impl.LazyPackageViewDescriptorImpl$memberScope$1.invoke(LazyPackageViewDescriptorImpl.kt:46)
        at org.jetbrains.kotlin.descriptors.impl.LazyPackageViewDescriptorImpl$memberScope$1.invoke(LazyPackageViewDescriptorImpl.kt:30)
        at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:346)
        at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:402)
        at org.jetbrains.kotlin.resolve.scopes.LazyScopeAdapter.getWorkerScope(LazyScopeAdapter.kt:23)
        at org.jetbrains.kotlin.resolve.scopes.AbstractScopeAdapter.getContributedClassifier(AbstractScopeAdapter.kt:44)
        at org.jetbrains.kotlin.backend.konan.InteropUtilsKt.getContributedClass(InteropUtils.kt:114)
        at org.jetbrains.kotlin.backend.konan.InteropUtilsKt.access$getContributedClass(InteropUtils.kt:1)
        at org.jetbrains.kotlin.backend.konan.InteropBuiltIns.<init>(InteropUtils.kt:33)
        at org.jetbrains.kotlin.backend.konan.Context$interopBuiltIns$2.invoke(Context.kt:307)
        at org.jetbrains.kotlin.backend.konan.Context$interopBuiltIns$2.invoke(Context.kt:193)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at org.jetbrains.kotlin.backend.konan.Context.getInteropBuiltIns(Context.kt)
        at org.jetbrains.kotlin.backend.konan.ir.KonanSymbols.<init>(Ir.kt:117)
        at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1.invoke(ToplevelPhases.kt:123)
        at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1.invoke(ToplevelPhases.kt)
        at org.jetbrains.kotlin.backend.common.phaser.PhaseBuildersKt$namedOpUnitPhase$1.invoke(PhaseBuilders.kt:116)
        at org.jetbrains.kotlin.backend.common.phaser.PhaseBuildersKt$namedOpUnitPhase$1.invoke(PhaseBuilders.kt:114)
        at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper$runBody$1.invoke(CompilerPhase.kt:113)
        at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.downlevel(CompilerPhase.kt:23)
        at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.runBody(CompilerPhase.kt:112)
        at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.invoke(CompilerPhase.kt:92)
        at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:28)
        at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper$runBody$1.invoke(CompilerPhase.kt:113)
        at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.downlevel(CompilerPhase.kt:23)
        at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.runBody(CompilerPhase.kt:112)
        at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.invoke(CompilerPhase.kt:92)
        at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:41)
        at org.jetbrains.kotlin.backend.konan.KonanDriverKt.runTopLevelPhases(KonanDriver.kt:27)
        at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:79)
        at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:34)
        at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:84)
        at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:42)
        at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:104)
        at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:82)
        at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:50)
        at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMainNoExit(CLITool.kt:215)
        at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMain(CLITool.kt:207)
        at org.jetbrains.kotlin.cli.bc.K2Native$Companion$main$1.invoke(K2Native.kt:215)
        at org.jetbrains.kotlin.cli.bc.K2Native$Companion$main$1.invoke(K2Native.kt:212)
        at org.jetbrains.kotlin.konan.util.UtilKt.profileIf(Util.kt:40)
        at org.jetbrains.kotlin.konan.util.UtilKt.profile(Util.kt:34)
        at org.jetbrains.kotlin.cli.bc.K2Native$Companion.main(K2Native.kt:214)
        at org.jetbrains.kotlin.cli.bc.K2NativeKt.main(K2Native.kt:296)
        at org.jetbrains.kotlin.cli.utilities.MainKt.main(main.kt:16)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':linkDebugExecutableLinux'.
> Process 'command '/usr/lib/jvm/java-10-openjdk/bin/java'' finished with non-zero exit value 2

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
1 actionable task: 1 executed

I tried fixing it by running it with another Java version, first ran it with jdk8, now with jdk10, but no change, error is still the same.
Here is my build.gradle if it changes anything:
plugins {
    id 'org.jetbrains.kotlin.multiplatform' version '1.3.41'
}
repositories {
    mavenCentral()
}
sourceCompatibility = 1.10
targetCompatibility = 1.10
kotlin {
    // For ARM, should be changed to iosArm32 or iosArm64
    // For Linux, should be changed to e.g. linuxX64
    // For MacOS, should be changed to e.g. macosX64
    // For Windows, should be changed to e.g. mingwX64
    linuxX64("linux") {
        binaries {
            executable {
                // Change to specify fully qualified name of your application's entry point:
                entryPoint = 'ymusic.main'
                // Specify command-line arguments, if necessary:
                runTask?.args('')
            }
        }
    }
    sourceSets {
        // Note: To enable common source sets please comment out 'kotlin.import.noCommonSourceSets' property
        // in gradle.properties file and re-import your project in IDE.
        linuxMain {
            dependencies {
                implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:1.3.0-RC"
                implementation "org.jetbrains.kotlinx:kotlinx-io-native:0.1.11"
            }
        }
        linuxTest {
        }
        commonMain {

        }
    }
}

I don't think it will, as the same thing happens on a new native project, started from scratch.
EDIT:
Added output with --info flag on a new project
11:54:19: Executing task 'runDebugExecutableLinux --info'...

The client will now receive all logging from the daemon (pid: 10182). The daemon log file: /home/notyours/.gradle/daemon/4.10/daemon-10182.out.log
Starting 2nd build in daemon [uptime: 1 mins 0.431 secs, performance: 97%, no major garbage collections]
Using 4 worker leases.
Starting Build
Settings evaluated using settings file '/home/notyours/IdeaProjects/test-jdk10/settings.gradle'.
Projects loaded. Root project using build file '/home/notyours/IdeaProjects/test-jdk10/build.gradle'.
Included projects: [root project 'test-jdk10']

> Configure project :
Evaluating root project 'test-jdk10' using build file '/home/notyours/IdeaProjects/test-jdk10/build.gradle'.
Kotlin Multiplatform Projects are an experimental feature.
Kotlin/Native distribution: /home/notyours/.konan/kotlin-native-linux-1.3.1
file or directory '/home/notyours/IdeaProjects/test-jdk10/src/commonMain/kotlin', not found
All projects evaluated.
Selected primary task 'runDebugExecutableLinux' from project :
Tasks to be executed: [task ':linkDebugExecutableLinux', task ':runDebugExecutableLinux']
:linkDebugExecutableLinux (Thread[Task worker for ':' Thread 2,5,main]) started.

> Task :linkDebugExecutableLinux
Task ':linkDebugExecutableLinux' is not up-to-date because:
  Task has failed previously.
file or directory '/home/notyours/IdeaProjects/test-jdk10/src/commonMain/kotlin', not found
file or directory '/home/notyours/IdeaProjects/test-jdk10/src/commonMain/kotlin', not found
Run tool: konanc with args: -g -ea -target linux_x64 -p program -o /home/notyours/IdeaProjects/test-jdk10/build/bin/linux/debugExecutable/test-jdk10.kexe -Xmulti-platform /home/notyours/IdeaProjects/test-jdk10/src/linuxMain/kotlin/sample/SampleLinux.kt -entry sample.main
Starting process 'command '/usr/lib/jvm/java-8-jdk/bin/java''. Working directory: /home/notyours/IdeaProjects/test-jdk10 Command: /usr/lib/jvm/java-8-jdk/bin/java -D__idea.mac.env.lock=unlocked -Dawt.toolkit=sun.awt.X11.XToolkit -Dcom.jetbrains.suppressWindowRaise=false -Dfile.encoding.pkg=sun.io -Dfile.separator=/ -Didea.active=true -Didea.cycle.buffer.size=1024 -Didea.dynamic.classpath=false -Didea.fatal.error.notification=disabled -Didea.jre.check=true -Didea.max.content.load.filesize=20000 -Didea.max.intellisense.filesize=2500 -Didea.no.launcher=false -Didea.paths.selector=IntelliJIdea2019.1 -Didea.popup.weight=heavy -Didea.registered=true -Didea.version=2019.1.3 -Didea.xdebug.key=-Xdebug -Dio.netty.machineId=28:f0:76:ff:fe:16:65:0e -Dio.netty.processId=3883 -Dio.netty.serviceThreadPrefix=Netty  -Djava.awt.graphicsenv=sun.awt.X11GraphicsEnvironment -Djava.awt.printerjob=sun.print.PSPrinterJob -Djava.class.path=/home/notyours/.gradle/wrapper/dists/gradle-4.10-bin/bg6py687nqv2mbe6e1hdtk57h/gradle-4.10/lib/gradle-launcher-4.10.jar -Djava.class.version=52.0 -Djava.ext.dirs=/usr/lib/jvm/java-8-jdk/jre/lib/ext:/usr/java/packages/lib/ext -Djava.home=/usr/lib/jvm/java-8-jdk/jre -Djava.library.path=/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/nativelib -Djava.net.preferIPv4Stack=true -Djava.rmi.server.disableHttp=true -Djava.rmi.server.hostname=127.0.0.1 -Djava.runtime.name=Java(TM) SE Runtime Environment -Djava.runtime.version=1.8.0_212-b10 -Djava.specification.name=Java Platform API Specification -Djava.specification.vendor=Oracle Corporation -Djava.specification.version=1.8 -Djava.util.Arrays.useLegacyMergeSort=true -Djava.util.concurrent.ForkJoinPool.common.threadFactory=com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory -Djava.vendor=Oracle Corporation -Djava.vendor.url=http://java.oracle.com/ -Djava.vendor.url.bug=http://bugreport.sun.com/bugreport/ -Djava.version=1.8.0_212 -Djava.vm.info=mixed mode -Djava.vm.name=Java HotSpot(TM) 64-Bit Server VM -Djava.vm.specification.name=Java Virtual Machine Specification -Djava.vm.specification.vendor=Oracle Corporation -Djava.vm.specification.version=1.8 -Djava.vm.vendor=Oracle Corporation -Djava.vm.version=25.212-b10 -Djavafx.runtime.version=8.0.212-b08 -Djavafx.version=8.0.212 -Djavax.swing.rebaseCssSizeMap=true -Djb.vmOptionsFile=/opt/intellij-idea-ultimate-edition/bin/idea64.vmoptions -Djbre.popupwindow.settype=true -Djdk.http.auth.tunneling.disabledSchemes="" -Djna.loaded=true -Djna.nosys=true -Djna.platform.library.path=/usr/lib64:/lib64:/usr/lib:/lib:/usr/lib/opencollada:/usr/lib32:/usr/lib/tls:/usr/lib32/tls:/usr/lib/libfakeroot -Djna.tmpdir=/home/notyours/.IntelliJIdea2019.1/system/tmp -Djnidispatch.path=/home/notyours/.IntelliJIdea2019.1/system/tmp/jna5357576498872694060.tmp -Dkonan.home=/home/notyours/.konan/kotlin-native-linux-1.3.1 -Dkotlin.environment.keepalive=true -Dlibrary.jansi.path=/home/notyours/.gradle/native/jansi/1.14/linux64 -Dline.separator=
 -Dlog4j.defaultInitOverride=true -Dorg.jetbrains.kotlin.cliMessageRenderer=GradleStyle -Dos.arch=amd64 -Dos.name=Linux -Dos.version=4.19.59-1-MANJARO -Dpath.separator=: -Dpty4j.preferred.native.folder=/opt/intellij-idea-ultimate-edition/lib/pty4j-native -Dpty4j.tmpdir=/home/notyours/.IntelliJIdea2019.1/system/tmp -Dsun.arch.data.model=64 -Dsun.boot.class.path=/usr/lib/jvm/java-8-jdk/jre/lib/resources.jar:/usr/lib/jvm/java-8-jdk/jre/lib/rt.jar:/usr/lib/jvm/java-8-jdk/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-8-jdk/jre/lib/jsse.jar:/usr/lib/jvm/java-8-jdk/jre/lib/jce.jar:/usr/lib/jvm/java-8-jdk/jre/lib/charsets.jar:/usr/lib/jvm/java-8-jdk/jre/lib/jfr.jar:/usr/lib/jvm/java-8-jdk/jre/classes -Dsun.boot.library.path=/usr/lib/jvm/java-8-jdk/jre/lib/amd64 -Dsun.cpu.endian=little -Dsun.cpu.isalist -Dsun.io.unicode.encoding=UnicodeLittle -Dsun.java.command=org.gradle.launcher.daemon.bootstrap.GradleDaemon 4.10 -Dsun.java.launcher=SUN_STANDARD -Dsun.jnu.encoding=UTF-8 -Dsun.management.compiler=HotSpot 64-Bit Tiered Compilers -Dsun.os.patch.level=unknown -Dswing.bufferPerWindow=true -Duser.dir=/home/notyours/IdeaProjects/test-jdk10 -Duser.home=/home/notyours -Duser.name=notyours -Duser.timezone=Europe/Ljubljana -XX:TieredStopAtLevel=1 -Xmx3G -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/tmp -Duser.country=GB -Duser.language=en -Duser.variant -ea -cp /home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/kotlin-reflect.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/StubGenerator.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/konan.serializer.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/Indexer.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/kotlin-native-shared.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/kotlin-compiler.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/Runtime.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/kotlin-script-runtime.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/utilities.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/kotlin-stdlib.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/klib.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/konan.metadata.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/protobuf-java-2.6.1.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/backend.native.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/version.jar:/home/notyours/.konan/kotlin-native-linux-1.3.1/konan/lib/trove4j.jar org.jetbrains.kotlin.cli.utilities.MainKt konanc @/tmp/konancArgs1404673531652305687.lst
Successfully started process 'command '/usr/lib/jvm/java-8-jdk/bin/java''
e: Compilation failed: Protocol message tag had invalid wire type.

 * Source files: SampleLinux.kt
 * Compiler version info: Konan: 1.3.1 / Kotlin: 1.3.40
 * Output kind: PROGRAM

e: org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
    at org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:99)
    at org.jetbrains.kotlin.protobuf.CodedInputStream.skipField(CodedInputStream.java:262)
    at org.jetbrains.kotlin.protobuf.GeneratedMessageLite.parseUnknownField(GeneratedMessageLite.java:73)
    at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment.<init>(KonanProtoBuf.java:1074)
    at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment.<init>(KonanProtoBuf.java:1033)
    at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment$1.parsePartialFrom(KonanProtoBuf.java:1167)
    at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment$1.parsePartialFrom(KonanProtoBuf.java:1162)
    at org.jetbrains.kotlin.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:137)
    at org.jetbrains.kotlin.protobuf.AbstractParser.parseFrom(AbstractParser.java:168)
    at org.jetbrains.kotlin.protobuf.AbstractParser.parseFrom(AbstractParser.java:180)
    at org.jetbrains.kotlin.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
    at org.jetbrains.kotlin.metadata.konan.KonanProtoBuf$LinkDataPackageFragment.parseFrom(KonanProtoBuf.java:1453)
    at org.jetbrains.kotlin.serialization.konan.KonanDeserializationUtilsKt.parsePackageFragment(KonanDeserializationUtils.kt:6)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$protoForNames$2.invoke(KonanPackageFragment.kt:57)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$protoForNames$2.invoke(KonanPackageFragment.kt:35)
    at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getProtoForNames(KonanPackageFragment.kt)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getProto(KonanPackageFragment.kt:61)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$_memberScope$2.invoke(KonanPackageFragment.kt:75)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment$_memberScope$2.invoke(KonanPackageFragment.kt:35)
    at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.get_memberScope(KonanPackageFragment.kt)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getMemberScope(KonanPackageFragment.kt:82)
    at org.jetbrains.kotlin.serialization.konan.KonanPackageFragment.getMemberScope(KonanPackageFragment.kt:35)
    at org.jetbrains.kotlin.descriptors.impl.LazyPackageViewDescriptorImpl$memberScope$1.invoke(LazyPackageViewDescriptorImpl.kt:46)
    at org.jetbrains.kotlin.descriptors.impl.LazyPackageViewDescriptorImpl$memberScope$1.invoke(LazyPackageViewDescriptorImpl.kt:30)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:346)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:402)
    at org.jetbrains.kotlin.resolve.scopes.LazyScopeAdapter.getWorkerScope(LazyScopeAdapter.kt:23)
    at org.jetbrains.kotlin.resolve.scopes.AbstractScopeAdapter.getContributedClassifier(AbstractScopeAdapter.kt:44)
    at org.jetbrains.kotlin.backend.konan.InteropUtilsKt.getContributedClass(InteropUtils.kt:114)
    at org.jetbrains.kotlin.backend.konan.InteropUtilsKt.access$getContributedClass(InteropUtils.kt:1)
    at org.jetbrains.kotlin.backend.konan.InteropBuiltIns.<init>(InteropUtils.kt:33)
    at org.jetbrains.kotlin.backend.konan.Context$interopBuiltIns$2.invoke(Context.kt:307)
    at org.jetbrains.kotlin.backend.konan.Context$interopBuiltIns$2.invoke(Context.kt:193)
    at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
    at org.jetbrains.kotlin.backend.konan.Context.getInteropBuiltIns(Context.kt)
    at org.jetbrains.kotlin.backend.konan.ir.KonanSymbols.<init>(Ir.kt:117)
    at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1.invoke(ToplevelPhases.kt:123)
    at org.jetbrains.kotlin.backend.konan.ToplevelPhasesKt$psiToIrPhase$1.invoke(ToplevelPhases.kt)
    at org.jetbrains.kotlin.backend.common.phaser.PhaseBuildersKt$namedOpUnitPhase$1.invoke(PhaseBuilders.kt:116)
    at org.jetbrains.kotlin.backend.common.phaser.PhaseBuildersKt$namedOpUnitPhase$1.invoke(PhaseBuilders.kt:114)
    at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper$runBody$1.invoke(CompilerPhase.kt:113)
    at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.downlevel(CompilerPhase.kt:23)
    at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.runBody(CompilerPhase.kt:112)
    at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.invoke(CompilerPhase.kt:92)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:28)
    at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper$runBody$1.invoke(CompilerPhase.kt:113)
    at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.downlevel(CompilerPhase.kt:23)
    at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.runBody(CompilerPhase.kt:112)
    at org.jetbrains.kotlin.backend.common.phaser.AbstractNamedPhaseWrapper.invoke(CompilerPhase.kt:92)
    at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:41)
    at org.jetbrains.kotlin.backend.konan.KonanDriverKt.runTopLevelPhases(KonanDriver.kt:27)
    at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:79)
    at org.jetbrains.kotlin.cli.bc.K2Native.doExecute(K2Native.kt:34)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:84)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:42)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:104)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:82)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:50)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMainNoExit(CLITool.kt:215)
    at org.jetbrains.kotlin.cli.common.CLITool$Companion.doMain(CLITool.kt:207)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion$main$1.invoke(K2Native.kt:215)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion$main$1.invoke(K2Native.kt:212)
    at org.jetbrains.kotlin.konan.util.UtilKt.profileIf(Util.kt:40)
    at org.jetbrains.kotlin.konan.util.UtilKt.profile(Util.kt:34)
    at org.jetbrains.kotlin.cli.bc.K2Native$Companion.main(K2Native.kt:214)
    at org.jetbrains.kotlin.cli.bc.K2NativeKt.main(K2Native.kt:296)
    at org.jetbrains.kotlin.cli.utilities.MainKt.main(main.kt:16)

> Task :linkDebugExecutableLinux FAILED
:linkDebugExecutableLinux (Thread[Task worker for ':' Thread 2,5,main]) completed. Took 2.843 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':linkDebugExecutableLinux'.
> Process 'command '/usr/lib/jvm/java-8-jdk/bin/java'' finished with non-zero exit value 2

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s
1 actionable task: 1 executed
Process 'command '/usr/lib/jvm/java-8-jdk/bin/java'' finished with non-zero exit value 2
11:54:22: Task execution finished 'runDebugExecutableLinux --info'.

A: This issue should be gone in the 1.3.41 release. But in this case, something went wrong.

In the error message, there is version info:

*

*Source files: Main.kt

*Compiler version info: Konan: 1.3.1 / Kotlin: 1.3.40

*Output kind: PROGRAM

But as I saw in the build script, you used 1.3.41 version of the multiplatform plugin. So, I recommend checking the /.konan/ folder, where the compiler is stored. Sometimes it's content can be defected, it's better to delete it manually, and let the Gradle re-download everything.


text:
Q: How can I use a singleton when switching/loading scenes? In the Hierarchy I have 3 objects I want to keep and to not destroy when starting a new game.
But I want to destroy them when switching back to the main menu.
The objects are : Player , Game Manager , Scene Loader

On the 3 objects Player , Game Manager , Scene Loader I added to each one a script name PersistentManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PersistentManager : MonoBehaviour
{
    public static PersistentManager Instance { get; private set; }

    private void Awake()
    {
        if(Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

The Scene Loader script that attached to Scene Loader :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class SceneLoader : MonoBehaviour
{
    private bool loadScene = false;

    [SerializeField]
    private int scene;
    [SerializeField]
    private Text loadingText;

    // Updates once per frame
    void Update()
    {
        // If the player has pressed the space bar and a new scene is not loading yet...
        if (Input.GetKeyUp(KeyCode.Space) && loadScene == false)
        {
            LoadScene(scene);
        }

        // If the new scene has started loading...
        if (loadScene == true)
        {
            // ...then pulse the transparency of the loading text to let the player know that the computer is still working.
            loadingText.color = new Color(loadingText.color.r, loadingText.color.g, loadingText.color.b, Mathf.PingPong(Time.time, 1));
        }
    }

    // The coroutine runs on its own at the same time as Update() and takes an integer indicating which scene to load.
    IEnumerator LoadNewScene()
    {
        // This line waits for 3 seconds before executing the next line in the coroutine.
        // This line is only necessary for this demo. The scenes are so simple that they load too fast to read the "Loading..." text.
        //yield return new WaitForSeconds(3);

        // Start an asynchronous operation to load the scene that was passed to the LoadNewScene coroutine.
        AsyncOperation async = SceneManager.LoadSceneAsync(scene);

        // While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
        while (!async.isDone)
        {
            yield return null;
        }
    }

    public void LoadScene(int scene)
    {
        // ...set the loadScene boolean to true to prevent loading a new scene more than once...
        loadScene = true;

        // ...change the instruction text to read "Loading..."
        loadingText.text = "Loading...";

        this.scene = scene;

        // ...and start a coroutine that will load the desired scene.
        StartCoroutine(LoadNewScene());
    }
}

And the Game Manager script that attached to Game Manager :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public SceneLoader sceneLoader;
    public PlayerController playerController;
    public CamMouseLook camMouseLook;
    public static bool backToMainMenu = false;
    public static bool togglePauseGame;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            PauseGame();
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            BackToMainMenu();
        }
    }

    public void PauseGame()
    {
        togglePauseGame = !togglePauseGame;

        if (togglePauseGame == true)
        {
            playerController.enabled = false;
            camMouseLook.enabled = false;
            Time.timeScale = 0f;
        }
        else
        {
            playerController.enabled = true;
            camMouseLook.enabled = true;
            Time.timeScale = 1f;
        }
    }

    private void BackToMainMenu()
    {
        sceneLoader.LoadScene(0);
        playerController.enabled = false;
        camMouseLook.enabled = false;
        Cursor.lockState = CursorLockMode.None;
        Time.timeScale = 0f;
        backToMainMenu = true;
    }
}

Now when I'm running the game and then pressing the space bar for starting a new game the Main Menu scene is removed not sure why.
Before using the PersistentManager script I used on each of the 3 objects another script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DontDestroy : MonoBehaviour
{
    private void Awake()
    {
        if (GameManager.backToMainMenu == false)
        {
            DontDestroyOnLoad(transform);
        }
    }
}

That keep the 3 objects alive when starting a new game and if switching back to the main menu the problem was that the 3 objects was also in the main menu when switching back to the main menu.
So I had 6 copies of the objects. 3 in the main menu scene and 3 in the DontDestroyOnLoad scene.
That's why I'm trying to use singleton.
I want that when I'm switching back to the main menu the 3 object will not be in the main menu scene in the hierarchy only on the DontDestroyOnLoad.

A: The problem is that the class you are inheriting from has it's instance in the parent
public static PersistentManager Instance { get; private set; }
this means that the first object will go

*

*Is instance null? yes

*Set me as instance

*Set a don't destroy on load

the other two objects will check the instance, see that it's not null because the first object is referenced, and they will destroy themselves.
In general I would advise against using singletons as much as possible, as some might consider them an anti design pattern.
However, if you still want to use one; I'm attaching here a script I used in games that are in production for multiple years with millions of users, so it's already set up against most of the edge cases we encountered.
#region Using

using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;

#endregion

///
///     Generic singleton Class. Extend this class to make singleton component.
///     Example:
///
/// public class Foo : GenericSingleton<Foo>
///
///     . To get the instance of Foo class, use Foo.instance
///     Override Init() method instead of using Awake()
///     from this class.
///
public abstract class GenericSingleton<T> : MonoBehaviour where T : GenericSingleton<T>
{
    private static T _instance;

    [SerializeField, Tooltip("If set to true, the gameobject will deactive on Awake")] private bool _deactivateOnLoad;
    [SerializeField, Tooltip("If set to true, the singleton will be marked as \"don't destroy on load\"")] private bool _dontDestroyOnLoad;

    private bool _isInitialized;

    public static T instance
    {
        get
        {
            // Instance required for the first time, we look for it
            if (_instance != null)
            {
                return _instance;
            }

            var instances = Resources.FindObjectsOfTypeAll<T>();
            if (instances == null || instances.Length == 0)
            {
                return null;
            }

            _instance = instances.FirstOrDefault(i => i.gameObject.scene.buildIndex != -1);
            if (Application.isPlaying)
            {
                _instance?.Init();
            }
            return _instance;
        }
    }

    // If no other monobehaviour request the instance in an awake function
    // executing before this one, no need to search the object.
    protected virtual void Awake()
    {
        if (_instance == null || !_instance || !_instance.gameObject)
        {
            _instance = (T)this;
        }
        else if (_instance != this)
        {
            Debug.LogError($"Another instance of {GetType()} already exist! Destroying self...");
            Destroy(this);
            return;
        }
        _instance.Init();
    }

    ///
    ///     This function is called when the instance is used the first time
    ///     Put all the initializations you need here, as you would do in Awake
    ///
    public void Init()
    {
        if (_isInitialized)
        {
            return;
        }

        if (_dontDestroyOnLoad)
        {
            DontDestroyOnLoad(gameObject);
        }

        if (_deactivateOnLoad)
        {
            gameObject.SetActive(false);
        }

        SceneManager.activeSceneChanged += SceneManagerOnActiveSceneChanged;

        InternalInit();
        _isInitialized = true;
    }

    private void SceneManagerOnActiveSceneChanged(Scene arg0, Scene scene)
    {
        // Sanity
        if (!instance || gameObject == null)
        {
            SceneManager.activeSceneChanged -= SceneManagerOnActiveSceneChanged;
            _instance = null;
            return;
        }

        if (_dontDestroyOnLoad)
        {
            return;
        }

        SceneManager.activeSceneChanged -= SceneManagerOnActiveSceneChanged;
        _instance = null;
    }

    protected abstract void InternalInit();

    /// Make sure the instance isn't referenced anymore when the user quit, just in case.
    private void OnApplicationQuit()
    {
        _instance = null;
    }

    void OnDestroy()
    {
        // Clear static listener OnDestroy
        SceneManager.activeSceneChanged -= SceneManagerOnActiveSceneChanged;

        StopAllCoroutines();
        InternalOnDestroy();
        if (_instance != this)
        {
            return;
        }
        _instance = null;
        _isInitialized = false;
    }

    protected abstract void InternalOnDestroy();
}


text:
Q: Electricity withdrawal We commonly say "electricity consumption" for both :

*

*the electric energy actually consumed by appliances

*the electric energy drawn from the grid by a house, measured by a meter (what appears on your utility bill)

I would like to find a more specific word for the latter, in the specific context of "measuring electric energy flow inside a house" :

*

*From the energy supplier's point of view, electricity drawn to your house is a consumption no matter what you do with it. The supplier calls "energy drawn from the grid" consumption because the supplier charges you for it (business).

*From within your house, you could store the drawn electric energy in a  battery rather than "consuming" it (converting the electric energy to another form). Therefore, not all energy drawn is necessarily "consumed" (physics). You can also "draw electric energy" from a solar panel, so the energy from the grid becomes just one of many "energy withdrawals".

Translations from the French word "Soutirage" (literally "under pull") include racking or withdrawal but they seem seldom used online.
What is the correct noun for the action of drawing energy from a source ?

A: Wattage, power usage, or current drain.
Soutirage immediately brings sapping to mind (as in, sapping electricity from a source is a bit like drawing from it), except that it's not a very elegant term, and probably not suitable for describing power drawn by a household.

A: Any action is described by a verb not a noun. A verb can be used as a noun; for instance The drawing of electricity costs money.
The utility of electricity is described by what it accomplishes. This can be making a wheel turn or just warming a chemical process to charge a battery. Both of these are described as Work.


text:
Q: Android Connect to MySQL using Java and REST currently I am working with Android native and MySQL. To connect both of it, I used Java and REST. However, when I tried to run my REST service, I did not get any response (just blank page show up). I have tried to check the log and I did now find any error. Here is my code:
Database.java -- Database Connection file
package datasource;

import java.sql.Connection;
import java.sql.DriverManager;

public class Database
{
    @SuppressWarnings("finally")
    public static Connection createConnection() throws Exception {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/friseur", "root", "");
        } catch (Exception e) {
            throw e;
        } finally {
            return con;
        }
    }
}

QueryPhoto.java -- To query from database
package query;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import datasource.Database;
import model.Photo;

public class QueryPhoto {
    public static ArrayList<Photo> GetPhoto() throws Exception
    {
        ArrayList<Photo> photo = new ArrayList<Photo>();
        Connection dbConn = null;
        try {
            try {
                dbConn = Database.createConnection();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Statement stmt = dbConn.createStatement();
            String selectPhoto = "SELECT * FROM photo, user where photo.user_id = user.id";
            ResultSet rs = stmt.executeQuery(selectPhoto);
            while(rs.next())
            {
                Photo photoObject = new Photo();
                photoObject.setPDateUpload(rs.getString("added_time"));
                photoObject.setPUrlOriginal(rs.getString("url_original"));
                photoObject.setPUrlWithHair(rs.getString("url_with_hair"));
                photoObject.setCaption(rs.getString("caption"));
                photoObject.setUserId(Integer.parseInt(rs.getString("user_id")));
                photoObject.setUserName(rs.getString("username"));

                photo.add(photoObject);
            }
        }
        catch (SQLException sqle) {
            throw sqle;
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            if (dbConn != null) {
                dbConn.close();
            }
            throw e;
        }
        finally {
            if (dbConn != null) {
                dbConn.close();
            }
        }
        return photo;
    }
}

PhotoJson.java -- to construct json object
package queryresult;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.util.*;

import model.Photo;

public class PhotoJson {
    public static String constructJSON( ArrayList<Photo> photo) {
        JSONObject obj = new JSONObject();
        try {
            for (int i = 0; i < photo.size(); i++) {
                Photo photoObj = photo.get(i);
                obj.put("date_upload", photoObj.getPDateUpload());
                obj.put("url_original", photoObj.getPUrlOriginal());
                obj.put("url_with_hair", photoObj.getPUrlWithHair());
                obj.put("caption", photoObj.getCaption());
                obj.put("user_id", photoObj.getUserId());
                obj.put("username", photoObj.getUserName());
            }
        } catch (Exception e) {

        }
        return obj.toString();
    }
}

GetPhoto.java -- for the REST
package webservice;

import java.util.ArrayList;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.Photo;
import query.QueryPhoto;
import queryresult.PhotoJson;

@Path("/WebService")
public class GetPhoto {

@POST
@Path("/GetPhotos")
@Produces("application/json")
public String photo()
{
    String response = null;
    try
    {
        ArrayList<Photo> photo = QueryPhoto.GetPhoto();
        response = PhotoJson.constructJSON(photo);
    }
    catch (Exception e)
    {
        System.out.println("Exception Error"); //Console
    }
    return response;
    }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>useraccount</display-name>
        <servlet>
            <servlet-name>Jersey REST Service</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                    <param-name>com.sun.jersey.config.property.packages</param-name>
                    <param-value>webservice</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Jersey REST Service</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
</web-app>

What is wrong actually? Thanks so much for your help.

A: Assuming that you're calling the correct URL, the problem most likely is that you're sending an HTTP GET request (you mention a blank page showing), while your method is annotated to respond to POST requests`.
Changing your annotation to @GET would then solve your problem:
@GET
@Path("/GetPhotos")
@Produces("application/json")
public String photo() { /* ... */ }


text:
Q: Handling identity column when managing SQL database table using external content type \ external list I have a SQL table (with a primary key identity column) which I want to perform CRUD operations on using a SharePoint external list as a front end. I have setup stored procedures to perform the CRUD operations. I have been able to setup an external content type with Read Item, Read List, Update Item, and Delete Item operations.
I am having an issue with the Create operation. The identity column value gets set automatically when a row is inserted into the table. When I try to setup a Create operation on the external content type it wants the identity column to be explicitly specified by the user. I don't want the user to specify this identity - I want to to be automatically handled by SQL server when the new row is inserted.


text:
Q: Allowed values for a property Is there a way in dart to only allow a number of values for a property?
class Kana {
  final String kana;
  final String romaji;
  final type = 'hiragana' | 'katakana';

  Kana({this.kana, this.romaji, this.type});
}

I'd like to make those values the only allowed values, preventing me to put a wrong value when initializing a Kana class.

A: You could use enums.
void main() {
  var kana = Kana('x', 'y', Style.hiragana);
  print(kana);
}

class Kana {
  final String kana;
  final String romaji;
  final Style style;

  Kana(this.kana, this.romaji, this.style);
}

enum Style { hiragana, katakana }

A: You can use assert to check the value of your type.
  Kana(this.kana, this.romaji, this.type)
      : assert(type == 'hiragana' || type == 'katakana');


text:
Q: Good or bad practice to have an NSNotification in this method: I followed the answer on this question How to properly hide these ad banners? to have google AdMob supplement iAd when it is unavailable and it works perfectly, but seldomly the advertisement be it google or apple appears even though I have used the NSNotifcation to tell it not to. I included the NSNotification to hide banners in my initWithSize method on the game scene but sometimes they still appear. I think this has to do with the internet connection and when the request becomes an impression. That being said:
I placed my hideAd notification in the -(void)update:(CFTimeInterval)currentTime method to make sure that the advertisement is hidden. Will this slow down my game though over time?
Is it bad to send an NSNotification with every frame update in a sprite-kit game?

A: Firstly, you should not be hiding the banner view at all.  If you don't want to use it the best thing to do is to destroy it and then recreate it later.  From Apple's iAD programming guide:

If the user navigates from a screen of content with a banner view to a
  screen that does not have a banner view, and you expect them to be on
  that screen for a long period of time, remove the banner view from the
  view hierarchy, set its delegate to nil and release it before
  transitioning to the new screen of content. More generally, avoid
  keeping a banner view around when it is invisible to the user.

As far as using NSNotifications per frame that's not a good idea as they have to synchronously notify their listeners with each broadcast.  Delegation is better for a case like this but as I said you shouldn't be doing this sort of thing at all, just destroy and recreate it later.
EDIT:  Here is the updated code that we were discussing in the comments.  You want to create two methods like this on your view controller, but make sure you place the bannerView inside a shell view that has exactly the same frame.  So it would look like this:
- (void)hideBanner
{
    [self.bannerView removeFromSuperview];
    self.shellView.hidden = YES;
}

- (void)showBanner
{
    self.bannerView = [[ADBannerView alloc] initWithAdType:type];
    self.shellView.hidden = NO;
    [self.shellView addSubview:self.bannerView];
}

Just make sure the shell view has the same size as the ad banner unit you are trying to display.  You COULD set the alpha channel of it to make it transparent but that has performance implications and is unnecessary if you size it correctly.


text:
Q: Embed generic new() constraint into interface/class? So far I've been adding new() constraint like this.
public T Request<T>(BaseRequest request)
        where T : BaseResponse, new()

Is there a way to bake the new() into BaseResponse so that I only need to specify
        where T : BaseResponse

A: No. A derived class can always have a private/protected constructor, and there's no way to prevent that. It might even be an abstract class.
The only exception are structs, which always have a default constructor - the one you get with default(SomeStruct). Needless to say, this simply means the struct is initialized with zeroes (though C# 6 made this a bit more complicated).

A: The only way you could spare some typing, provided you have several generic methods in your class, is to make the class generic instead, i.e. go from this:
class YourClass
{
    public static T Request<T>(BaseRequest request)
       where T : BaseResponse, new()
    { }

    public static T SomethingElse<T>(BaseRequest request)
       where T : BaseResponse, new()
    { }
}

to this:
class YourClass<T> where T : BaseResponse, new()
{
    public static T Request(BaseRequest request)
    { }

    public static T SomethingElse(BaseRequest request)
    { }
}


text:
Q: Body scrollbar stopped autohiding I was working on a page with an overflow: auto DIV.
It showed a fancy narrow autohiding scrollbar.
At some point that fancy scrollbar turned into the normal clunky one.
I tried to backtrace but can't seem to get it restored.
You can see on the screenshot that the two scrollbars look different. Mine wasn't red though but subtle blueish.

Image borrowed from: Why is Edge body scrollbar different from Firefox body scrollbar?


text:
Q: The Type does not Exist in the namespace. Are you missing an Assembly? I have 2 C# projects first one name is "Advocar" and the second one is "Import".
There is a class in Advocar project which we need to access to that from Import project. So in Import project I added reference to Advocar.
The problem is from Import project I recognizes all the Advocar classes except the new class that I just created in the Advocar. and when I build it, it say "The Type or namespace does not exist in the Advocar.Data.Inventory namespace. Are you missing an assembly?", but the class is exist in that namespace.
I build Advocar project and re-add the assembly to the Import project and it did not help. Both project are in .NET 2.0.

*

*Any Idea please?

A: Check the access level of new class added into the namespace.

A: Ok. I found the solution although I dont know what would cause that.
since 40% of all the classes that I have are the same code, so to create a new class I just copied and pasted one of the existing class and made changes on that one.
So to solve my issue, I deleted the new classes and I just Add New Item and create a blank class and past the code that I needed to the new class and it fixed that.
Its look like some kind of caching issue that although you rename a class and so on, but it still has some record from past.


text:
Q: Firebase query only documents I participate in I am trying to create simple one-to-one chat. I created structure like this:

My chat document id is:
const roomId = sender < reciever ? sender + reciever : reciever + sender

I can add to it but I have 0 clue how would I query only the ones that have my id in the id. Since I have no clue what is the reciever id at the point I query the documents. Should I create new collection under my user document that keeps reference of the chats? If so how would I then query only messages I am in?
I tried like this:
firebase.firestore().collection('chats').where('senderId', '==', currentUser.id)

but I have no idea who is sender and who is reciever at the time I query them so only one user can see the chats.
Any help is much appreciated.


text:
Q: Can't change the "CALCULATE VAT" logic of following php application Can't change the "CALCULATE VAT" logic of following php application
Here I am dealing with an inventory management system. I downloaded an open source project from the web. I want to edit/remove the VAT feature from this project. I changed the way of calculating vat from this,
// vat
var vat = (Number($("#subTotal").val())/100) * 13;
vat = vat.toFixed(2);
$("#vat").val(vat);
$("#vatValue").val(vat);

// total amount
var totalAmount = (Number($("#subTotal").val()) + Number($("#vat").val()));
totalAmount = totalAmount.toFixed(2);
$("#totalAmount").val(totalAmount);
$("#totalAmountValue").val(totalAmount);

to this
// vat
var vat = (Number($("#subTotal").val())/100) * 2;
vat = vat.toFixed(2);
$("#vat").val(vat);
$("#vatValue").val(vat);

// total amount
var totalAmount = (Number($("#subTotal").val()) + Number($("#vat").val()));
totalAmount = totalAmount.toFixed(2);
$("#totalAmount").val(totalAmount);
$("#totalAmountValue").val(totalAmount);

but it's always calculating 13% of VAT. Please help me solve this problem.

A: If you want to calculate VAT dynamically then add an input
<input type="text" value="0" id="vat-percentage" name="vat-percentage" />

and then replace this
var vat = (Number($("#subTotal").val())/100) * 13;

with that
var vat = (Number($("#subTotal").val())/100) * Number($('#vat-percentage').val());


text:
Q: How can i show the value of item counter inside of the firebase snapshot in JavaScript When i print my item counter the value is still 0 even there is a data on it but if i print the itemcount below on increment it shows the right value. Please help me I also use firebase on this
I want the right value of item counter because it always shows a 0 value
here is the code :
var itemCounter = 0;

get(queGadget).then((snapshot)=>{
    snapshot.forEach(childSnapshot => {
      ++itemCounter;

    });

})

console.log(itemCounter)


text:
Q: XHR doesn't appear to fire on transition with Ember Basic Ember app using an API i've written in Laravel. I have an index page showing all products, I generate edit links and when I visit the edit link none of the data is being returned from the model. Looking in the console it appears no XHR request is being made. If I force refresh then the XHR fires and the data appears.
// Init App
App = Ember.Application.create({
    LOG_TRANSITIONS: true,
    rootElement: '#myapp-ember'
});

// Declare routes
App.Router.map(function(){
    this.resource("products",function(){
        this.route('new');
        this.route("edit", { path: "/:id/edit" });
    });
});

// Model
App.Product = DS.Model.extend({
    title: DS.attr('string'),
    brand: DS.attr('string'),
    category: DS.attr('string'),
    type: DS.attr('string')
});

// Declare Data Store so Ember knows we're using Ember Data to handle our Model
App.Store = DS.Store.extend({
    revision: 11
});

// set our API namespace
DS.RESTAdapter.reopen({
    namespace: 'api/v1'
});

// forward from "/" to "/products"
App.IndexRoute = Ember.Route.extend({
    redirect: function(){
        this.transitionTo('products');
    }
});

App.ProductsIndexRoute = Ember.Route.extend({
    model: function(){
        return App.Product.find();
    }
});

App.ProductsEditRoute = Ember.Route.extend({
    model: function(params){
        return App.Product.find(params.id);
    }
});

Main HTML file here:

Like I said, index page (that redirects to /products) is showing all data as expected, links are created as they should be but when I land on the /products/ID/edit page I only see the
edit
 until I refresh which causes the product title to appear

A: There are two reasons that the ajax request is not firing:

*

*when using {{linkTo theRoute theObject}}, the model hook on theRoute is never called, because you already have the object to link to it! Instead, the routes model is set to be theObject

*Even if the model hook were called and it called App.Product.find(params.id);, it would return the original object, because you have loaded it into the datastore with App.Product.find().

The solution is either:

*

*Return all data in your list action, rather than just e.g. name and id. The list you get back from /products should have all the data for each item that you'd get from /products/1, products/2 etc, just all in a big list

*Use a related model, e.g. ProductData, and use a relation to load in the product data when you need it.

With this in mind, your {{linkTo}} should have just product instead of product.id in it.
The last piece of the puzzle is in your route definition - you have used the param :id, instead of :product_id which is what ember expects. Either change it to :product_id, or add an appropriate serialize hook to your ProductsEditRoute


text:
Q: How do I download a file using java Selenium WebDriver? I'm using Selenium 2.21.0 with Java 6.  How do I use the Selenium WebDriver API to download a file on a web page?  That is, there is a link that causes the download of an Excel file to start.  I would like to know how to initiate that download, determine when its finished, and then figure out where the file got downloaded to on my local system.

A: Once you click on any link to download a file, it depends on browsers behaviour like
Chrome Behaviour: It will start downloading the file by default, as soon as the user click on the link of any file.
IE Behaviour: IE displays a bar at the bottom of the window and displays the option to Save or Cancel the file download.
FireFox Behaviour: This will display an dialog box window and displays the option to Save or Cancel the file download.
So this can be achieved with the help of FireFox Profile.
And Before downloading any file you have to pass the MIME type of the file to FireFox Profile.
Some of the commonly used MIME types are:
Text File (.txt) – text/plain
PDF File (.pdf) – application/pdf
CSV File (.csv) – text/csv
MS Excel File (.xlsx) – application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
MS word File (.docx) – application/vnd.openxmlformats-officedocument.wordprocessingml.document
HERE IS THE CODE:
    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.FirefoxProfile;

    public class DownloadFiles {

    public static void main(String[] args) throws InterruptedException {
    //Create FireFox Profile object
    FirefoxProfile p = new FirefoxProfile();

    //Set Location to store files after downloading.
    profile.setPreference("browser.download.folderList", 2);

   //Set preference not to file confirmation dialogue
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
        "application/vnd.openxmlformats-
        officedocument.spreadsheetml.sheet");

  // Specify the local system path where to download
     p.setPreference("browser.download.dir", "D:\\downloads");
  // Pass Profile parameters in Firefox browser
    FirefoxDriver driver = new FirefoxDriver(profile);

    // Open APP to download application
    driver.get("http://url");

    // Click to download
    driver.findElement(By.xpath("//html[@attribute='value']")).click();

    Thread.sleep(5000);

    driver.close();

Hope it will solve your queries. Happy coding.

A: I am specifically focusing of the Firefox browser you can use where the download option comes with pop up option when any download link is been click by the visitor. It is shows two buttons and two radio button that gives us the option of save and open the file directly without downloading it afterwards if we find the file is useful we can download it explicitly though the download icon on the above toolbar of the Firefox browser.
So you can perform the following steps
1)  Clicking on the download link
WebDriver driver = new FirefoxDriver();

driver.findElement(By.linkText("somelink")).click();

The above code can help the WebDriver to identify the object and perform the action which is mentioned
2)  Once the download link is clicked the firefox browser will pop up a download dialog box with multiple option
Like Save radio button, open radio button, ok button, cancel button inorder to use this
You can use the Robot class or the Keys in the WebDriver
Like
Robot r = new Robot();

r.KeyPress(KeyEvent.VK_TAB);

you can use as many time the above code to press the tab button
r.KeyRelease(KeyEvent.VK_TAB);

you have to release the pressed key
lastly perform the enter
r.KeyPress(KeyEvent.VK_ENTER);

That's it it will help you to download the object when the download link is pressed
Hope it will help you


text:
Q: Next js: Can we use React router with Next js for server side rendering? Context:
I have a react app with multiple pages along with react router, some pages use references of react router to read route params. Now I am trying to create a new app with next js, so that I could server side render all my pages.
For this, I am trying to use react-router with next js, so that I don't want to make changes in the shared pages(which uses react router references)
Example:
<BrowserRouter>
   <Switch>
       <Route path={'/'}><Home /></Route>
       <Route path={'/about'}><About /></Route
   <Switch>
</BrowserRouter>

Consider both Home and About are react components and are not present under 'pages' folder
Problem:
When I use react router, it just does the client side rendering, I don't see any calls in network that renders the prerendered html for new route
Please share your thoughts!.


text: Q: How do I install the marble plasmoid in KDE 5.9.0? I recently upgraded from Kubuntu Utopic Unicorn (14.10) to Vivid Vervet (15.04).  In the process, I lost the marble plasmoid that showed a day/night world map on my background.  I have the marble package installed, which includes files such as /usr/bin/marble, /usr/share/kde4/services/plasma-applet-kworldclock.desktop, /usr/share/applications/kde4/marble.desktop, and others.  However, it does not include a .plasmoid file that I apparently need for installing new plasmoids.  How do I get back to the situation where I had the world day/night view on my desktop?


text:
Q: How can I assign a click event to an element outside a directive? I currently have a custom directive that truncates the text if it's longer than 3 lines. Right now it works if you click directly on the text itself but I would like to assign the click event to a button. This is my current code:
@Directive({
  selector: '[appReadMore]'
})
export class ReadMoreDirective {

  constructor() { }

  @HostBinding('class.truncate-text') get opened() {
    return this.isClosed;
  }
  @HostListener('click') open() {
    this.isClosed = (this.isClosed === true ? false : true);
  }

  private isClosed = true;

}

In my html file I have:

      {{Text 1}}

      {{Text 2}}

    <button appReadMoreTrigger>Read more</button>

and my css:
.truncate-text {
   overflow: hidden;
   display: -webkit-box;
   -webkit-line-clamp: 3;
   -webkit-box-orient: vertical;
}

When I click on each individual
 content the truncate-text class is applied and removed every other click but I would like that to happen to both
 tags when I click on the Read More button instead.
I tried creating a button directive to set the ReadMoreDirective isClosed value to true/false but it doesn't seem to work correctly (maybe because it's not in the scope of ReadMoreDirective?):
@Directive({
  selector: '[appReadMoreTrigger]',
})
export class ReadMoreTriggerDirective{

  constructor(private readMore:ReadMoreDirective) {}

  @HostListener('click') open() {
    this.readMore.open();
  }
}

When I try this it throws an error saying "No provider for appReadMoreDirective" and when I do put it in the list of providers, it seems like it creates a new ReadMoreDirective instance.
Thanks

A: Try something like this on button click event:
document.querySelectorAll('[appReadMore]').classList.toggle('truncate-text')


text:
Q: Issues with django-admin.py makemessages -l en I want to use multiple languages in my app
I do not want a locale file for english inside LOCALE folder but by mistake i have create this using this
django-admin.py makemessages -l en
so Please tell me how can I remove this 'en' folder which I have creates.
Because now if i try to create language folder for another language using this django-admin.py makemessages -l es it does not create.
WHY SO???

A: First of all there is no relation between having an english "en" directory in locale, and "es" not being created.
Secondly, if you want to remove en you could just remove that by rm -r en/
And es, as you are trying to do, has several variants.
probably you could try giving a a particular variant. This will help you with language codes. http://www.science.co.il/language/locale-codes.asp


text:
Q: Is it possible to set properties automatically in VB.NET? I'm actually more comfortable in Java language for developing apps.
But since my requirement now is getting tighter, I need to jump forward into VB.NET
well yeah... seems need to adapt some a bit.
Anyway, I typed a lot for making this setter and getter properties inside visual studio;
Public Property supplierId() As Integer
    Get
        supplierId = iSupplierId
    End Get
    Set(ByVal value As Integer)
        iSupplierId = value
    End Set
End Property

Do we have any automatic way to do setting and getting those properties of a variable?
Because I found that while I'm in java language and using Netbeans, setter and getter function (or sometimes we called as method) is quite a bit CLICK and CLICK. Everything is done! But here... when I tried in VB.Net, waw... typed, ... hehehe.
Do we have automatically way to insert those setter and getter properties of a variable inside VB.NET?

A: Yes, you have two different options:

*

*Code snippets. This sounds most similar to what you're used to in Netbeans. The IDE will automatically insert the "stub" for a property, and all you have to do is fill in the details.
To make this happen, all you have to do is start typing property. IntelliSense (auto-completion) will suggest that you're typing "Property". When that happens and you see the word "Property" highlighted, press the Tab key twice. It will insert a snippet that looks like this:
Private newPropertyValue As String
Public Property NewProperty() As String
    Get
        Return newPropertyValue
    End Get
    Set(ByVal value As String)
         newPropertyValue = value
    End Set
End Property

There are lots of these snippets built-in, all accessed the same way for the common keywords.

*Automatic properties. This is a simplified syntax for declaring properties, where the compiler will automatically create a private backing field. You can even specify a default value for the property using this syntax. It looks like this:
Public Property MyFavoriteColor As Color = Color.Green

Note, however, that this is only available starting with VB.NET version 10. Meaning that it will work as long as you're using Visual Studio 2010 or a later version, regardless of the .NET Framework version that you are targeting.


text:
Q: How do I allow VPN traffic only inside the network? I set up an OpenVPN server on Ubuntu 20.4. I created a client config. By connecting using this config, for example on my laptop and going to google.com, the route will be through the VPN network, which I can verify by going to whoer.net and seeing the VPN address, not the address of my provider. How do I get rid of this?
I need to allow only traffic inside the VPN network, all the rest of the client's traffic should go along the normal route.
My server config:
;local a.b.c.d

port 1194

;proto tcp
proto udp

;dev tap
dev tun

;dev-node MyTap

ca ca.crt
cert server.crt
key server.key  # This file should be kept secret
dh dh.pem
tls-auth ta.key 0

;dh dh2048.pem

;topology subnet

server 10.8.0.0 255.255.255.0

ifconfig-pool-persist /var/log/openvpn/ipp.txt

;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

;server-bridge

;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"

;client-config-dir ccd
;route 192.168.40.128 255.255.255.248

;client-config-dir ccd
;route 10.9.0.0 255.255.255.252

;learn-address ./script

push "redirect-gateway def1 bypass-dhcp"

push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.8.8"

client-to-client

;duplicate-cn

keepalive 10 120

tls-auth ta.key 0 # This file is secret

cipher AES-256-CBC

;compress lz4-v2
;push "compress lz4-v2"

;comp-lzo

;max-clients 100

;user nobody
;group nogroup

persist-key
persist-tun

status /var/log/openvpn/openvpn-status.log

;log         /var/log/openvpn/openvpn.log
;log-append  /var/log/openvpn/openvpn.log

verb 3

;mute 20

explicit-exit-notify 1

A: Get rid of
push "redirect-gateway def1 bypass-dhcp"

BTW, man openvpn and read documentation.


text:
Q: Cannot complete download from popup when prompting location with saveAs I've been working on a browser extension allowing users to generate epub files from any webpage.
To use the extension, a user has to click on a toolbar button which opens a popup. On the latter, after specifying a config, the user clicks on "Generate". Here is my issue though:
When I use the download API directly, and specify saveAs to false (i.e the user is NOT prompted where to save the file), then the download is completed as expected and the file saved in some location.
However, when I do set saveAs to true --- which is what I want in the final version --- then once the user has selected the location under which to save the file, the download fails. My intuition is that as soon as the file location window pops up, the popup looses focus and dies, which makes the download impossible to resume.
Is that the explanation? And is there a way to prevent such a problem? I do not find my use case to be much of a stretch, and do not get why popups associated with browser actions are not allowed to loose focus for file selection.
Another weird thing is that I'm pretty confident this problem only appeared recently in firefox, since when I started developing the extension, I had no issue.

A:
My intuition is that as soon as the file location window pops up, the
  popup looses focus and dies, which makes the download impossible to
  resume.

That's right...
Browser Action Popup is page and once page is closed,  async operations will lose their reference. It is best to pass async operations to the background script.

*

*You can use
runtime.sendMessage()
to pass a message to the background script to run the download.

*You can also use the async
runtime.getBackgroundPage() to run a function in the background script but the first option works
easier as you dont need to wait for the async response as in runtime.getBackgroundPage()


text:
Q: SQL UNION on group by and an aggregate query I wrote a query which presents the top 5 average amounts per id and then the averages of all ids except the top 5.
When i wrote it like this:
SELECT TOP 5 cast(lefty1.id as varchar) AS id, AVG(lefty1.amount) avg_amount
FROM left_table lefty1
GROUP BY id
ORDER BY AVG(amount) DESC
UNION
SELECT 'others' AS id, AVG(lefty2.amount) AS avg_amount
FROM left_table lefty2
WHERE id NOT IN(
SELECT TOP 5 lefty1.id AS id
FROM left_table lefty1
GROUP BY id
ORDER BY AVG(amount) DESC)

It gave me an error.
But when I wrote it like this:
SELECT *
FROM (SELECT TOP 5 cast(lefty1.id as varchar) AS id, AVG(lefty1.amount) avg_amount
FROM left_table lefty1
GROUP BY id
ORDER BY AVG(amount) DESC) AS a
UNION
SELECT 'others' AS id, AVG(lefty2.amount) AS avg_amount
FROM left_table lefty2
WHERE id NOT IN(
SELECT TOP 5 lefty1.id AS id
FROM left_table lefty1
GROUP BY id
ORDER BY AVG(amount) DESC)

It worked. why?

A: In a UNION query the ORDER BY clause comes last and affects the whole result. If you have ORDER BY in the partial queries (in order to apply a top clause) you need parentheses.
You would have placed the parentheses best as follows:
(
  SELECT TOP 5
    cast(lefty1.id as varchar) AS id,
    AVG(lefty1.amount) avg_amount
  FROM left_table lefty1
  GROUP BY id
  ORDER BY AVG(amount) DESC
)
UNION ALL
(
  SELECT
    'others' AS id,
    AVG(lefty2.amount) AS avg_amount
  FROM left_table lefty2
  WHERE id NOT IN
  (
    SELECT TOP 5 lefty1.id AS id
    FROM left_table lefty1
    GROUP BY id
    ORDER BY AVG(amount) DESC
  )
);

I also replaced UNION with the simpler UNION ALL as there are obviously no duplicates to remove.
BTW: Your result rows are not necessarily ordered. If you want them ordered you would have to specify an according order by clause at the end of the query.

A: You cannot have two ORDER BY clauses when you use a UNION/UNION ALL.
By wrapping your first SELECT in (SELECT...) AS A you bypassed this syntax check as the first ORDER BY now happens within the parenthesis, and BEFORE the UNION occurs.


text:
Q: How to open a URL (generated using XMLNode in MS Word) open in a new window? I am creating a word document report where a website hyperlink will be generated using below code.
Here I am using w:tgtFrame='_blank' but no use that it still gets opened in the same browser.
Please let me know for the solution.
<w:document>
                                                <w:p w:rsidR='00CA103F' w:rsidRDefault='00CA103F' w:rsidP='00264350'>
                                                    <w:r>
                                                        <w:t>Website: </w:t>
                                                    </w:r>
                                                    <w:hyperlink r:id='rId100' w:history='1' w:tgtFrame='_blank'>
                                                        <w:r w:rsidRPr='00CA103F'>
                                                            <w:rPr>
                                                                <w:rStyle w:val='Hyperlink' />
                                                                <w:rFonts w:cs='Arial' />
                                                                <w:u w:val='single' />
                                                            </w:rPr>
                                                            <w:t>" + Website + "</w:t>
                                                        </w:r>
                                                    </w:hyperlink>
                                                 </w:p>
                                             </w:document>"

A: I got this from another forum:
http://answers.microsoft.com/en-us/office/forum/office_2010-word/hyperlinks-in-msword-2010-target-frame-issue/e65c6ee2-6b3c-475f-8d01-1f5b49f91a09
It looks like Adobe issue that the URL will display in the same window and now solution yet from Adobe.


text:
Q: Authentication with Active Directory. Angular 2, Spring - theoretical I'm doing some research about authentication via Active Directory for internal application.
Application is divided in two parts - front-end in Angular 2, and back-end in Spring. I would like to add windows authentication to it to avoid providing credentials when you are already logged in, but i can't fully understand how possibly server knows the credentials of which user to compare with those stored in Active Directory. For example let's assume that I've logged into windows, my data are sent to Active Directory. Now I'm heading to website, which i would like to automatically authenticate me with http request sent to rest api. Rest server invokes some logic connected with authentication with Active Directory, and after success rest api sends token back to Angular. But the thing I'm missing is how server knows which credentials compare to know if user exists in AD. Should i somehow use angular to gain acces of user credentials stored in windows through browser? Or I'm missing something important here.


text:
Q: Cannot install ArchLinux on Acer Aspire containing windows 8 I am in a tad bit of a problem . I am trying to install ArchLinux on my new Acer Aspire V5
http://i.imgur.com/xvkvFPx.jpg . I have made my OS usb bootable using software from pendriveinux.com . I have used their software in the past and had success in installing Archlinux in my old laptop also from Acer . My last laptop was 3 years old .
After inserting the usb , I can see the bootup screen, where I get to choose from 64 bit and 32 bit architecture . On clicking any one of the options , I am greeting a screen that says that the kernel loading . However , after that the screen goes blank even though the laptop is on.
Someone in the Archlinux community on Google Plus said that there is a problem with secure booting , that is enabled on uefi mode . But as I fa as I know my laptop runs on legacy bootloader and there is no problem with secure booting .
Anybody came across this problem before ?

A: If this is a UEFI issue, this solution will not work. However, the black screen at boot is a classic problem and it is often solved by modifying the kernel parameters in GRUB. The most common solution is adding the nomodeset option (instructions adapted from here):

*

*When the GRUB menu shows up press E

*That should bring up the GRUB parameters. Navigate to the line beginning with linux, it should look something like this:
linux /boot/vmlinuz-linux root=UUID=978e3e81 quiet splash

Remove the quiet and splash (that makes messages appear that could be helpful if this does not work) and add nomodeset so that it looks like this:
linux /boot/vmlinuz-linux root=UUID=978e3e81 nomodeset

*Press B to boot with these changes.

Let me know if this fixes it. Also, search google for linux black screen boot or similar. you will find many many hits about this type of problem.
Useful links:

*

*https://wiki.archlinux.org/

*http://community.linuxmint.com/tutorial/view/842

*https://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it


text:
Q: Easy way to re-diagonalize a matrix after a minor addition? Let's say I have a real, symmetric positive semi-definite matrix $L$ that I have diagonalized. Let's say I have a very simple additional matrix
$\Delta(i,j)$ which is $-1$ at entries $i,j$ and $j,i$ and 0 everywhere else.
EDIT: Also, \Delta(i,j) is $1$ at entries $i,i$ and $j,j$.
Is there a simple way to re-compute the eigenvalues of $L + \Delta(i,j)$ for a given $i,j$ assuming that $L_{ij} = 0$?
(Context: $L$ is the Laplacian matrix of a graph. I have computed the eigenvalues and spectrum of $L$, now I'm adding an edge to the graph and want to (reasonably efficiently) recompute the Laplacian spectrum).

A: Let me give some initial thoughts.
Let's say $V$ is the orthogonal matrix whose columns are the eigenvectors of $L$, then $L = VDV^T$ for some diagonal matrix $D$.
Now let's wlog consider $i = 1, j = 2$.
We have $L' = L + \Delta_{1,2}$. Now, cool enough, we can do some math by hand to realize that $V \Delta_{1,2} V^T = \Delta_{1,2}$, so we can just put it into the decomposition:
$L' = V(D + \Delta_{1,2})V^T$
So matrix inside the parentheses is block-diagonal, with the upper left block a $2\times 2$ matrix, which is symmetric. Obviously then we can re-diagonalize $D + \Delta_{1,2}$, and the resulting orthogonal matrix will have a $2\times 2$ orthogonal block in the upper left, and the rest will be just the identity. (Note: Kinda reminds me of them rotations you use for iterative eigenvalue computation).
Huh, so I think I solved that?
EDIT: Note, this answer was for the previous, unedited version of the question. Will look into changed version later...
EDIT 2: Well, nothing really changes, it still holds that $\Delta_{1,2}$ is invariant under the orthogonal transformation.
Oops, got the matrix transposes wrong. $\Delta$ is in fact not invariant under orthogonal transformation. However, $\Delta$ can be written has
$uu^T$ for $u = (1, -1, 0, \dots)$, and thus it's a rank 1 update. This has been studied in the literature quite extensively, but the method isn't "trivial". Searching on this site here regarding rank 1 updates will provide some useful results...


text:
Q: Installing redmine_contacts plugin for bitnami_redmine I am trying to install redmine_contacts plugin for my redmine 2.2.3.0 (which is installed using BITNami installer), as in readme.rdoc:

*

*Copy redmine_contacts plugin to {RAILS_APP}/plugins on your redmine path

*Run bundle install --without development test RAILS_ENV=production

*Run rake redmine:plugins NAME=redmine_contacts RAILS_ENV=production

The first two steps was successful, but last executing last command, following error would occur:
(in /home/.../redmine-2.2.3-0/apps/redmine/htdocs)
Could not find sprockets-2.2.1 in any of the sources
Run bundle install to install missing gems.
To see if the sprockets library is installed by executing command: #bundle show sprockets, it shows a newer version of this library is installed:
/var/lib/gems/1.8/gems/sprockets-2.2.2

A: I think somehow the BitNami version of gem which is installed is not compatible with the sprockets-2.2.2 on the system and it requires 2.2.1. Maybe you should change to that version.
Try something like:
gem install sprockets -v 2.2.1


text:
Q: Rename files with specific pattern and trimming the rest of the name - bash I have my files with the below names, I am trying to get rid of the unwanted chars and just want to get the file name alone extracted.
File names
          abc_xyz.file name 1.unwanted part.xls
          abc_xyz.file 2.unwanted part.xls
          abc_xyz.file name 3.unwanted part.xls
          abc_xyz.file name 4.unwanted part.csv
          abc_xyz.file 5.unwanted part.csv
          abc_xyz.file name 6.unwanted part.csv

I want my files to be renamed which have only .xls in the extenstion and with the same name.
          file name 1.xls
          file 2.xls
          file name 3.xls
          abc_xyz.file name 4.unwanted part.csv
          abc_xyz.file 5.unwanted part.csv
          abc_xyz.file name 6.unwanted part.csv

I tried to use a for loop with sed and awk commands, but am not able to get it done. Here is what I have tried. I have saved the file names which I want to change in /tmp/dileep/files.txt and used below command to get the names that I want, into a different file.
          cut -d '.' -f2  < /tmp/dileep/files.txt | sed -e 's/._//g' > /tmp/dileep/names.txt

I am able to get the file names as what I want, but I am unable to iterate within them to rename them with the correct name.
for i in *.xls ; do cp $i /tmp/dileep/{awk -F '.' '{print $2}' < $i | sed -e
's/._//g'} ; done
sed: -e expression #1, char 8: unexpected `}'
cp: invalid option -- 'F'
Try `cp --help' for more information.
sed: -e expression #1, char 8: unexpected `}'
cp: invalid option -- 'F'
Try `cp --help' for more information.
-bash: $i: ambiguous redirect
sed: -e expression #1, char 8: unexpected `}'
-bash: $i: ambiguous redirect
sed: -e expression #1, char 8: unexpected `}'

Can you please let me know where I am going wrong

A: EDIT: To handle spaces or new lines in file names try following.
find /tmp -type f -name "*.xls" -print0 | while IFS= read -r -d '' file;
do
   new_file=$(echo "$file" | sed 's/\(.*\/\)[^.]*\.\([^.]*\.\).*/\1\2xls/')
   echo "mv \"$file\" \"$new_file\""
done

Above will print commands on terminal, to run them and rename files run following once you are Happy with above.
find /tmp -type f -name "*.xls" -print0 | while IFS= read -r -d '' file;
do
   new_file=$(echo "$file" | sed 's/\(.*\/\)[^.]*\.\([^.]*\.\).*/\1\2xls/')
   echo "mv \"$file\" \"$new_file\"" | sh
done

Also with find I have give /tmp as an example, please change it to complete path as per your need too.

Could you please try following.
for file in *.xls
do
   new_file=$(echo "$file" | sed 's/[^.]*\.\([^.]*\.\).*/\1xls/')
   echo "mv \"$file\" \"$new_file\""
done

As of now it is only printing mv(command to rename the files) on terminal once you are Happy you could run following code then.
With few shown samples output of above command will be as follows.
mv "abc_xyz.file 2.unwanted part.xls" "file 2.xls"
mv "abc_xyz.file name 1.unwanted part.xls" "file name 1.xls"
mv "abc_xyz.file name 3.unwanted part.xls" "file name 3.xls"

Run following only and only when you are Happy with above command's result since this will rename the files.
for file in *.xls
do
   new_file=$(echo "$file" | sed 's/[^.]*\.\([^.]*\.\).*/\1xls/')
   echo "mv \"$file\" \"$new_file\"" | sh
done

A: Supposing the file where the 'unwanted part' must be stripped from is /tmp/dileep/files.txt, the only thing you have to do is:
sed -i -e '/\.xls$/s/^abc_xyz\.//' -e 's/unwanted part\.xls/.xls/' /tmp/dileep/files.txt

The option -i means you make the change inside the file /tmp/dileep/files.txt.
Please clarify how to know which is the unwanted part.

A: Use rename, it provides lot of option for rule based rename, for the specific case, regular expression substitution seems like the approach
rename 's/\.unwanted part\././' file-list

# Bulk, wildcard
rename 's/\.unwanted part\././' file-list *".unwanted part."*

Use rename -n ... test the translation to avoid errors. The 'man rename' and 'info rename' can provide more information.
Note: there are multiple rename programs. On some systems, you will have to invoke the correct alternative with 'file-rename'.
Note 2: Remember to property quote the files - as they have embedded spaces


text:
Q: SQL SERVER Query result performance question When I run a simple query on server SSMS it takes 3 seconds. When I run the same query on my computer on SSMS it takes 35 seconds. What could be the reason? What should I check first?
I tried disable the antivirus samething.

A: First thing to check is if the execution plans are same or NOT. And then next thing is to check the connection properties from both the machines. The below whitepaper might help you there.
http://www.sommarskog.se/query-plan-mysteries.html