Q: Jenkins Pipeline as Code Groovy Error on Class Annotation Hi I am trying to use Jenkins pipeline as code (formally workflow). I am getting errors whenever I try to use Annotations on a class defined in the pipeline script.
Error
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
General error during canonicalization: Unexpected variable type: null

java.lang.UnsupportedOperationException: Unexpected variable type: null

JenkinsFile
import groovy.transform.ToString;
import groovy.transform.EqualsAndHashCode;
@EqualsAndHashCode
@ToString
class BarDeploy {
    String barFile
    String app
    String integrationServer
}

Any ideas why I cannot do this?
Full Stack Trace
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
General error during canonicalization: Unexpected variable type: null

java.lang.UnsupportedOperationException: Unexpected variable type: null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
    at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:71)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:81)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:190)
    at com.cloudbees.groovy.cps.CpsTransformer.visitVariableExpression(CpsTransformer.groovy:723)
    at org.codehaus.groovy.ast.expr.VariableExpression.visit(VariableExpression.java:70)
    at org.codehaus.groovy.ast.expr.VariableExpression$visit.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.ast.expr.BinaryExpression$visit.call(Unknown Source)
    at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
    at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_visitBinaryExpression_closure25.doCall(CpsTransformer.groovy:553)
    at sun.reflect.GeneratedMethodAccessor569.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_visitBinaryExpression_closure25.doCall(CpsTransformer.groovy)
    at sun.reflect.GeneratedMethodAccessor568.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at com.cloudbees.groovy.cps.CpsTransformer.makeChildren(CpsTransformer.groovy:278)
    at sun.reflect.GeneratedMethodAccessor545.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer.makeNode(CpsTransformer.groovy:253)
    at sun.reflect.GeneratedMethodAccessor544.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
    at com.cloudbees.groovy.cps.CpsTransformer.visitBinaryExpression(CpsTransformer.groovy:559)
    at org.codehaus.groovy.ast.expr.BinaryExpression.visit(BinaryExpression.java:49)
    at org.codehaus.groovy.ast.expr.BinaryExpression$visit.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.ast.stmt.ExpressionStatement$visit.call(Unknown Source)
    at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
    at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer.visitExpressionStatement(CpsTransformer.groovy:395)
    at org.codehaus.groovy.ast.stmt.ExpressionStatement.visit(ExpressionStatement.java:40)
    at org.codehaus.groovy.ast.stmt.ExpressionStatement$visit.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.ast.expr.StaticMethodCallExpression$visit.call(Unknown Source)
    at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
    at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:240)
    at sun.reflect.GeneratedMethodAccessor552.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy:342)
    at sun.reflect.GeneratedMethodAccessor580.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy)
    at sun.reflect.GeneratedMethodAccessor579.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at com.cloudbees.groovy.cps.CpsTransformer.makeChildren(CpsTransformer.groovy:278)
    at sun.reflect.GeneratedMethodAccessor545.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer.makeNode(CpsTransformer.groovy:253)
    at sun.reflect.GeneratedMethodAccessor544.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
    at com.cloudbees.groovy.cps.CpsTransformer.visitBlockStatement(CpsTransformer.groovy:341)
    at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69)
    at org.codehaus.groovy.ast.stmt.BlockStatement$visit.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.ast.expr.VariableExpression$visit.call(Unknown Source)
    at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
    at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:240)
    at sun.reflect.GeneratedMethodAccessor552.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy:342)
    at sun.reflect.GeneratedMethodAccessor580.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy)
    at sun.reflect.GeneratedMethodAccessor579.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at com.cloudbees.groovy.cps.CpsTransformer.makeChildren(CpsTransformer.groovy:278)
    at sun.reflect.GeneratedMethodAccessor545.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer.makeNode(CpsTransformer.groovy:253)
    at sun.reflect.GeneratedMethodAccessor544.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
    at com.cloudbees.groovy.cps.CpsTransformer.visitBlockStatement(CpsTransformer.groovy:341)
    at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69)
    at org.codehaus.groovy.ast.stmt.BlockStatement$visit.call(Unknown Source)
    at com.cloudbees.groovy.cps.CpsTransformer.visitMethod(CpsTransformer.groovy:166)
    at sun.reflect.GeneratedMethodAccessor606.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at com.cloudbees.groovy.cps.CpsTransformer$_call_closure1.doCall(CpsTransformer.groovy:95)
    at sun.reflect.GeneratedMethodAccessor605.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
    at groovy.lang.Closure.call(Closure.java:415)
    at groovy.lang.Closure.call(Closure.java:428)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1379)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1351)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods$each.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods$each.call(Unknown Source)
    at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.each(CpsDefaultGroovyMethods.groovy:26)
    at sun.reflect.GeneratedMethodAccessor582.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.groovy.runtime.metaclass.ReflectionMetaMethod.invoke(ReflectionMetaMethod.java:51)
    at org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod.invoke(NewInstanceMetaMethod.java:54)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callSafe(AbstractCallSite.java:82)
    at com.cloudbees.groovy.cps.CpsTransformer.call(CpsTransformer.groovy:95)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:970)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:548)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:526)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:503)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:302)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:281)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:731)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:743)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:106)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:376)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:343)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:212)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:410)

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:302)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:997)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:548)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:526)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:503)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:302)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:281)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:731)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:743)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:106)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:376)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:343)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:212)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:410)
Finished: FAILURE

A: This issue is known about, and still open, in Jenkins.  See https://issues.jenkins-ci.org/browse/JENKINS-40564


Q: JQuery interfering with lxml parsing I am trying to scrape a website which was probably written poorly, so when you initially perform a GET request on their page, it responds with 5 entries in a mixture of html, javascript, jquery because it's the visual part of the page, and if you want to get more entries, you click a button, which internally performs a POST request on the same page along with the "pagination value" which is like the page you want, like if you want entries 6 to 10, you give a value of "2" to pagination value and if you want entries 11 to 15, you give a value of "3", and it does this asynchronously and appends the data to the end of the previous result set.
Sending/receiving is not a problem, in fact, when I try to scrape the page using lxml, I can easily get values for the first 5 entries, however, when I have to get the second set of data, I provide pagination value of "2" and I expect xml data back, because xml/html would be easy to parse, but here's my problem:
They return a weird combination of jquery AND html. It goes something like this:
$(".entry:last").after("

some data

");

When you inspect their website, this works flawlessly, the last 5 entries that just got downloaded asynchronously via AJAX, gets added sequentially to the first 5 entries, I looked into the "after" method of Jquery and I can confirm that it just appends the 5 entries after the 5th element.
When I initially scraped their data, the root element was a html tag, so I could parse it using lxml, but the response that they provide the moment I have to parse the result of this pagination is this weird mix of Jquery and html.
Also I can assure you that there is only one "after" method, and everything else is html, so basically 2 lines of Jquery, the first line and the last line, so I assumed I would just blindly remove the first and last line and then parse it again, but the response object that I get from the requests library, which I use to perform the POST operation, returns it as one long line of data, so I cannot do any readLine() on it, to seperate the first line from the second line from the last line, it's all just one line to me. So I would like pointers on how I would solve something like this.
Thanks :D

A: So if I understand correctly, the question is "How do I extract HTML embedded in javascript code".
The quick and dirty solution is to use a regular expression to extract the HTML. This is going to be a little finicky because of quoting but it's not too bad, you need a regular expression which can match a string with escaped quotes, this one will do the trick for doublequotes, it will match anything between doublequotes which is not a double quote, or is a quoted double quote:
"((?:[^"]+|\\")+)"

You can then use that to create a regular expression which will extract the contents of the html string from it's jquery wrapping:
import re

mixed_js_html = r'$(".entry:last").after("

some data

");')

m = re.search(r'after\("((?:[^"]+|\\")+)"\)', mixed_js_html):
html_code = m.group(1)
html_code = html_code.replace('\\"', '"') # unescape quotes
print(html_code)
#

some data


Q: accessing current redux state in monaco editor action run function I have a monaco editor instance, and I add an action for the Ctrl+S Keys.
const addActions = (editor: editor.IStandaloneCodeEditor) => {
        editor.addAction({
            id: "save-element-action",
            label: "Save Element",
            keybindings: [KeyMod.CtrlCmd | KeyCode.KEY_S],
            precondition: undefined,
            keybindingContext: undefined,
            contextMenuGroupId: "navigation",
            contextMenuOrder: 1.5,

            // @param editor The editor instance is passed in as a convinience
            run: function (ed) {
                // TODO: saveElement is called but doesnt work yet because expressionEditorState is empty (Closure??)
                saveElement();
            },
        });
    };

in the saveElement function i want to access some state from my redux store
    const saveElement = (editor?: editor.ICodeEditor) => {
        if (expressionEditorState.elementContent === undefined || expressionEditorState.elementContent === "") {
            dispatch(createErrorAction("No content for element"));
            return;
        }

        dispatch(createSaveElementAction(user, expressionEditorState.elementContent, expressionEditorState.elementMetaData));
    };

the expressionEditorState is the same as the initial state (so empty).
The setup of the state is down with a custom hook and the useSelector hook.
How can i access the current state of redux in the run function of a monaco action?

A: if anyone is following up...
the solution is to use thunks (see redux-thunks). so i rewrote saveElement as thunk and just dispatch it.
dispatch(saveElement())


Q: How to specify different buld dirrectories for qmake? I use qmake. I have the following project structure:
/
|_SFMLWidgets
| |_...
| |_View.h
| |_View.cpp
| \_...
|
|_MapEditor
| |_...
| |_View.h
| |_View.cpp
| \_...
|
\_main.cpp

This views do different things. When I try to compile project I get compilation errors:
overriding recipe for target 'debug/View.o'
ignoring old recipe for target 'debug/View.o'

It happens because both views are builded in same directory. Is there any way to specify different build dirrectories?
I want something like:
/
|_debug
  |_SFMLWidgets
  | |_...
  | |_View.o
  | \_...
  |
  |_MapEditor
  | |_...
  | |_View.o
  | \_...
  |
  |_main.o
  \_main.exe

My .pro file

A: You can put each of SFMLwidgets and MapEditor in separate subdirs qmake project files. Shared configuration of the two subprojects can go into a pri file.


Q: Scrollbar in mIRC window Is it possible to remove or hide (hide to allow mouse wheeling) a scroll bar within a custom mIRC window.  The verticle scrollbar to be specific.
If you look to the very right of the picture you see the scrollbar.
Is there a way to remove it?

A: Yes, it can be removed.
I put together this AHK script that will hide the scrollbar in mIRC, and will keep it hidden even after resizing the window, as well as minimizing and restoring the window.
Load this up in autohotkey and it will start working once you click on a channel or anything in the switchbar.
~LButton::
MouseGetPos, , , , OutputVarControl
if (OutputVarControl = "mIRC_SwitchBar1" or OutputVarControl = "ScrollBar1")
{
WinWait, ahk_class mIRC
Control, Style, Hide, ScrollBar1
ControlGetPos, x,, Width,, mIRC_Channel1
ControlMove, mIRC_Channel1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Query1
ControlMove, mIRC_Query1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Status1
ControlMove, mIRC_Status1, ,, (Width + 18)
ControlGetPos, x,y, Width,Height, ListBox1
ControlMove, ListBox1, (x - 18),, ,
}
else if (OutputVarControl = "MSTaskListWClass1")
{
sleep, 500
if WinActive("ahk_class mIRC"){
WinWait, ahk_class mIRC
Control, Style, Hide, ScrollBar1
WinGetPos, X, Y, W, H, ahk_class mIRC
WinMove, ahk_class mIRC, , , , (W + 18),,
WinGetPos, X, Y, W, H, ahk_class mIRC
WinMove, ahk_class mIRC, , , , (W - 18),,
ControlGetPos, x,, Width,, mIRC_Channel1
ControlMove, mIRC_Channel1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Query1
ControlMove, mIRC_Query1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Status1
ControlMove, mIRC_Status1, ,, (Width + 18)
ControlGetPos, x,y, Width,Height, ListBox1
ControlMove, ListBox1, (x - 18),, ,
}
}
return

Assumes you use mIRC with one window maximized at a time inside the mIRC client like this. But you can have as many channels/query windows open, the script can handle switching between them.

A: No, The scroll-bar at the main custom window, can not be removed.


Q: Flashlight app (How to set screen brightness to Max?) I am working on a flashlight android app, which has an option for screen light(Max Brightness). How can I set an activity brightness to max with a button press?

A: This site has some information about the topic: http://www.tutorialforandroid.com/2009/01/changing-screen-brightness.html
The part what you need:
IHardwareService hardware = IHardwareService.Stub.asInterface(ServiceManager.getService("hardware"));
if (hardware != null)
        hardware.setScreenBacklight(brightness);

I didn't test it but it should work
UPDATE:
Alternate solution:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);


Q: StringBuilder, add Tab between Values I have a small problem:
I have a List of fields, with 3 Values. I want to build my String with these three Values,
delimited by a "TAB"..
Code:
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

The Tab is only between the 3rd and 2nd Value (Between 1st and 2nd is a Space ?!)
So I tried this:
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field + "\t").Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

Then I have 2 Tabs between 3rd and 2nd, one Tab between 1st and 2nd and also a Space
between 1st and 2nd..
(The Space is always there, how to avoid that?)
So what I have to do? Need only (without spaces..) a Tab between these Values..

A: I think you are confusing with tab char and sapces.
Are you expecting fixed no of white spaces to be added in the end of every word?
\t -> is just a tab char
The following is generated by the code given by you.
Java    StackOverflow   Banyan
Javasun StackOverflow   Banyan

The above two lines have same tab char b/w the 1st & 2nd Word.
if you type one more char in the end of "Javasun" it will extend like the following
Javaasunk   StackOverflow   Banyan

A: try
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field.Trim()).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

Basically I would just use return string.Join ( "\t", fields ); .

A: I would have thought you would want
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field);
    stringBuilder.Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

A: Instead of looping, you can use string.Join:
StringBuilder stringBuilder = new StringBuilder();

stringBuilder.AppendLine(string.Join("\t", fields));

Note that you can pass in the string directly to AppendLine as well.

A: Sub WarningWindow(ByVal content As String)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Dim gridHTML As String = sw.ToString().Replace("""", "'").Replace(System.Environment.NewLine, "")
    Dim sb As New StringBuilder()
    Dim a As String = "Welcomeback"
    'GridView1.RenderControl(hw)
    sb.Append("<script type = 'text/javascript'>")
    sb.Append("window.onload = new function(){")
    sb.Append("var printWin = window.open('', '', 'left=0")
    sb.Append(",top=0,width=1400,height=500,resize=yes,scrollbars =yes');")
    sb.Append("printWin.document.write(""")
    sb.Append("<INPUT Type=Button Name=Close Size=40  Value='Clsose(GSS)' onclick='self.close()'; / > ")
    sb.Append("</br><INPUT Type=Button Name=fu Size=40  Value='Alert' onclick=javascript:window.alert('" & a & "'); / > ")
    sb.Append("<INPUT Type=Text Name=gss Size=40  Value=300 ; / > ")
    sb.Append(" <P>")
    sb.Append(content)
    sb.Append(""");")
    sb.Append("printWin.focus();")
    sb.Append("printWin.show;};")
    sb.Append("</script>")
    ClientScript.RegisterStartupScript(Me.GetType(), "suvesh", sb.ToString())
End Sub


Q: Working with array as table and employee hours and salaries I need help with an array that shows a list of employees, their hours, their wage and then totals the pay for each employee and then totals the hours for all employee's hours, wages and total employee pay. I have code so far as:
import java.util .*;
public class Employee
{
    public static void main(String[] args)
{
String wages[][] =
    {
        {"Emp", " " , "Hours", " ", "Wages", " ", "Total Pay"},
        {"Bobby", " ", "45", " ", "35"},
        {"Rick", " ", "15", " ",  "33"},
        {"Mike", " ", "66", " ", "50"},
        {"Jayme", " ", "15", " ",  "45"},
        {"Total", " ", " ", " ", " ", " "}
    };
  for (int i = 0; i < wages.length; i++)
  {
for (int j = 0; j < wages[i].length; j++)
{
    System.out.print(wages[i][j]);
}
System.out.println();

 }
          Integer H1 = Integer.valueOf(wages[1][2]);
          Integer H2 = Integer.valueOf(wages[2][2]);
          Integer H3 = Integer.valueOf(wages[3][2]);
          Integer H4 = Integer.valueOf(wages[4][2]);

          int sumH = 0;

          sumH = H1 + H2 + H3 + H4;

  System.out.println();
  System.out.println("The Sum of All Employee Hours is: " + sumH);

          Integer W1 = Integer.valueOf(wages[1][4]);
          Integer W2 = Integer.valueOf(wages[2][4]);
          Integer W3 = Integer.valueOf(wages[3][4]);
          Integer W4 = Integer.valueOf(wages[4][4]);

          double over = 0;
          double  totalPay1 = 0;

          if (H1 <= 40)
          {
        totalPay1 = W1 * H1;
          }
            else
              {

                 totalPay1 = (W1 * H1)  + ((H1- 40 ) * (W1 * 1.5));
               }

        double  totalPay2 = 0;

          if (H2 <= 40)
          {
        totalPay2 = W2 * H2;
          }
            else
              {

                 totalPay2 = (W2 * H2)  + ((H2) * (W2 * 1.5));
               }

        double  totalPay3 = 0;

          if (H3 <= 40)
          {
        totalPay3 = W3 * H3;
          }
            else
              {

                 totalPay3 = (W3 * H3)  + ((H3) * (W3 * 1.5));
               }

        double  totalPay4 = 0;

          if (H4 <= 40)
          {
        totalPay4 = W4 * H4;
          }
            else
              {

                 totalPay4 = (W4 * H4)  + ((H4) * (W4 * 1.5));
               }

      double grandTotal = 0;

      grandTotal = totalPay1 + totalPay2 + totalPay3 + totalPay4;

      System.out.printf("The total number of Pay is $%.2f.%n", grandTotal);

      //Bobby's totalPay1

          double bobbyTotal = (double) 0;

          bobbyTotal = totalPay1;

          System.out.printf("Bobby's total pay is $%.2f.%n", bobbyTotal);

        //Ricks Total
          double rickTotal = (double) 0;

          rickTotal = totalPay2;

          System.out.printf("Rick's total pay is $%.2f.%n", rickTotal);

            //Mikes Total
          double mikeTotal = (double) 0;

          mikeTotal = totalPay3;

          System.out.printf("Mike's total pay is $%.2f.%n", mikeTotal);

            //Jaymes Total
          double jaymeTotal = (double) 0;

          jaymeTotal = totalPay4;

          System.out.printf("Jayme's total pay is $%.2f.%n", jaymeTotal);
   }

 }

I need to be able to print the totals for each employee as the last column in the array [x][6]
I was able to print them out but I want it to look more like a a table. Along with that my formulas might be off because I don't think it's factoring in overtime right. I think there might be something wrong with my IF ELSE  statement.
The array should print out like
Emp   Hours   Wage   Total
Bobby  45       35          $1662.50
Rick      15       33          $495.00
Mike     66        50          $3,950.00
Jayme   15       45         $675.00
Total      141    163         $6,782.50

What I've got is:
Emp Hours Wages Total Pay
Bobby 45 35
Rick 15 33
Mike 66 50
Jayme 15 45
Total

The Sum of All Employee Hours is: 141
The total number of Pay is $11257.50.
Bobby's total pay is $1837.50.
Rick's total pay is $495.00.
Mike's total pay is $8250.00.
Jayme's total pay is $675.00

A: Using a class rather than a String[]
We identified that each employee has name, hours, wage, total values, instead of representing this in a String[], we can use a class
class Employee{

   private String name;
   private int hours;
   private int wage;
   private int total;

   public Employee(String name, int hours, int wage){
       this.name = name;
       this.hours = hours;
       this.wage = wage;
       this.total = hours * wage;
   }

   public String getName(){
       return name;
   }

   public int getHours(){
       return hours;
   }

   public int getWage(){
       return wage;
   }

   public int getTotal(){
      return total;
   }

   public String toString(){
       return String.format("%s %d %d %d", name, hours, wage, total);
   }
}

Now we have defined how an Employee looks like, so now we can use Employee
Putting the Employee into a List
public class EmployeeData{
    public static void main(String[] args){
       List<Employee> employees = new ArrayList<Employee>();

       Employee bobby = new Employee("Bobby", 45, 35);
       Employee rick = new Employee("Rick", 15, 33);
       Employee mike = new Employee("Mike", 66, 50);
       Employee jayme = new Employee("Jayme", 15, 45);

       employees.add(bobby);
       employees.add(rick);
       employees.add(mike);
       employees.add(jayme);

       //Now we have added all the employees, so we can just run through them
       System.out.println("Employee Hours Wage Total");
       for(Employee employee: employees){
          System.out.println(employee.toString());
       }
    }
}

Now you don't have to calculate everything many times, but just run through the list once, if you want to change the total, then you can calculate it inside here
public Employee(String name, int hours, int wage){
    this.name = name;
    this.hours = hours;
    this.wage = wage;
    this.total = hours * wage;
}


Q: WSDL UNKNOWN for input/output I've recently started developing a SOAP web service but running through some issues I can't resolve. So I've built a PHP client to test out the service. When I invoke __getFunctions using soapclient through my php script, I receive the following
array(1) { [0]=> string(31) "UNKNOWN doOrder(UNKNOWN $order)" }

Why are my input and output data types unknown?
WSDL:
<?xml version="1.0"?>
<definitions name="PlaceOrders"
         targetNamespace="urn:PlaceOrders"
         xmlns:tns="urn:PlaceOrders"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
         xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
         xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
         xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Orders">
  <xsd:element name="orderXML" type="xsd:base64Binary" />
  <xsd:element name="orderResponse" type="xsd:string" />
</xsd:schema>
</types>

<message name="doOrder">
<part name="order" type="tns:orderXML" />
</message>

<message name="doOrderResponse">
<part name="return" type="tns:orderResponse" />
</message>

<portType name="OrderPort">
  <operation name="doOrder">
    <input message="tns:doOrder" />
    <output message="tns:doOrderResponse" />
  </operation>
</portType>

<binding name="OrderBinding" type="tns:OrderPort">
  <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="doOrder">
  <soap:operation soapAction="urn:OrderAction" />
  <input>
    <soap:body use="encoded" namespace="urn:Orders" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
  </input>
  <output>
    <soap:body use="literal" namespace="urn:Orders" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
  </output>
</operation>
</binding>

<service name="OrderService">
<port name="OrderPort" binding="tns:OrderBinding">
  <soap:address location="[MYLINK]" />
</port>
</service>

</definitions>

SOAP Client:
ini_set('display_errors',1);
ini_set('soap.wsdl_cache_enabled', 0);
$client = new SoapClient([MYLINK]);
var_dump($client->__getFunctions());


Q: JPA/Hibernate How to add duplicate values to a List<> with a @OneToMany mapping I am getting an error every time I try to add duplicate products to the Client class.
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_8opk6otadh2pkvi9bghguwp89"
  Detail: Key (products_id)=(500010) already exists.

My entities
@Entity
public class Client {
    @Id
    private String id;

    @OneToMany
    private List<Product> products;
}

@Entity
public class Product {
    @Id
    private String id;

    private Boolean foreign;
    private Integer price;
}

When I call .save() hibernate is trying to re-save an already existing Product. I believe this is due to the how it cascades things.
public Client addNewProduct(Client client, Product newProduct) {
    List<Product> products = client.getProducts();
    products.add(newProduct);
    client.setProducts(products);
    return clientRepository.save(client);
}

I just want to be able to add duplicates to a List<>. I believe this is & should be a uni-directional relationship.

A: This does not work with your current relationship, I don't understand why you would want to add duplicates, but if you have to, then you'd have to create a new entity for that. One example would be something like this:
@Entity
public class ProductBatch {

  @Id
  private String id;

  @OneToOne
  private Product product;

  private Integer count;

  // getter & setter
}

and then you change your Client like this:
@Entity
public class Client {

    @Id
    private String id;

    @OneToMany
    private List<ProductBatch> products;
}

this makes something like this possible for your addNewProduct function:
public Client addNewProduct(Client client, Product newProduct) {
    List<ProductBatch> products = client.getProducts();
    boolean exists = false;
    for(ProductBatch product : products) {
        if(product.getProduct().equals(newProduct)) {
            product.setCount(product.getCount() + 1);
            exists = true;
        }
    }
    if(!exists) {
        BatchProduct product = new BatchProduct();
        product.setProduct(newProduct);
        product.setCount(0);
        products.add(product);
    }
    client.setProducts(products);
    return clientRepository.save(client);
}

A: That has nothing to do with JPA or Hibernate. A constraint is a Database constraint and it is right. If a Foreign Key is already part of the table, trying to add it again, violates this constraint. An ID is unique and it should stay that way. So adding duplicates (at least with the same ID) will not work.


Q: Javascript ! and !! differences
Possible Duplicate:
What is the !! operator in JavaScript?

What is the difference between these two operators? Does !! have special meaning, or does it simply mean you are doing two '!' operations. I know there are "Truth" and "Truthy" concepts in Javascript, but I'm not sure if !! is meant for "Truth"

A: !! is just double !
!true // -> false
!!true // -> true

!! is a common way to cast something to boolean value
!!{}  // -> true
!!null // -> false

A: Writing !! is a common way of converting a "truthy" or "falsey" variable into a genuine boolean value.
For example:
var foo = null;

if (!!foo === true) {
    // Code if foo was "truthy"
}

After the first ! is applied to foo, the value returned is true. Notting that value again makes it false, meaning the code inside the if block is not entered.


Q: Efficient iteration through AD Group Membership I'm just going to five straight in with what I have, the scenario is a little too complex to explain off the mark.
XML config:
  <Groups>
    <Group priority="1" name="testGroup1" profile="testProfile1"/>
    <Group priority="2" name="testGroup2" profile="testProfile2"/>
    <Group priority="3" name="testGroup3" profile="testProfile3"/>
    <Group priority="4" name="testGroup4" profile="testProfile4"/>
  </Groups>

Powershell:
$userProfileHash = [ordered]@{}
# Itterate through groups
foreach ($group in ($homeNode.ApplicationMethod | ? {$_.id -eq "adgroup"}).Groups.Group | Sort-Object $_.priority) {
  # Get group members, Itterate through them
  Get-ADGroupMember -Identity $group.name | ForEach-Object {
    # Add to ordered hash
    try {
      $userProfileHash.Add($($_.samaccountname),$group.profile)
    } catch {#don't want to see errors, there may be many}
  }
}

Now I'll to to explain:
To protect against a user being a member of more than 1 of the defined groups. I sort the groups by priority (in the foreach expression) and then use the hashtable rule that the key must be unique.
This ensures that each user is only added once and that they will be assigned the profile of the group they appeared in first.
I don't really like this approach, but it was the quickest of the approaches I tried: 5 Seconds with 1100 test users.
Question:
How can I speed up this code?
(there may be tens of thousands of users when this is in production)

A: Hash table operations are very efficient, and if you're getting a lot of errors due to duplicate adds you might be better off eliminating the error handling.  If you sort the priorities in descending order then you can do this:
$userProfileHash[$_.samaccountname] = $group.profile

and eliminate the Try/Catch.  Duplicate memberships will just get overwritten and the last entry written for each user will be the highest priority group profile they belong to.
Edit: the original command I posted used the += operator.  That's not correct for this application, and I've corrected the code.


Q: Javascript files getting included multiple times For some reason my javascript files are getting included in my source 12 times.  Other members of my team, using the same source, do not have this problem.
Any ideas what could cause this?

A: Have you made sure that you are precompiling all of your assets?
Try using:
bundle exec rake assets:precompile


Q: Cancelling a background worker without worker.CancellationPending check? I have a Validator class which has a Validate function, This validate function loops over bunch of file and validates them. User can cancel the validate process.
For cancelling the back ground worker I need ta reference of the background worker instance in Validtor class (for cancelling the validation process) and call CancellationPending on it.
But the problem is  Validator class can't have reference to background worker because there are times when we call the "Validate" function synchronously and Validator class does not have to know this.
So far  I have tried replacing  backgroundworker.CancellationPending check with some flag e.g. IsCanceled which do not seems to work.

A: You have two options:

*

*Make two overloads of the Validate method. One that is synchronous and one that is asynchronous and cancellable.

*Change your Validate method so that the calling code is responsible for looping over the files (consider an iterator method, using yield)

I'd go with option 1 as it is a smaller change.


Q: How to use std::chrono::milliseconds as a default parameter Scenario
I have a C++ function which intakes a parameter as std::chrono::milliseconds. It is basically a timeout value. And, it is a default parameter set to some value by default.
Code
#include <iostream>
#include <chrono>

void Fun(const std::chrono::milliseconds someTimeout = std::chrono::milliseconds(100)) {
    if (someTimeout > 0) {
        std::cout << "someNumberInMillis is: " << someNumberInMillis.count() << std::endl;
    }
}

int main() {
    unsigned int someValue = 500;
    Fun(std::chrono::milliseconds(someValue))
}

Issue
All of above is okay but, when I call Fun with a value then fails to compile and I get the following error:

No viable conversion from 'bool' to 'std::chrono::milliseconds' (aka
  'duration >')

Question:
What am I doing wrong here? I want the caller of Fun to be explicitly aware that it is using std::chrono::milliseconds when it invokes Fun. But the compiler doesn't seem to allow using std::chrono::milliseconds as a parameter?
How use std::chrono::milliseconds as a default parameter?
Environment
Compiler used is clang on macOS High Sierra

A: With the other syntax errors fixed, this compiles without warnings in GCC 9:
#include <iostream>
#include <chrono>

void Fun(const std::chrono::milliseconds someNumberInMillis
                                         = std::chrono::milliseconds(100))
{
    if (someNumberInMillis > std::chrono::milliseconds{0}) {
        std::cout << "someNumberInMillis is: " << someNumberInMillis.count()
                  << std::endl;
    }
}

int main()
{
    unsigned int someValue = 500;
    Fun(std::chrono::milliseconds(someValue));
}


Q: use gruntjs in root file my file tree
|-  root
|-- gruntfile.js
|-- package.json
|-- lib (jQuery & other)
|-- webapp
|---- App-1
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- package.json(use to require other modules)
|---- App-2
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- package.json(use to require other modules)
... ...
|---- App-n

In my file system,most app use a same task.Make gruntfile in every "App" file is not easy.
so,how can i use a gruntfile on "root",and use it on my "App" file?
thanks~:)

A: Unless all your apps are going to be exactly the same, use a new gruntfile for each app. I'm guessing each of your apps will all be different as you've duplicated the src folder within each in anticipation.
I don't recommend a global dependency setup. As time goes on, each of your apps will diverge and the amount of your apps will increase. When it comes time to upgrade jQuery or any other dependency in your root/lib folder... you will be forced to upgrade every single app.
The small convenience now is totally not worth it later.
Instead, just install everything locally and then you can upgrade each app as needed without breaking the other apps. If you come across duplicate code in your apps, consider moving it into a module. Create your module just like another app, then type npm link to make it installable. Then in each of your apps do npm link mymodule to install your module to the node_modules/mymodule folder. Here is an example file tree:
my file tree
|-  root
|-- devmodules
|---- mymodule
|------ index.js
|------ package.json
|-- webapps
|---- App-1
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- node_modules (jQuery & other)
|------- Gruntfile.js
|------- package.json(use to require other modules)
|---- App-2
|------- src(app src)
|---------- js
|---------- css
|---------- images
|------- node_modules (jQuery & other)
|------- Gruntfile.js
|------- package.json(use to require other modules)
... ...
|---- App-n


Q: Aggregate by name and average value per day in SQL I have data of the following format in a table (I have only shown values for two hours, but in reality I have values for all 24 hours):
Name    Availability           Date             ItemID
--------------------------------------------------------
S1          75        2014-11-11 19:00:00.000   1124023
S1          80        2014-11-11 20:00:00.000   1124023
S2          60        2014-11-11 19:00:00.000   1124010
S2          50        2014-11-11 20:00:00.000   1124010

I would like to get the average availability for the entire day in the following format in a view:
Name    Availability       Date     ItemID
--------------------------------------------------------
S1         77.5         2014-11-11  1124023
S2          55          2014-11-11  1124010

It's okay if Date in the output shows up as 2014-11-11 0:00:00.000 as well.
I tried the following, but it doesn't work. Any help would be greatly appreciated.
SELECT Name, AVG(Availability), CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME) AS Expr1, ItemID
    FROM dbo.ServiceAvailability
    GROUP BY CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME)

A: Your current query is very close, you are missing a few columns in your GROUP BY clause. I'd also suggest a shorter way to get the date without time.
SELECT
  Name,
  AVG(cast(Availability as decimal(10, 2))),
  CAST([Date] as date) AS Expr1,
  ItemID
FROM dbo.ServiceAvailability
GROUP BY Name, CAST([Date] as date), ItemID

See Demo. Since you are using SQL Server 2014, you can just cast your datetime column as a date - which drops the time portion.  I'd also suggest casting your Availability column to something other than an int so you get a decimal.
Since you are using an aggregate function any columns in the SELECT list that aren't being aggregated need to be included in the GROUP BY clause, so you need to include Name and ItemID.


Q: Silverlight 4.0 - image cropping with mouse events I have a task to build image cropping functionality in Silverlight 4.0 application. What I need to do is to have user on the left button mouse click select area to remain after cropping is applied and then call some other event (button click maybe) to apply that cropping itself.
I did develop similar functionality for rotation. I am pretty sure it is possible to do for cropping as well but that task is probably rare at this point for I can't find tutorials on the topic in the net.
If you guys can get me a snippet to begin with or point to some good tutorial about Silverlight 4.0 image cropping, I would appreciate it.
Thanks!

A: As far as cropping images are concerned you can use the WriteableBitmapEx library on codeplex.
Now you just need to draw a rectangle on a canvas containing the image to describe the crop region.


Q: TIdTCPServer gets stuck when connecting the second time I am using TIdTCPClient to get a file list all works well but when i close the client application and open it again i don't receive any event on TCPServer onExecute though the TIdTCPClient successfully connects to it and i am not able to send the file list.
What am i doing wrong ?
Some code :
procedure TTaifun.csConnected(Sender: TObject);
begin
  cs.IOHandler.WriteLn('FILE_LIST|NOW'); //Sending a request to server for the files
  fname := cs.IOHandler.ReadLn(nil); //Got the file names
  files := ExplodeString(fname,'|'); // Parse the files
end;

procedure TTaifun.svExecute(AContext: TIdContext);
var
  cmds, flist: TStringList;
  i: Integer;
  tmp: string;
  FS : TFileStream;
begin
  CSection.Enter; //Enter critical section
  cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn(nil), '|');
  try
    if cmds[0] = 'FILE_LIST' then //Check command received
    begin
      flist := TStringList.Create;
      flist.LoadFromFile(MyPath + 'files.dat');
      tmp := '';
      for i := 0 to flist.Count - 1 do
      begin
          tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' +
          BoolToStr(FileExists(MyPath + 'Thumbs\' +
          ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing
      end;
      AContext.Connection.IOHandler.WriteLn(tmp); //Send the string
    end
 finally
  CSection.Leave; //Leave critical section
 end;
end;

A: You are not protecting your critical section from exceptions.  When the client disconnects, an exception will be raised by either ReadLn() or WriteLn() (depending on timing) to terminate the thread for that client.  The next time the OnExecute event is called for a different thread, the critical section will still be locked and cannot be re-entered again, deadlocking your code.  Add a try/finally to your code to guard against that, eg:
procedure TTaifun.svExecute(AContext: TIdContext);
var
  ...
begin
  CSection.Enter; //Enter critical section
  try
    ...
  finally
    CSection.Leave; //Leave critical section
  end;
end;

With that said, why are you using a critical section to begin with?  The code you showed is thread-safe by itself, it does not need to be protected from concurrent access:
procedure TTaifun.svExecute(AContext: TIdContext);
var
  cmds, flist: TStringList;
  i: Integer;
  tmp: string;
begin
  cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|');
  if cmds[0] = 'FILE_LIST' then //Check command received
  begin
    tmp := '';
    flist := TStringList.Create;
    try
      flist.LoadFromFile(MyPath + 'files.dat');
      for i := 0 to flist.Count - 1 do
      begin
        tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' +
          BoolToStr(FileExists(MyPath + 'Thumbs\' +
          ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing
      end;
    finally
      flist.Free;
    end;
    AContext.Connection.IOHandler.WriteLn(tmp); //Send the string
  end;
end;

Alternatively:
procedure TTaifun.svExecute(AContext: TIdContext);
var
  cmds, flist: TStringList;
  i: Integer;
begin
  cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|');
  if cmds[0] = 'FILE_LIST' then //Check command received
  begin
    flist := TStringList.Create;
    try
      flist.LoadFromFile(MyPath + 'files.dat');
      for i := 0 to flist.Count - 1 do
      begin
        flist[i] := flist[i] + ',' + GetFileSize(flist[i]) + ',' +
          BoolToStr(FileExists(MyPath + 'Thumbs\' +
          ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true); //Do some parsing
      end;
      flist.Delimiter := '|';
      flist.StrictDelimiter := True;
      AContext.Connection.IOHandler.WriteLn(flist.DelimitedText); //Send the string
    finally
      flist.Free;
    end;
  end;
end;


Q: Why no type mismatch in call to CoCreateInstance function in the Windows API? I'm trying to translate this example of calling the WMI/COM using winapi from C++ to Rust, but there's something I don't understand in the original code. Here's a function call in the C++ code:
hres = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pLoc);

What puzzles me is the type of the first and fourth arguments. Take the fourth argument, for example. If we look at the definition of CoCreateInstance, the fourth argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the fourth argument should be a pointer to a GUID object.
But if you look at what I think is the definition of IID_IWbemLocator, it's defined as a GUID (using the DEFINE_GUID macro). So it looks like we're passing a GUID as an argument when really we should be passing a pointer to a GUID. Why does this code compile?
By comparison, in Rust I have to pass a reference to IID_IWbemLocator.
Apologies if the answer is really simple, I'm pretty unfamiliar with both C++ and the Winapi.

A:
the third argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the third argument should be a pointer to a GUID object.

The documentation you linked is incorrect. I suspect it was written for C.
In C++, REFIID and REFCLSID are defined as IID references in Windows headers, like so:
#ifdef __cplusplus
#define REFIID const IID &
#else
#define REFIID const IID * __MIDL_CONST
#endif

#ifdef __cplusplus
#define REFCLSID const IID &
#else
#define REFCLSID const IID * __MIDL_CONST
#endif


Q: replacing elements in a vector of vectors C++ i have a vector of vector that contain just periods
(".") so far and I want to replace certain coordinates on the grid with a symbol that I am taking in from an input file. I am using the replace method but keep getting this error

" error: no matching function for call to replace(std::basic_string, std::allocator >&, std::basic_string, std::allocator >&, const char [2], const char*)"

I am not sure what that error means. I appreciate any and all help. Thanks in advance
here is my code
 #include <vector>
 #include <string>
 #include <fstream>
 #include <iostream>
 #include <algorithm>

using namespace std;

int main()
{
string locationfilename, filenames,symbol;
int numRows, numCols, startRow, startCol, endRow, endCol, possRow, possCol, id;

cout<< "Enter Locations Filename"<<endl;
cin>>locationfilename;
cout<< "Enter Names Filename"<<endl;
cin>>filenames;

ifstream locations(locationfilename.c_str());
ifstream names(filenames.c_str());

locations>>numRows>>numCols>>startRow>>startCol>>endRow>>endCol;

vector <string> rows(numCols,".");
vector< vector<string> > grid(numRows,rows);

locations>>possRow>>possCol>>symbol>>id;
while(!locations.fail())
{

    if(possRow>numRows || possCol>numCols)
    {
        cout<<id<< " out of bounds-ignoring"<<endl;
    }
    else
    {
    replace(grid.at(possRow).front(),grid.at(possRow).back(),".",symbol.c_str());
    }

locations>>possRow>>possCol>>symbol>>id;
}

}

A: As pointed by Chris, the parameters you passed in std::replace are not the correct ones. std::replace expects iterators for its first two parameters but you are passing references.
You can use begin() and end() to get the iterators:
std::replace(grid.at(possRow).begin(), grid.at(possRow).end(), ".", symbol.c_str());


Q: Soap Request as String convert it into java object I'm getting a SOAP request as string, from which I want to extract a Java object. Is it possible? If yes, then how? What API can be used for this?

A:
I'm getting a SOAP request as string, from which I want to extract a
  Java object. Is it possible?

Yes.

If yes, then how?

You need to convert the String into something that JAXB can unmarshal.  Examples include a StringReader or XMLStreamReader.

What API can be used for this?

Since a SOAP message contains more information than what corresponds to the domain model I would recommend using JAXB with a StAX XMLStreamReader.  You use StAX to parser the String.  Then you advance the XMLStreamReader to the element that contains the content you wish to unmarshal.  Then you unmarshal the XMLStreamReader at that point.

*

*http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html


Q: PostgreSQL using constants in foreign key The syntax for Foreign Key, as described in official documentation, includes set of column from table A referencing set of column from table B.
Is it possible to use Constant in foreign key declaration?
The problem is, I have table DICTIONARIES which contains all dictionary values, discriminated by TYPE. I know it's not good design, but unfortunatelly, I have not much to say, as the DB admin wants to 'minimize the number of tables'...
Is it possible to achieve something like that:
CREATE TABLE PERSON (
  id integer primary key,
  country_id integer,
  ...
  FOREIGN KEY ('COUNTRY', country_id) REFERENCES DICTIONARIES(TYPE, ID)
)

It would effectively solve the issue. I'm aware I can add column to the table person, which will has only one possible value 'COUNTRY', or I could write a trigger, but I'd prefer to avoid that to keep design cleaner.

A: A foreign key constraint is from one table's columns to another's columns, so, no.
Of course the database should have a table COUNTRY(country_id). Commenters have pointed out that your admin is imposing an anti-pattern.
Good, you are aware that you can define a column and set it to the value you want and make the foreign key on that. That is an idiom used for avoiding triggers in constraining some subtyping schemes.
You may be able to compute a 'COUNTRY' column depending on your DBMS, at least.
Your question is essentially this one, see the end of the question & the comments & answers.
(Lots of functionality would be trivial to implement. Perhaps the difficulty (besides ignorance of consumers) is that arbitrary constraints become quickly expensive computationally. That might just get vendors aggravation. Also, optimization in SQL is impeded by its differences from the relatonal model.)

A: For Posrgres not having computed (or constant) columns, you can force them to a fixed value column, using DEFAULT plus (maybe) a check. This may be ugly, but it works:
CREATE TABLE dictionaries
  ( id integer primary key
  , typename varchar NOT NULL CHECK ( typename IN ('person' ,'animal' ,'plant' ))
  , content varchar NOT NULL
  -- ...
  , UNIQUE (typename, id)
  , UNIQUE (typename, content)
  );

CREATE TABLE person
  ( id integer primary key
  , typename varchar NOT NULL DEFAULT 'person' CHECK( typename IN ('person' ))
  , species_id integer
  -- ...
  , FOREIGN KEY (typename, species_id) REFERENCES dictionaries(typename, id) -- DEFERRABLE INITIALLY DEFERRED
);

INSERT INTO dictionaries( id, typename, content) VALUES
 ( 1 , 'person' , 'Bob')
,( 2 , 'person' , 'Alice')
,( 11 , 'animal' , 'monkey')
,( 12 , 'animal' , 'cat')
,( 13 , 'animal' , 'dog')
,( 21 , 'plant' , 'cabbage')
        ;
SELECT * FROM dictionaries;

        -- this should succeed
INSERT INTO person( id, species_id) VALUES
 ( 1,1 )
,( 2,2 )
        ;
        -- this should fail
INSERT INTO person( id, species_id) VALUES
 ( 3,11 )
,( 4,12 )
        ;


Q: CocoaPodspec unresolved identifier error I am trying to create my own framework by CocoaPodspec.
I need some help to resolve the issue.
And I got an error after run command pod lib lint --no-clean --verbose interminal :
error: use of unresolved identifier 'GlobalLoaderView'

This is Podspec file content :
Pod::Spec.new do |s|
  s.platform = :ios
  s.ios.deployment_target = '11.0'
  s.name = "HalBase"
  s.swift_version = '4.0'
  s.summary = "This is example"
  s.requires_arc = true
  s.version = "1.0"
  s.license = { :type => "MIT", :file => "LICENSE" }
  s.author = { "ntancnit@gmail.com" => "ntancnit@gmail.com" }
  s.homepage = "https://github.com/ntancnit/HalBase"
  s.source = { :git => "https://github.com/ntancnit/HalBase.git", :tag => "#{s.version}"}
  s.ios.framework = "UIKit"
  s.ios.framework = "CoreLocation"
  s.ios.framework = "Foundation"
  s.dependency 'RxSwift', '~> 4.0.0'
  s.dependency 'RxCocoa', '~> 4.0.0'
  s.dependency 'RxDataSources', '~> 3.0'
  s.dependency 'Action'
  s.dependency 'Alamofire', '~> 4.0'
  s.dependency 'AlamofireImage', '~> 3.0'
  s.dependency 'ObjectMapper', '~> 3.0'
  s.dependency 'IQKeyboardManagerSwift', '~> 5.0.0'
  s.dependency 'SVProgressHUD'
  s.dependency 'PureLayout'
  s.dependency 'KeychainAccess'
  s.source_files = "HalBase/**/*.{swift,h,m}"
  s.resources = "HalBase/**/*.{png,jpeg,jpg,storyboard,xib,plist,swift}"
end

GlobalLoaderView is my custome class inhered from UIControl.
I am using swift 4, Xcode 9.4
Thank you!


Q: How to take screen shot of a web page in PHP and show it in model popup and submit it into database function screenshot(){
       html2canvas(document.body).then(function(canvas) {

         //document.body.appendChild(canvas);

         // Get base64URL
         var base64URL = canvas.toDataURL('').replace( 'image/octet-stream');

         // AJAX request
      $.ajax({
            url: 'screen_shot.php',
            type: 'post',
            data: {image: base64URL},

            success: function(data){
               alert('Upload successfully');
            }
         });
       });
    }

A: 1) You can use HTML5 & javaScript to take screenshots. This will work for sure. check more details
here
(function (exports) {
    function urlsToAbsolute(nodeList) {
        if (!nodeList.length) {
            return [];
        }
        var attrName = 'href';
        if (nodeList[0].__proto__ === HTMLImageElement.prototype
        || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
            attrName = 'src';
        }
        nodeList = [].map.call(nodeList, function (el, i) {
            var attr = el.getAttribute(attrName);
            if (!attr) {
                return;
            }
            var absURL = /^(https?|data):/i.test(attr);
            if (absURL) {
                return el;
            } else {
                return el;
            }
        });
        return nodeList;
    }

    function screenshotPage() {
        urlsToAbsolute(document.images);
        urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
        var screenshot = document.documentElement.cloneNode(true);
        var b = document.createElement('base');
        b.href = document.location.protocol + '//' + location.host;
        var head = screenshot.querySelector('head');
        head.insertBefore(b, head.firstChild);
        screenshot.style.pointerEvents = 'none';
        screenshot.style.overflow = 'hidden';
        screenshot.style.webkitUserSelect = 'none';
        screenshot.style.mozUserSelect = 'none';
        screenshot.style.msUserSelect = 'none';
        screenshot.style.oUserSelect = 'none';
        screenshot.style.userSelect = 'none';
        screenshot.dataset.scrollX = window.scrollX;
        screenshot.dataset.scrollY = window.scrollY;
        var script = document.createElement('script');
        script.textContent = '(' + addOnPageLoad_.toString() + ')();';
        screenshot.querySelector('body').appendChild(script);
        var blob = new Blob([screenshot.outerHTML], {
            type: 'text/html'
        });
        return blob;
    }

    function addOnPageLoad_() {
        window.addEventListener('DOMContentLoaded', function (e) {
            var scrollX = document.documentElement.dataset.scrollX || 0;
            var scrollY = document.documentElement.dataset.scrollY || 0;
            window.scrollTo(scrollX, scrollY);
        });
    }

    function generate() {
        window.URL = window.URL || window.webkitURL;
        window.open(window.URL.createObjectURL(screenshotPage()));
    }
    exports.screenshotPage = screenshotPage;
    exports.generate = generate;
})(window);

2) You can also use html2canvas below is the simple example of how to implement.
JS
  html2canvas(document.querySelector("#capture")).then(canvas => {
        document.body.appendChild(canvas)
    });

HTML

Hello world!

download & include in the head section
//*

//*


Q: Differences between query using LINQ and IQueryable interface directly? Using Entity Framework 4, and given:
ObjectSet<Thing> AllThings = Context.CreateObjectSet<Thing>;

public IQueryable<Thing> ByNameA(String name)
{
    IQueryable<Thing> query =  from o in AllThings
                               where o.Name == name
                               select o;
    return query;
}

public IQueryable<Thing> ByNameB(String name)
{
    return AllThings.Where((o) => o.Name == name);
}

Both return IQueryable<> instances, and thus the query doesn't hit the server until something like ToList() is called, right? Is it purely readability that is the difference, or are the using fundamentally different technologies on the back-end?

A: These compile to nearly identical code.
The first syntax translates directly, by the compiler, into methods with the names provided in the second syntax.
The main difference between these two methods is really just that you're using a different syntax, and that you're assigning to a temporary variable (query) instead of just returning the result directly.  However, they are, for all practical purposes, identical.


Q: Filling content from bottom and right to left order Inside my page I have div which I want to populate with some content like it's on image. How can I do this without shrinking div content and populate inside div from bottom to up?

A: Best approach for this layout would be the Flexbox Technique
You can wrap the rows in the reverse order using wrap-reverse

$(document).ready(function() {
  $('.create').on('click', function() {
    $('.container').append('

');
  })
});
.container {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  background: #6CC4DA;
  -webkit-flex-wrap: wrap-reverse;
  -ms-flex-wrap: wrap-reverse;
  flex-wrap: wrap-reverse;
  align-items: baseline;
  align-content: flex-start;
  height: 280px;
  width: 770px;
}
.circle {
  background: #C78DEF;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  margin: 5px;
}

<button class="create">Create a circle</button>

JSfiddle

A: You can flip horizontal parent div and flip horizontal back each child block:

$(document).ready(function() {
  $(document).on('click', 'button', function() {
    var
      items = $('.content-item').size(),
      space = document.createTextNode(' ');
    $('.container').append($('
' + (items + 1) + '
')).append(space);
  });
});
.container {
  width: 400px;
  height: 200px;
  background: cyan;
  transform: ScaleY(-1);
}
.content-item {
  display: inline-block;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin: 5px;
  text-align: center;
  line-height: 50px;
  background: purple;
  color: #fff;
  transform: ScaleY(-1);
}

<button>Increase population</button>

1

2

3

4

5

6

7


Q: meteorjs -- Problems with the accounts-twitch package & OAuth2 Today, I started a new project (IRC Bot, etc.) to be used with Twitch.TV's chat servers.
I wanted to use the accounts-twitch package that I found on Atmosphere, and had to manually install it (editing the package.js file) due to a deprecated dependency on accounts-oauth2-helper.
After getting it to properly install, my app crashes on startup now.  It tosses the following error before dying, and I don't know how to fix it:
[[[[[ ~/projects/wasdbot ]]]]]

=> Started MongoDB.
=> Starting your app...

W20140605-15:22:42.283(-4)? (STDERR)
W20140605-15:22:42.350(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
W20140605-15:22:42.350(-4)? (STDERR)                        throw(ex);
W20140605-15:22:42.350(-4)? (STDERR)                              ^
W20140605-15:22:42.351(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined
W20140605-15:22:42.351(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:2)
W20140605-15:22:42.351(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:82)
W20140605-15:22:42.351(-4)? (STDERR)     at packages/accounts-twitch.js:123:4
W20140605-15:22:42.351(-4)? (STDERR)     at packages/accounts-twitch.js:130:3
W20140605-15:22:42.352(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10
W20140605-15:22:42.352(-4)? (STDERR)     at Array.forEach (native)
W20140605-15:22:42.352(-4)? (STDERR)     at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11)
W20140605-15:22:42.352(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8
W20140605-15:22:43.456(-4)? (STDERR)
W20140605-15:22:43.457(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
W20140605-15:22:43.457(-4)? (STDERR)                        throw(ex);
W20140605-15:22:43.458(-4)? (STDERR)                              ^
W20140605-15:22:43.463(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined
W20140605-15:22:43.463(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:2)
W20140605-15:22:43.464(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:82)
W20140605-15:22:43.464(-4)? (STDERR)     at packages/accounts-twitch.js:123:4
W20140605-15:22:43.464(-4)? (STDERR)     at packages/accounts-twitch.js:130:3
W20140605-15:22:43.465(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10
W20140605-15:22:43.465(-4)? (STDERR)     at Array.forEach (native)
W20140605-15:22:43.465(-4)? (STDERR)     at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11)
W20140605-15:22:43.466(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8
W20140605-15:22:44.622(-4)? (STDERR)
W20140605-15:22:44.624(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
W20140605-15:22:44.625(-4)? (STDERR)                        throw(ex);
W20140605-15:22:44.625(-4)? (STDERR)                              ^
W20140605-15:22:44.628(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined
W20140605-15:22:44.629(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:2)
W20140605-15:22:44.629(-4)? (STDERR)     at Package (packages/accounts-twitch/twitch_server.js:82)
W20140605-15:22:44.630(-4)? (STDERR)     at packages/accounts-twitch.js:123:4
W20140605-15:22:44.630(-4)? (STDERR)     at packages/accounts-twitch.js:130:3
W20140605-15:22:44.630(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10
W20140605-15:22:44.631(-4)? (STDERR)     at Array.forEach (native)
W20140605-15:22:44.631(-4)? (STDERR)     at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11)
W20140605-15:22:44.631(-4)? (STDERR)     at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8
=> Your application is crashing. Waiting for file change.

Seems like the problem is this call to Accounts.oauth.registerService, in twitch_server.js, but I don't really know how to go about fixing it.
I also can't seem to find anything about this oauth stuff in their API docs, anywhere, or maybe I'm looking in the wrong place, or maybe I'm missing a package that I should have included?
All I added to my project is accounts-twitch, accounts-ui, and coffeescript, as of right now.  I haven't written any code yet, just trying to fire up Meteor.
Any help would be amazing.  I really appreciate everyone's time beforehand.


Q: Mule ESB + RabbitMQ reliability and up-time: how to re-create a deleted exchange automatically at runtime I've got a Large mule application that receives on multiple queues and publishes to at least one exchange. I'm manually QA'ing the application by deleting the queues and exchanges to see if mule will retry to connect (and also shut down rabbit altogether)
This question is for when an exchange is deleted. The messages go into a locked anonymous queue named something like: amq.gen-gFs6-7sP2nw1ntgobO6cBg
I'm looking for a way to reconnect the exchange and still pass through the messages. Is this even possible?
I've set options like
exchangeDurable="true"
queueDurable="true"
Is there any other things (or rabbit configs) that I need to do or would be beneficial to me?
Next Test: Shutdown RabbitMQ in the middle of processing.
Code:

<mule xmlns:jdbc-ee="http://www.mulesoft.org/schema/mule/ee/jdbc"
xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:amqp="http://www.mulesoft.org/schema/mule/amqp"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml"
xmlns:file="http://www.mulesoft.org/schema/mule/file"
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/jdbc http://www.mulesoft.org/schema/mule/ee/jdbc/current/mule-jdbc-ee.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/amqp http://www.mulesoft.org/schema/mule/amqp/current/mule-amqp.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd"
xmlns:context="http://www.springframework.org/schema/context">

<amqp:connector name="amqpAutoAckLocalhostConnector"
      host="${config.status_reporting.host}"
      port="${config.status_reporting.port}"
      virtualHost="${config.status_reporting.virtual_host}"
      username="${config.status_reporting.username}"
      password="${config.status_reporting.password}"
      requestedHeartbeat="${config.status_reporting.requestedHeartbeat}"
      doc:name="AMQP Connector for Status Messages"/>

<flow name="send_status" doc:name="send_status">
    <vm:inbound-endpoint path="send_status" exchange-pattern="one-way" responseTimeout="10000" doc:name="VM" />
    <logger message="starting send status" level="DEBUG" doc:name="Logger"/>

    <!-- some code here has been removed for stackoverflow question -->

    <flow-ref name="cwm_send" doc:name="flow ref"/>
</flow>

<flow name="cwm_send" doc:name="cwm_send">
    <amqp:outbound-endpoint exchangeName="${config.status_reporting.exchange_name}"
                      exchangeType="topic"
                      exchangeDurable="${config.status_reporting.exchange_is_durable}"
                      routingKey="${config.status_reporting.routing_key}"
                      connector-ref="amqpAutoAckLocalhostConnector" doc:name="AMQP Out" queueDurable="true" responseTimeout="10000"/>
</flow>

<flow name="send_ingest_status" doc:name="send_ingest_status">
    <vm:inbound-endpoint exchange-pattern="request-response" responseTimeout="10000" doc:name="VM" path="send_ingest_status"/>
    <vm:outbound-endpoint path="send_status" exchange-pattern="one-way" doc:name="Send Status">
        <set-payload value="#[[
            'status_code': 'foo',
            'status_descr': 'test description.',
            'status_final': '0',
            'version': '1.0']]"/>
    </vm:outbound-endpoint>

</flow>
</mule>

Thank you.

A: This problem also seems to occur when an exchange is declared only in an outbound endpoint. There is an open bug concerning this in the Mulesoft JIRA, and you can vote for it to help them prioritize it.
I took a look at the source code, and the problem seems to be that there is simply no code to declare exchanges when an outbound endpoint is started.  In your case, you'd probably want the code to run at the time the message is sent, or maybe at the time the exchange is deleted.  This timing wouldn't be covered by the aforementioned bug, but you might open a new issue describing the use case and the desired functionality.  And a pull request would probably be even better! ;)


Q: Show ajaxloader on the time of $.getJson call i want to show ajaxloader icon on the time of executing $.getJSON.
it should disappear after $.getJSON completes.
$.getJSON("url",
    function(data){
      ........
      ........
      });

A: Try this pattern:
$("#someAnimatedGif").show();
$.getJSON("url", function (data) {
    $("#someAnimatedGif").hide();
});

The animated gif will initially be hidden, and you can use JQuery to hide/show it.
The key is to show it right before you execute the Ajax call, and hide it again when the callback returns.


Q: Servlets and synchronization Servlets runs in several threads, so my question is:
If I have a lot of servlets which call some utility class (DbUtils, for example
Connection c = DbUtils.getConnection();
//....some action with db here

should I assume additional actions for synchronization inside DbUtils?
Actually I'd like to inherit HttpServlet into something like DatabaseInvokerServlet:
public abstract class DatabaseInvokerServlet extends HttpServlet
with methods:
public abstract void getResultSets(Connection connection) throws SQLException;
private AbstractUser currentUser;
private HttpServletRequest request;
private HttpServletResponse response;
protected void processData() {}
protected void afterRequestProcessed() throws ServletException, IOException {}
protected void beforeRequestProcessed() throws ServletException, IOException {}

protected void execute() {
    Connection c = null;
    try {
        c = DbUtils.getConnection();
        getResultSets(c);
        processData();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public HttpServletRequest getRequest() {
    return request;
}

public HttpServletResponse getResponse() {
    return response;
}

public AbstractUser getCurrentUser() {
    return currentUser;
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    this.request = request;
    this.response = response;
    this.currentUser = (AbstractUser) request.getSession().getAttribute("currentUser");

}

Then I'd just inherit my DatabaseInvokerServlet to new servlets to do custom stuff. The reason is not to copy-paste database invoke block with try-catch-finally in a lot of places.
But as I can see such approach won't work because of synchronization issues. Am I right?

A: If the DbUtils creates the connection in the same thread, like as:
public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(url, username, password);
}

Then it's threadsafe.
But if the connection is a class variable, like as:
private static Connection connection = DriverManager.getConnection(url, username, password);

public static Connection getConnection() throws SQLException {
    return connection;
}

Then it is definitely not threadsafe because the same connection will be shared among all threads. Also when it's closed in a thread, all subsequent threads won't be able to use the connection because it's not open anymore. Also when it's never closed, the DB will timeout the connection sooner or later, usually after a few hours, and your application won't work anymore because the connection is not open anymore.

As to the servlet,
public abstract class DatabaseInvokerServlet extends HttpServlet {
    private AbstractUser currentUser;
    private HttpServletRequest request;
    private HttpServletResponse response;
    // ...
}

it's definitely not threadsafe. You're assigning the current user, request and response as instance variables. From each servlet class, there is only one instance during the application's lifetime. This instance is shared among all visitors/sessions throughout the entire application's lifetime. Each HTTP request operates in a separate thread and uses the same instance.
Imagine two simultaneous visitors: visitor A will set the current user, request and response. The DB process however takes a long time. Before the response of visitor A has returned, visitor B calls the same servlet and thus the current user, request and response will be overriden. Then, the query of visitor A finishes and wants to write to the response, it is instead writing to the response of visitor B! Visitor B sees the result of the query of visitor A and visitor A sees nothing on his screen!
You should never assign request/session-specific data as instance variable of the servlet. You should keep them method (thread) local.
public abstract class DatabaseInvokerServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AbstractUser currentUser = request.getSession().getAttribute("user");
        // Keep the variables in the method block!
        // Do not assign them as instance variable!
    }
}

As to the complete picture, this approach is clumsy. The database access layer should have nothing to do with servlets. It should operate in its own standalone classes which you could just construct/invoke in every other Java class, any servlet class, or a normal application with main(), or whatever. You should not have any single line of java.sql.* imports in your servlet classes (expect of maybe SQLException if it is not abstracted away). You should not have any single line of javax.servlet.* imports in your database classes.
See also:

*

*Servlet instantiation and (session) variables

*Basic DAO tutorial

A: If the utility class has state (example: class or instance variables) most probably yes.

A: If I guess right the DBUtils is returning new instance for each call of getConnection(). And as the DBUtils class is a utility class so it shouldn't be maintaining any state. In this scenario no you dont need any addition efforts for synchronization.

A: Servlets runs in several threads.
The J2EE spec says there is only one instance per servlet class running in one web container for non single thread servlet.

Servlet 2.3 specs

A servlet container may send
  concurrent requests through the
  service method of the servlet. To
  handle the requests the developer of
  the servlet must make adequate
  provisions for concurrent processing
  with multiple threads in the service
  method.

Synchronisation in servlet.
Never have an member variable in a servlet, it is not thread safe.


Q: java: NoSuchElementException: Reading to arrayList sorry if my formatting is garbage.
I'm trying to add 2 strings and a boolean to an arrayList doing the following.
while((in.hasNextLine())){
    list.add(new Task(in.next(),in.next(), in.hasNextBoolean()));
    }

I keep getting a no such element exception. If I take the while loop away like so
list.add(new Task(in.next(),in.next(), in.hasNextBoolean()));

It functions fine but I can only add the first line of the text file.
Is there something wrong in the loop or with the Scanner?
try {
        in = new Scanner(f1);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    while((in.hasNextLine())){
    list.add(new Task(in.next(),in.next(), in.hasNextBoolean()));
    }

f1 is declared as File f1 = new File ("src/mylist.txt");
Any help would be great! Thanks!

A: NoSuchElementException exception is throwed by in.next(), in list.add(new Task(in.next(),in.next(), in.hasNextBoolean())),.
and for in.next(), if you don't use any Pattern in Scanner to match the next token. it will use default Pattern private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*") to match whole line. it will cause in.next() will read whole line.
so list.add(new Task(in.next(),in.next(), in.hasNextBoolean())) will throw NoSuchElementException, you have read twice but you only check once.