问:
Java Database instantly disconnect
I try to edit and read out of my database and I always get a connection but I'm not able to insert or select anything from the database because it tells me the connection is already closed again. So the methods don't work. I don't understand why.</p>

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class Test {

    public static Connection connect() {
        Connection conn = null;
        String url = "jdbc:sqlite:C:/Users/eichw/Desktop/test.db";

        try {

            // create a connection to the database
            conn = DriverManager.getConnection(url);

            System.out.println("Connection to SQLite has been established.");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
        return conn;
    }

   public void selectAll(){
        String sql = "SELECT KNr, KName, KFirma, KMail FROM test";

        try (Connection conn = this.connect();
             Statement stmt  = conn.createStatement();
             ResultSet rs    = stmt.executeQuery(sql)){

            // loop through the result set
            while (rs.next()) {
                System.out.println(rs.getInt("KNr") +  "\t" +
                                   rs.getString("KName") + "\t" +
                                   rs.getDouble("KFirma"));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        Test app = new Test();
       app.selectAll();

    }
}
</code>```

答:
As @Berger said on the comments, your connect() method is opening the connection, but then it's also closing it right after, in the finally block.

Then you return the connection object already closed to the selectAll() method. It then tries to create a Statement and so on with a connection that is already closed.

What you need to do is to open the connection, return it, use it and only after it's used you should close it.

Title: Java Database instantly disconnect

Body:
I try to edit and read out of my database and I always get a connection but I'm not able to insert or select anything from the database because it tells me the connection is already closed again. So the methods don't work. I don't understand why.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class Test {

    public static Connection connect() {
        Connection conn = null;
        String url = "jdbc:sqlite:C:/Users/eichw/Desktop/test.db";

        try {

            // create a connection to the database
            conn = DriverManager.getConnection(url);

            System.out.println("Connection to SQLite has been established.");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
        return conn;
    }

   public void selectAll(){
        String sql = "SELECT KNr, KName, KFirma, KMail FROM test";

        try (Connection conn = this.connect();
             Statement stmt  = conn.createStatement();
             ResultSet rs    = stmt.executeQuery(sql)){

            // loop through the result set
            while (rs.next()) {
                System.out.println(rs.getInt("KNr") +  "\t" +
                                   rs.getString("KName") + "\t" +
                                   rs.getDouble("KFirma"));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        Test app = new Test();
       app.selectAll();

    }
}


来源: stackexchange

问:
Is it Possible to Run a Python Code Forever?
I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as python file.py The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, the script might get stopped when my Internet Connection is off or at Night. So i couldn't keep running the Script Whole day on my PC..

So is there any way or website or Method where i could deploy my Script and make it Execute forever there ? I have heard about CRON JOBS before in Cpanel which can Help repeated Tasks but here in my case i want to keep running my Script on the Machine till i don't close the script .

Are their any such solutions. Because most of twitter bots i see are running forever, meaning their Script is getting executed somewhere 24x7 . This is what i want to know, How is that Task possible?

答:
As mentioned by Jon and Vincent, it's better to run the code from a cloud service. But either way, I think what you're looking for is what to put into the terminal to run the code even after you close the terminal. This is what worked for me:</p>

```<code>nohup python code.py &
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As mentioned by Jon and Vincent, it's better to run the code from a cloud service. But either way, I think what you're looking for is what to put into the terminal to run the code even after you close the terminal. This is what worked for me:

nohup python code.py &


问:
Using constexpr in a namespace with static_assert is giving error
I have declared the following in header file.

```<code>namespace G1
{
    inline namespace V1
    {
        constexpr float getV();
    }
}
</code>```

In CPP file, I have defined the getV function as

```<code>constexpr float G1::V1::getV()
{
    return 0.1f;
}
</code>```

In the main I am using static_assert to compare the version as shown.

```<code>int main()
{
    static_assert( G1::getV() == 1.0f, "Error"); // Please Ignore the way I am comparing the floats
    return 0;
}
</code>```

But when I compile the code, I am getting expression did not evaluate to a constant.

Am I doing anything wrong here? I am using VS2015.
Thanks in advance

答:
If you want the compiler compiling main to know about the value getV returns at compile time, you must implement the function in the header too.
Since you use static_assert the definition is needed at compile time.

The way you do it only the compiler of the .cpp file containing getV can know what it returns. This is usually a different compiler call.

By link time, it is too late to check the static_assert.

The error message: expression did not evaluate to a constant is caused by the compiler not knowing the implementation. In a "runtime" context it would insert a call here, to be later fixed up by the linker and executed at runtime. A runtime call is however never a compile time constant.

Body:
I have declared the following in header file.

namespace G1
{
    inline namespace V1
    {
        constexpr float getV();
    }
}

In CPP file, I have defined the getV function as

constexpr float G1::V1::getV()
{
    return 0.1f;
}

In the main I am using static_assert to compare the version as shown.

int main()
{
    static_assert( G1::getV() == 1.0f, "Error"); // Please Ignore the way I am comparing the floats
    return 0;
}

But when I compile the code, I am getting expression did not evaluate to a constant.

Am I doing anything wrong here? I am using VS2015.
Thanks in advance


问:
References for z/OS and DB2 performance tuning
I need references for z/OS and DB2 performance tuning.</p>

答: All normal documentation is help on the Boulder publib site (DB2/z and z/OS). Other than that, you should be looking into IBM RedBooks. IBM invests a lot of time and money into putting those together.</p>

ContentLicense: CC BY-SA 2.5


问:
global initialize function and global constants in Python without using sys.path.append()
My use case is the following:

several scripts that can be run individually

one 'mother' script that can run all the scripts

each script has global variables it uses (paths to specific locations, constants used by all scripts)

some of these global variables are inputted in a settings.yaml file which gets dynamically loaded with yaml.load()

several people are running the system, we want to avoid environment variables or any kind of low-level path settings

The use cases were satisfied with an

```<code>import settings
</code>```

at the beginning of each export module.

The settings.py script is our 'initialize' script that loads and create variables used for all the modules, e.g.:

```<code>import os
import yaml
from utils import create_dir

input_f = open("settings.yml")
settings = yaml.load(input_f.read())
input_f.close()

TOHELLO = settings['TOHELLO']
TOBONJOUR = settings['TOBONJOUR']

#check for needed directories and create if necessary
create_dir(TOHELLO)
create_dir(TOBONJOUR)
</code>```

The 'mother module' export_all.py uses Subprocess.Popen() to run all the scripts sequentially.

Originally all files were in the root:

```<code>+--settings.py
+--settings.yml
+--export_foo1.py
+--export_foo2.py
+--export_foo3.py
+--export_foo4.py
+--export_bar1.py
+--export_bar2.py
+--export_bar3.py
+--export_bar4.py
+--export_all.py
</code>```

With time, though, this became messy and we decided to restructure it:

```<code>+--settings.py
+--settings.yml
+--Foo
+  +--export_foo1.py
+  +--export_foo2.py
+  +--export_foo3.py
+  +--export_foo4.py
+--Bar
+  +--export_bar1.py
+  +--export_bar2.py
+  +--export_bar3.py
+  +--export_bar4.py
+--export_all.py
</code>```

And then all hell broke loose.

We discovered that one can only use 'import' for modules that are either underneath the module or specifically within sys.path.

The solution we've come up with involves inserting this beauty at the top of all of our scripts:

```<code>PACKAGE_PARENT = os.path.join('..','..')
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
</code>```

but it just seems like overkill to us.

We tried

```<code>from settings import functionname
</code>```

but that doesn't run the code that generates the constants from the yaml file

Also, we tried squeezing the imports in __init.py__ in each directory, but then the Subprocess.Popen() didn't work.

We're kind of missing a pythonesque way to have some global constants, and an initialiazing script that runs only once (even when the 'mother' script is running).

Is it us, or is python just weird and ugly here?

答:
You need to turn your directories into modules: https://docs.python.org/2/tutorial/modules.html#packages

to allow you use a structure like this:

```<code>from foo import export_foo1
</code>```

or to use:

```<code>from ..bar import export_bar1
</code>```

in case you are inside a subfolder

https://docs.python.org/2/tutorial/modules.html#intra-package-references

Body:
My use case is the following:

several scripts that can be run individually

one 'mother' script that can run all the scripts

each script has global variables it uses (paths to specific locations, constants used by all scripts)

some of these global variables are inputted in a settings.yaml file which gets dynamically loaded with yaml.load()

several people are running the system, we want to avoid environment variables or any kind of low-level path settings

The use cases were satisfied with an

import settings

at the beginning of each export module.

The settings.py script is our 'initialize' script that loads and create variables used for all the modules, e.g.:

import os
import yaml
from utils import create_dir

input_f = open("settings.yml")
settings = yaml.load(input_f.read())
input_f.close()

TOHELLO = settings['TOHELLO']
TOBONJOUR = settings['TOBONJOUR']

#check for needed directories and create if necessary
create_dir(TOHELLO)
create_dir(TOBONJOUR)

The 'mother module' export_all.py uses Subprocess.Popen() to run all the scripts sequentially.

Originally all files were in the root:

+--settings.py
+--settings.yml
+--export_foo1.py
+--export_foo2.py
+--export_foo3.py
+--export_foo4.py
+--export_bar1.py
+--export_bar2.py
+--export_bar3.py
+--export_bar4.py
+--export_all.py

With time, though, this became messy and we decided to restructure it:

+--settings.py
+--settings.yml
+--Foo
+  +--export_foo1.py
+  +--export_foo2.py
+  +--export_foo3.py
+  +--export_foo4.py
+--Bar
+  +--export_bar1.py
+  +--export_bar2.py
+  +--export_bar3.py
+  +--export_bar4.py
+--export_all.py

And then all hell broke loose.

We discovered that one can only use 'import' for modules that are either underneath the module or specifically within sys.path.

The solution we've come up with involves inserting this beauty at the top of all of our scripts:

PACKAGE_PARENT = os.path.join('..','..')
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

but it just seems like overkill to us.

We tried

from settings import functionname

but that doesn't run the code that generates the constants from the yaml file

Also, we tried squeezing the imports in __init.py__ in each directory, but then the Subprocess.Popen() didn't work.

We're kind of missing a pythonesque way to have some global constants, and an initialiazing script that runs only once (even when the 'mother' script is running).

Is it us, or is python just weird and ugly here?

Body:
You need to turn your directories into modules: https://docs.python.org/2/tutorial/modules.html#packages

to allow you use a structure like this:

from foo import export_foo1

or to use:

from ..bar import export_bar1

in case you are inside a subfolder

https://docs.python.org/2/tutorial/modules.html#intra-package-references


问:
getting the number of local variables in a method
So I have some classes into which "dummy method calls" have been inserted; i.e. static methods in a dedicated class that have an empty body.

The idea is to take the arguments that were pushed to the stack prior to the method invokation, store them in local variables, then replace the method invocation with the actual implementation.

To see how locals are handled, I run

A.java

```<code>package asmvisit;

public class A {
    long y;

    public long doSomething(int x, A a){
        if(a == null){
            this.y = (long)x;
            return -1L;
        }
        else{
            long old = y;
            this.y += (long)x;
            return old;
        }
    }
}
</code>```

through a textifier (code at the bottom of the post).

As you can see in the output (also at the bottom of the post), the local variables

```<code>    LOCALVARIABLE old J L4 L6 3
    LOCALVARIABLE this Lasmvisit/A; L0 L6 0
    LOCALVARIABLE x I L0 L6 1
    LOCALVARIABLE a Lasmvisit/A; L0 L6 2
</code>```

get visited at the very end of the method.

Technically speaking, we would be allowed to visit them earlier, but I get why inserting locals at arbitrary places may screw up the numbering -- and with it, the program.

So the way I see it, the only safe way to add more local variables would be to run twice through every method:

once doing absolutely nothing except counting the number of local variable visits

once actually modifying the code, keeping track of the locals "generated", but delaying actual generation (i.e. visiting the local) until just before the visitMaxs, using a counter to keep track of the indices the new locals will end up having.

Is there a simpler alternative that doesn't require two passes?

textifier

```<code>package asmvisit;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.util.Printer;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceMethodVisitor;

import java.io.PrintWriter;
import java.util.Arrays;

public class MyClassVisitor extends ClassVisitor {
    public MyClassVisitor(ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        System.out.println(String.format("\nvisitMethod: %d, %s, %s, %s, %s", access,name,desc,signature, Arrays.toString(exceptions)));

        Printer p = new Textifier(api) {
            @Override
            public void visitMethodEnd() {
                PrintWriter pw = new PrintWriter(System.out);
                print(pw); // print it after it has been visited
                pw.flush();
            }
        };

        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        if(mv != null){
            return new TraceMethodVisitor(mv,p);
        }

        return mv;
    }
}
</code>```

output

```<code>visitMethod: 1, <init>, ()V, null, null
L0
    LINENUMBER 3 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init> ()V
    RETURN
L1
    LOCALVARIABLE this Lasmvisit/A; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

visitMethod: 1, doSomething, (ILasmvisit/A;)J, null, null
L0
    LINENUMBER 7 L0
    ALOAD 2
    IFNONNULL L1
L2
    LINENUMBER 8 L2
    ALOAD 0
    ILOAD 1
    I2L
    PUTFIELD asmvisit/A.y : J
L3
    LINENUMBER 9 L3
    LDC -1
    LRETURN
L1
    LINENUMBER 12 L1
FRAME SAME
    ALOAD 0
    GETFIELD asmvisit/A.y : J
    LSTORE 3
L4
    LINENUMBER 13 L4
    ALOAD 0
    DUP
    GETFIELD asmvisit/A.y : J
    ILOAD 1
    I2L
    LADD
    PUTFIELD asmvisit/A.y : J
L5
    LINENUMBER 14 L5
    LLOAD 3
    LRETURN
L6
    LOCALVARIABLE old J L4 L6 3
    LOCALVARIABLE this Lasmvisit/A; L0 L6 0
    LOCALVARIABLE x I L0 L6 1
    LOCALVARIABLE a Lasmvisit/A; L0 L6 2
    MAXSTACK = 5
    MAXLOCALS = 5
</code>```

答:
The local variables, as reported by visitLocalVariable, are only debug information, as stored in the LocalVariableTable attribute and LocalVariableTypeTable attribute. If these attributes are not present, no such declarations will be reported.

Further, they are not required to be complete regarding bytecode level variables, i.e. they do not report the second variable occupied by long and double values. They also may not include synthetic variables, like introduced by the for-each construct (holding the hidden iterator), try-with-resource construct (holding pending exceptions) or pending values like in

try { return expression; } finally { otherAction(); } constructs.

On the bytecode level, local variables are established by actually storing values into them (referring to the index only). Variables having disjunct scopes on the source code level may use the same index in the stack frame. To the bytecode, it doesn’t matter whether two writes to the same index are actually a change of the same variable or two variables with different scope. But the sizes as reported by visitMaxs must be large enough to hold the operand stack elements and all variable indices used in the method’s stack frame. Also stack map table frames are mandatory for new class files specifying the expected types for branch targets.

Since ASM reports the old max locals at the end of the visiting, you can’t use that to use indices larger than that beforehand, but it’s not necessary. As said above, variable indices are not required to be unique. Your use case is like introducing a new variable scope, so you may use indices that haven’t been used before that point and there is no problem if these indices are used again by subsequent code after your injected code ended.

Getting the indices which have been used before a certain point is not so hard, if you can live with only supporting newer class files having StackMapTable attributes. For these classes you only have to care for two events. At branch targets, visitFrame will report which variables are in use at this point. Using this information is easier when specifying EXPAND_FRAMES to the ClassReader. The other event to care are actual variable use instructions (actually, only stores matter), which are reported via visitVarInsn. Putting it together, the sketch looks like

```<code>classReader.accept(new ClassVisitor(Opcodes.ASM5) {
    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        return new MyMethodVisitor(access, desc);
    }
}, ClassReader.EXPAND_FRAMES);
</code>```

```<code>class MyMethodVisitor extends MethodVisitor {
    private int used, usedAfterInjection;

    public MyMethodVisitor(int acc, String signature) {
        super(Opcodes.ASM5);
        used = Type.getArgumentsAndReturnSizes(signature)>>2;
        if((acc&Opcodes.ACC_STATIC)!=0) used--; // no this
    }

    @Override
    public void visitFrame(
            int type, int nLocal, Object[] local, int nStack, Object[] stack) {
        if(type != Opcodes.F_NEW)
            throw new IllegalStateException("only expanded frames supported");
        int l = nLocal;
        for(int ix = 0; ix < nLocal; ix++)
            if(local[ix]==Opcodes.LONG || local[ix]==Opcodes.DOUBLE) l++;
        if(l > used) used = l;
        super.visitFrame(type, nLocal, local, nStack, stack);
    }

    @Override
    public void visitVarInsn(int opcode, int var) {
        int newMax = var+(opcode==Opcodes.LSTORE || opcode==Opcodes.DSTORE? 2: 1);
        if(newMax > used) used = newMax;
        super.visitVarInsn(opcode, var);
    }

    @Override
    public void visitMethodInsn(
            int opcode, String owner, String name, String desc, boolean itf) {
        if(!shouldReplace(owner, name, desc)) {
            super.visitMethodInsn(opcode, owner, name, desc, itf);
        }
        else {
            int numVars = (Type.getArgumentsAndReturnSizes(desc)>>2)-1;
            usedAfterInjection = used+numVars;
            /*
              use local vars between [used, usedAfterInjection]
            */
        }
    }
    @Override
    public void visitMaxs(int maxStack, int maxLocals) {
        super.visitMaxs(maxStack, Math.max(used, usedAfterInjection));
    }
}
</code>```

Things to pay attention to, is that when storing long or double values into a variable, the variable at index + 1 must be considered as being in use as well. In contrast, in the frames of a stack map table attribute, these long and double are reported as single entries, so we have to look for them and raise the number of used variables appropriately.

By tracking the used variables, we can simply use variables beyond that number within visitMethodInsn, as said, by simply storing values into these indices without the need to report them via visitLocalVariable. There is also no action need for declaring that they are out of scope afterwards, the subsequent code may or may not overwrite these indices.

Then visitMaxs must report the changed size, if bigger than the old size (unless you’re using COMPUTE_MAXS or COMPUTE_FRAMES anyway).

Body:
So I have some classes into which "dummy method calls" have been inserted; i.e. static methods in a dedicated class that have an empty body.

The idea is to take the arguments that were pushed to the stack prior to the method invokation, store them in local variables, then replace the method invocation with the actual implementation.

To see how locals are handled, I run

A.java

package asmvisit;

public class A {
    long y;

    public long doSomething(int x, A a){
        if(a == null){
            this.y = (long)x;
            return -1L;
        }
        else{
            long old = y;
            this.y += (long)x;
            return old;
        }
    }
}

through a textifier (code at the bottom of the post).

As you can see in the output (also at the bottom of the post), the local variables

    LOCALVARIABLE old J L4 L6 3
    LOCALVARIABLE this Lasmvisit/A; L0 L6 0
    LOCALVARIABLE x I L0 L6 1
    LOCALVARIABLE a Lasmvisit/A; L0 L6 2

get visited at the very end of the method.

Technically speaking, we would be allowed to visit them earlier, but I get why inserting locals at arbitrary places may screw up the numbering -- and with it, the program.

So the way I see it, the only safe way to add more local variables would be to run twice through every method:

once doing absolutely nothing except counting the number of local variable visits

once actually modifying the code, keeping track of the locals "generated", but delaying actual generation (i.e. visiting the local) until just before the visitMaxs, using a counter to keep track of the indices the new locals will end up having.

Is there a simpler alternative that doesn't require two passes?

textifier

package asmvisit;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.util.Printer;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceMethodVisitor;

import java.io.PrintWriter;
import java.util.Arrays;

public class MyClassVisitor extends ClassVisitor {
    public MyClassVisitor(ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        System.out.println(String.format("\nvisitMethod: %d, %s, %s, %s, %s", access,name,desc,signature, Arrays.toString(exceptions)));

        Printer p = new Textifier(api) {
            @Override
            public void visitMethodEnd() {
                PrintWriter pw = new PrintWriter(System.out);
                print(pw); // print it after it has been visited
                pw.flush();
            }
        };

        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        if(mv != null){
            return new TraceMethodVisitor(mv,p);
        }

        return mv;
    }
}

output

visitMethod: 1, <init>, ()V, null, null
L0
    LINENUMBER 3 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init> ()V
    RETURN
L1
    LOCALVARIABLE this Lasmvisit/A; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

visitMethod: 1, doSomething, (ILasmvisit/A;)J, null, null
L0
    LINENUMBER 7 L0
    ALOAD 2
    IFNONNULL L1
L2
    LINENUMBER 8 L2
    ALOAD 0
    ILOAD 1
    I2L
    PUTFIELD asmvisit/A.y : J
L3
    LINENUMBER 9 L3
    LDC -1
    LRETURN
L1
    LINENUMBER 12 L1
FRAME SAME
    ALOAD 0
    GETFIELD asmvisit/A.y : J
    LSTORE 3
L4
    LINENUMBER 13 L4
    ALOAD 0
    DUP
    GETFIELD asmvisit/A.y : J
    ILOAD 1
    I2L
    LADD
    PUTFIELD asmvisit/A.y : J
L5
    LINENUMBER 14 L5
    LLOAD 3
    LRETURN
L6
    LOCALVARIABLE old J L4 L6 3
    LOCALVARIABLE this Lasmvisit/A; L0 L6 0
    LOCALVARIABLE x I L0 L6 1
    LOCALVARIABLE a Lasmvisit/A; L0 L6 2
    MAXSTACK = 5
    MAXLOCALS = 5

Body:
The local variables, as reported by visitLocalVariable, are only debug information, as stored in the LocalVariableTable attribute and LocalVariableTypeTable attribute. If these attributes are not present, no such declarations will be reported.

Further, they are not required to be complete regarding bytecode level variables, i.e. they do not report the second variable occupied by long and double values. They also may not include synthetic variables, like introduced by the for-each construct (holding the hidden iterator), try-with-resource construct (holding pending exceptions) or pending values like in

try { return expression; } finally { otherAction(); } constructs.

On the bytecode level, local variables are established by actually storing values into them (referring to the index only). Variables having disjunct scopes on the source code level may use the same index in the stack frame. To the bytecode, it doesn’t matter whether two writes to the same index are actually a change of the same variable or two variables with different scope. But the sizes as reported by visitMaxs must be large enough to hold the operand stack elements and all variable indices used in the method’s stack frame. Also stack map table frames are mandatory for new class files specifying the expected types for branch targets.

Since ASM reports the old max locals at the end of the visiting, you can’t use that to use indices larger than that beforehand, but it’s not necessary. As said above, variable indices are not required to be unique. Your use case is like introducing a new variable scope, so you may use indices that haven’t been used before that point and there is no problem if these indices are used again by subsequent code after your injected code ended.

Getting the indices which have been used before a certain point is not so hard, if you can live with only supporting newer class files having StackMapTable attributes. For these classes you only have to care for two events. At branch targets, visitFrame will report which variables are in use at this point. Using this information is easier when specifying EXPAND_FRAMES to the ClassReader. The other event to care are actual variable use instructions (actually, only stores matter), which are reported via visitVarInsn. Putting it together, the sketch looks like

classReader.accept(new ClassVisitor(Opcodes.ASM5) {
    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        return new MyMethodVisitor(access, desc);
    }
}, ClassReader.EXPAND_FRAMES);

class MyMethodVisitor extends MethodVisitor {
    private int used, usedAfterInjection;

    public MyMethodVisitor(int acc, String signature) {
        super(Opcodes.ASM5);
        used = Type.getArgumentsAndReturnSizes(signature)>>2;
        if((acc&Opcodes.ACC_STATIC)!=0) used--; // no this
    }

    @Override
    public void visitFrame(
            int type, int nLocal, Object[] local, int nStack, Object[] stack) {
        if(type != Opcodes.F_NEW)
            throw new IllegalStateException("only expanded frames supported");
        int l = nLocal;
        for(int ix = 0; ix < nLocal; ix++)
            if(local[ix]==Opcodes.LONG || local[ix]==Opcodes.DOUBLE) l++;
        if(l > used) used = l;
        super.visitFrame(type, nLocal, local, nStack, stack);
    }

    @Override
    public void visitVarInsn(int opcode, int var) {
        int newMax = var+(opcode==Opcodes.LSTORE || opcode==Opcodes.DSTORE? 2: 1);
        if(newMax > used) used = newMax;
        super.visitVarInsn(opcode, var);
    }

    @Override
    public void visitMethodInsn(
            int opcode, String owner, String name, String desc, boolean itf) {
        if(!shouldReplace(owner, name, desc)) {
            super.visitMethodInsn(opcode, owner, name, desc, itf);
        }
        else {
            int numVars = (Type.getArgumentsAndReturnSizes(desc)>>2)-1;
            usedAfterInjection = used+numVars;
            /*
              use local vars between [used, usedAfterInjection]
            */
        }
    }
    @Override
    public void visitMaxs(int maxStack, int maxLocals) {
        super.visitMaxs(maxStack, Math.max(used, usedAfterInjection));
    }
}

Things to pay attention to, is that when storing long or double values into a variable, the variable at index + 1 must be considered as being in use as well. In contrast, in the frames of a stack map table attribute, these long and double are reported as single entries, so we have to look for them and raise the number of used variables appropriately.

By tracking the used variables, we can simply use variables beyond that number within visitMethodInsn, as said, by simply storing values into these indices without the need to report them via visitLocalVariable. There is also no action need for declaring that they are out of scope afterwards, the subsequent code may or may not overwrite these indices.

Then visitMaxs must report the changed size, if bigger than the old size (unless you’re using COMPUTE_MAXS or COMPUTE_FRAMES anyway).


问:
Gitlab CI - how to build a local maven dependency before the current build?
I have the following setup:

Java Library 1

Java Library 2

Java application

The "Java application" depends on "Java Library 1" and "Java Library 2" and they are both internal.

"Java Library 1" and "Java Library 2" need to be installed on the local maven repository before "Java application" can be successfully compiled and packaged.

"Java Library 1", "Java Library 2" and "Java application" are separate projects on GitLab.

Each project has a .gitlab-ci.yml.

Each "Java Library" would have something like this:

```<code>build:
    script:
        - mvn clean install
    stage: build
    only:
        - master
    tags:
        - java
</code>```

I want to tell the .gitlab-ci.yml from the "Java application" to first build "Java Library 1" and "Java Library 2".

Is it possible?

答:
I think you're looking for Multi Project Pipelines.

Multi-project pipeline graphs are useful for larger projects, especially those adopting a microservices architecture, that often have a set of interdependent components which form the complete product.

There's also an discussion regarding multi project build on gitlab here: https://gitlab.com/gitlab-org/gitlab-ce/issues/4194

Body:
I have the following setup:

Java Library 1

Java Library 2

Java application

The "Java application" depends on "Java Library 1" and "Java Library 2" and they are both internal.

"Java Library 1" and "Java Library 2" need to be installed on the local maven repository before "Java application" can be successfully compiled and packaged.

"Java Library 1", "Java Library 2" and "Java application" are separate projects on GitLab.

Each project has a .gitlab-ci.yml.

Each "Java Library" would have something like this:

build:
    script:
        - mvn clean install
    stage: build
    only:
        - master
    tags:
        - java

I want to tell the .gitlab-ci.yml from the "Java application" to first build "Java Library 1" and "Java Library 2".

Is it possible?


问:
Qt Installer Framework: Detecting if VC++ redistributables are installed
I have read this, it is very helpful but it doesn't answer my question. I am using Qt Installer Frame and I want to be able to detect if VC++ redistributables are installed. Because, if they are not, the installer will install them too; and if they already are, the installer won't try to install them again. Is there a way I can do this with Qt Installer Frame?</p>

答:
you have to query directly the Windows Registry.
Basically:

```<code>var registryVC2010x86 = installer.execute("reg", new Array("QUERY", "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\10.0\\VC\\VCRedist\\x86", "/v", "Installed"))[0];
if (!registryVC2010x86) {
// VC2010 x86 redist not found: do something
}
</code>```

I hope this will help.

Body:
you have to query directly the Windows Registry.
Basically:

var registryVC2010x86 = installer.execute("reg", new Array("QUERY", "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\10.0\\VC\\VCRedist\\x86", "/v", "Installed"))[0];
if (!registryVC2010x86) {
// VC2010 x86 redist not found: do something
}

I hope this will help.


问:
IPv6 Address Ranging in C#
I'm writing a socket server that requires the ability to allow/restrict by IP and I'm trying to make it compatible with both IPv4 and IPv6.

I understand the IPv4 principle fairly well, for example I can allow 192.168.0.0/255.255.255.0 catering for all 192.168.0.* addresses, basing my code off of http://blogs.msdn.com/b/knom/archive/2008/12/31/ip-address-calculations-with-c-subnetmasks-networks.aspx.

However, how does this work with IPv6? i.e how do I handle ranges with that protocol?

答:
IPv6 by convention does not use the subnet mask format like IPv4 does. However, there is no reason why you cannot visualise it that way still.

An equivalent “subnet mask” for /64 in IPv6 would be ffff:ffff:ffff:fffff:0:0:0:0. Just don’t try quoting that to any IPv6 user, as nobody will know what you mean. And don’t try pasting that into any IPv6 configuration — people only ever use prefixes like /64, /48, /32, etc. (Anything smaller than /64, such as /96, is rarely used, and officially deprecated for LAN environments.)

Here’s a handy ASCII art chart I just wrote up to help you understand IPv6 prefixes:

```<code>2001:db8:1000:2000:3000:4000:5000:6000/32
<--net--><-------------------host---->

2001:db8:1000:2000:3000:4000:5000:6000/48
<--network--> <--------------host---->

2001:db8:1000:2000:3000:4000:5000:6000/64
<--network-------> <---------host---->

2001:db8:1000:2000:3000:4000:5000:6000/96
<--network------------> <----host---->
</code>```

Hopefully the above is the same way you would visualise IPv4 subnets (it’s pretty much exactly the same, to be honest). In fact, calculating IPv6 is slightly easier in your head, because IPv6 uses hexadecimal, so if you stick to prefixes divisible by 4, you get to divide your subnet at the nybble (i.e. digit) boundary — something you can’t do with IPv4!

I acknowledge that my answer does not have any C# specific information in it. Nevertheless, it should put you on the right track with what to look for: specifying the prefix lengths.

Title: IPv6 Address Ranging in C#

Body:
IPv6 by convention does not use the subnet mask format like IPv4 does. However, there is no reason why you cannot visualise it that way still.

An equivalent “subnet mask” for /64 in IPv6 would be ffff:ffff:ffff:fffff:0:0:0:0. Just don’t try quoting that to any IPv6 user, as nobody will know what you mean. And don’t try pasting that into any IPv6 configuration — people only ever use prefixes like /64, /48, /32, etc. (Anything smaller than /64, such as /96, is rarely used, and officially deprecated for LAN environments.)

Here’s a handy ASCII art chart I just wrote up to help you understand IPv6 prefixes:

2001:db8:1000:2000:3000:4000:5000:6000/32
<--net--><-------------------host---->

2001:db8:1000:2000:3000:4000:5000:6000/48
<--network--> <--------------host---->

2001:db8:1000:2000:3000:4000:5000:6000/64
<--network-------> <---------host---->

2001:db8:1000:2000:3000:4000:5000:6000/96
<--network------------> <----host---->

Hopefully the above is the same way you would visualise IPv4 subnets (it’s pretty much exactly the same, to be honest). In fact, calculating IPv6 is slightly easier in your head, because IPv6 uses hexadecimal, so if you stick to prefixes divisible by 4, you get to divide your subnet at the nybble (i.e. digit) boundary — something you can’t do with IPv4!

I acknowledge that my answer does not have any C# specific information in it. Nevertheless, it should put you on the right track with what to look for: specifying the prefix lengths.


问:
Scylla not working with docker volumes
I am trying out Scylla with Docker and when I try to start a container with volumes like this:

Update: it is only when setting -developer-mode=0 and it runs if setting --developer-mode 1. Just as is says somewhere in the error message. Then what is the different - performance?

```<code>docker run --name some-scylla -v $(pwd)/scylla:/var/lib/scylla -d scylladb/scylla --developer-mode=0
</code>```

I get the following errors:

```<code> docker logs some-scylla
running: (['/usr/lib/scylla/scylla_dev_mode_setup', '--developer-mode', '0'],)
running: (['/usr/lib/scylla/scylla_io_setup'],)
Unexpected end of /proc/mounts line `overlay / overlay rw,relatime,lowerdir=/var/lib/docker/overlay2/l/4EW63UOV5QXIGGMQLID2222UKM:/var/lib/docker/overlay2/l/6XJRXN2HPJYCHXAGSSVWQ7LJM5:/var/lib/docker/overlay2/l/7RYKDGFWLSHQ5RNAQ7UIKI5D7I:/var/lib/docker/overlay2/l/GJCMLIFXUHTV5VL62MKFAXK4AF:/var/lib/docker/overlay2/l/URWQYQVXC7M5WACG5RLJXVXWKQ:/var/lib/docker/overlay2/l/Z7IZ43DGLAA4INFGTVAYIKM6OT:/var/lib/docker/overlay2/l/VH54CMJH4X3CA73VDJ63PA7SWD:/var/lib/docker/overlay2/l/4C7TNR7TY4F3QEOBOFCUBUJWGX:/var/lib/docker/overlay2/l/LNERBP5J7NDIO'
Unexpected end of /proc/mounts line `LH2VHSK2IDPTG:/var/lib/docker/overlay2/l/RNU5XYUHEFGGKKI2Z72VY6AFMR:/var/lib/docker/overlay2/l/62I7NFGNKNPMSYHM4SJOIZF3GE:/var/lib/docker/overlay2/l/ITSIUWLMY2ZDDWIYXHZN3OU3B5:/var/lib/docker/overlay2/l/NJZMNPZMNE4REV5ROKRYKALW66:/var/lib/docker/overlay2/l/6UZO7ISW4XSYPVRBAT2PWLDGTF:/var/lib/docker/overlay2/l/QHVAVYSQMYGUEE5WGGNNFBSKVF:/var/lib/docker/overlay2/l/EUSBWKEFMZRSXJ5OOMI7HC3B3V:/var/lib/docker/overlay2/l/QIJNRYNZVZ2RTON5CACSBQKSMA:/var/lib/docker/overlay2/l/PTQZWWDEG3ACWQMUYQ2V7QTVMS:/var/lib/do'
terminate called after throwing an instance of 'std::system_error'
  what():  open: No such file or directory
ERROR:root:/var/lib/scylla/data did not pass validation tests, it may not be on XFS and/or has limited disk space.
This is a non-supported setup, and performance is expected to be very bad.
For better performance, placing your data on XFS-formatted directories is required.
To override this error, enable developer mode as follow:
sudo /usr/lib/scylla/scylla_dev_mode_setup --developer-mode 1
failed!
Traceback (most recent call last):
  File "/docker-entrypoint.py", line 15, in <module>
    setup.io()
  File "/scyllasetup.py", line 33, in io
    self._run(['/usr/lib/scylla/scylla_io_setup'])
  File "/scyllasetup.py", line 22, in _run
    subprocess.check_call(*args, **kwargs)
  File "/usr/lib64/python3.4/subprocess.py", line 558, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/lib/scylla/scylla_io_setup']' returned non-zero exit status 1
</code>```

Do you know why?

答:
Before starting up, Scylla does a benchmark of your existing I/O infrastructure and determines a bunch of things, like:

what's the maximum number of concurrent requests the disk can take

what's the performance of the filesystem for asynchronous operations

That information is then fed to Scylla's internal disk I/O Scheduler that is used to provide QoS between classes of request.

A lot of the benefits of Scylla - like low latency and automatic isolation between different I/O classes is predicated in a functioning I/O scheduler.

The error message that you see happens because your I/O layer did not pass the basic validation tests, as you can see in this message:

ERROR:root:/var/lib/scylla/data did not pass validation tests, it may not be on XFS and/or has limited disk space.

From the rest of the logs, I am supposing you are using docker's default overlay, as opposed to the recommended method of passing an external XFS-formatted disk to Scylla.

As you found out yourself, you can start the container in developer-mode. That means some aspects of Scylla (like described above) won't function correctly and you will not enjoy the best performance in the database.

If you are not doing any production deployment with this, and is only testing out basic queries and test apps, you are good to go.

Title: Scylla not working with docker volumes

Body:
I am trying out Scylla with Docker and when I try to start a container with volumes like this:

Update: it is only when setting -developer-mode=0 and it runs if setting --developer-mode 1. Just as is says somewhere in the error message. Then what is the different - performance?

docker run --name some-scylla -v $(pwd)/scylla:/var/lib/scylla -d scylladb/scylla --developer-mode=0

I get the following errors:

 docker logs some-scylla
running: (['/usr/lib/scylla/scylla_dev_mode_setup', '--developer-mode', '0'],)
running: (['/usr/lib/scylla/scylla_io_setup'],)
Unexpected end of /proc/mounts line `overlay / overlay rw,relatime,lowerdir=/var/lib/docker/overlay2/l/4EW63UOV5QXIGGMQLID2222UKM:/var/lib/docker/overlay2/l/6XJRXN2HPJYCHXAGSSVWQ7LJM5:/var/lib/docker/overlay2/l/7RYKDGFWLSHQ5RNAQ7UIKI5D7I:/var/lib/docker/overlay2/l/GJCMLIFXUHTV5VL62MKFAXK4AF:/var/lib/docker/overlay2/l/URWQYQVXC7M5WACG5RLJXVXWKQ:/var/lib/docker/overlay2/l/Z7IZ43DGLAA4INFGTVAYIKM6OT:/var/lib/docker/overlay2/l/VH54CMJH4X3CA73VDJ63PA7SWD:/var/lib/docker/overlay2/l/4C7TNR7TY4F3QEOBOFCUBUJWGX:/var/lib/docker/overlay2/l/LNERBP5J7NDIO'
Unexpected end of /proc/mounts line `LH2VHSK2IDPTG:/var/lib/docker/overlay2/l/RNU5XYUHEFGGKKI2Z72VY6AFMR:/var/lib/docker/overlay2/l/62I7NFGNKNPMSYHM4SJOIZF3GE:/var/lib/docker/overlay2/l/ITSIUWLMY2ZDDWIYXHZN3OU3B5:/var/lib/docker/overlay2/l/NJZMNPZMNE4REV5ROKRYKALW66:/var/lib/docker/overlay2/l/6UZO7ISW4XSYPVRBAT2PWLDGTF:/var/lib/docker/overlay2/l/QHVAVYSQMYGUEE5WGGNNFBSKVF:/var/lib/docker/overlay2/l/EUSBWKEFMZRSXJ5OOMI7HC3B3V:/var/lib/docker/overlay2/l/QIJNRYNZVZ2RTON5CACSBQKSMA:/var/lib/docker/overlay2/l/PTQZWWDEG3ACWQMUYQ2V7QTVMS:/var/lib/do'
terminate called after throwing an instance of 'std::system_error'
  what():  open: No such file or directory
ERROR:root:/var/lib/scylla/data did not pass validation tests, it may not be on XFS and/or has limited disk space.
This is a non-supported setup, and performance is expected to be very bad.
For better performance, placing your data on XFS-formatted directories is required.
To override this error, enable developer mode as follow:
sudo /usr/lib/scylla/scylla_dev_mode_setup --developer-mode 1
failed!
Traceback (most recent call last):
  File "/docker-entrypoint.py", line 15, in <module>
    setup.io()
  File "/scyllasetup.py", line 33, in io
    self._run(['/usr/lib/scylla/scylla_io_setup'])
  File "/scyllasetup.py", line 22, in _run
    subprocess.check_call(*args, **kwargs)
  File "/usr/lib64/python3.4/subprocess.py", line 558, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/lib/scylla/scylla_io_setup']' returned non-zero exit status 1

Do you know why?


问:
Opening PDF String in new window with javascript
I have a formatted PDF string that looks like

```<code>%PDF-1.73 0 obj<<< /Type /Group /S /Transparency /CS /DeviceRGB >> /Resources 2 0 R/Contents 4 0 R>> endobj4 0 obj<> streamx��R=o�0��+��=|vL�R���l�-��ځ,���Ge�JK����{���Y5�����Z˯k�vf�a��`G֢ۢ��Asf�z�ͼ��`%��aI#�!;�t���GD?!���<�����B�b��

...

00000 n 0000000703 00000 n 0000000820 00000 n 0000000926 00000 n 0000001206 00000 n 0000001649 00000 n trailer << /Size 11 /Root 10 0 R /Info 9 0 R >>startxref2015%%EOF
</code>```

I am trying to open up this string in a new window as a PDF file.  Whenever I use window.open() and write the string to the new tab it thinks that the text should be the contents of an HTML document.  I want it to recognize that this is a PDF file.

Any help is much appreciated

答:
One suggestion is that use a pdf library like PDFJS.

Yo have to append, the following "data:application/pdf;base64" + your pdf String, and set the src of your element to that.

Try with this example:

```<code>var pdfsrc = "data:application/pdf;base64" + "67987yiujkhkyktgiyuyhjhgkhgyi...n"

<pdf-element id="pdfOpen" elevation="5" downloadable src="pdfsrc" ></pdf-element>
</code>```

Hope it helps :)

Body:
I have a formatted PDF string that looks like

%PDF-1.73 0 obj<<< /Type /Group /S /Transparency /CS /DeviceRGB >> /Resources 2 0 R/Contents 4 0 R>> endobj4 0 obj<> streamx��R=o�0��+��=|vL�R���l�-��ځ,���Ge�JK����{���Y5�����Z˯k�vf�a��`G֢ۢ��Asf�z�ͼ��`%��aI#�!;�t���GD?!���<�����B�b��

...

00000 n 0000000703 00000 n 0000000820 00000 n 0000000926 00000 n 0000001206 00000 n 0000001649 00000 n trailer << /Size 11 /Root 10 0 R /Info 9 0 R >>startxref2015%%EOF

I am trying to open up this string in a new window as a PDF file.  Whenever I use window.open() and write the string to the new tab it thinks that the text should be the contents of an HTML document.  I want it to recognize that this is a PDF file.

Any help is much appreciated

Body:
One suggestion is that use a pdf library like PDFJS.

Yo have to append, the following "data:application/pdf;base64" + your pdf String, and set the src of your element to that.

Try with this example:

var pdfsrc = "data:application/pdf;base64" + "67987yiujkhkyktgiyuyhjhgkhgyi...n"

<pdf-element id="pdfOpen" elevation="5" downloadable src="pdfsrc" ></pdf-element>

Hope it helps :)


问:
[LAContext biometryType]: unrecognized selector on iOS 11.0.0
I see dozens of crashes in fabric

```<code>Fatal Exception: NSInvalidArgumentException
-[LAContext biometryType]: unrecognized selector sent to instance 0x1c066aa00
</code>```

And it's strange because I do call biometryType on LAContext only for iOS 11+.

The code:

```<code>    private static var biometryType: BiometryType? {
        let context = LAContext()

        guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil),
            context.evaluatedPolicyDomainState == BiometryManager.savedPolicyDomainState else { return nil }

        if #available(iOS 11.0, *) {
            switch context.biometryType {
            case .typeFaceID: return .typeFaceID
            case .typeTouchID: return .typeTouchID
            case .none: return nil
            }
        }
        return .typeTouchID
    }
</code>```

Any suggestions?

The only clue I have is that all crashes related to 11.0.0. So maybe Apple added biometryType not in 11.0.0 but a bit later.

Links:

https://developer.apple.com/documentation/localauthentication/lacontext/2867583-biometrytype

http://www.codeprocedures.com/question/nsinvalidargumentexception-unrecognized-selector-sent-to-instance-on-specific-phone-with-ios-11/

答:
As @stonesam92 said, it is probably a bug in ios 11.0.0. The below code safeguards me against the crash.</p>

```<code>if #available(iOS 11.0, *), authenticationContext.responds(to: #selector(getter: LAContext.biometryType))
</code>```

Body:
I see dozens of crashes in fabric

Fatal Exception: NSInvalidArgumentException
-[LAContext biometryType]: unrecognized selector sent to instance 0x1c066aa00

And it's strange because I do call biometryType on LAContext only for iOS 11+.

The code:

    private static var biometryType: BiometryType? {
        let context = LAContext()

        guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil),
            context.evaluatedPolicyDomainState == BiometryManager.savedPolicyDomainState else { return nil }

        if #available(iOS 11.0, *) {
            switch context.biometryType {
            case .typeFaceID: return .typeFaceID
            case .typeTouchID: return .typeTouchID
            case .none: return nil
            }
        }
        return .typeTouchID
    }

Any suggestions?

The only clue I have is that all crashes related to 11.0.0. So maybe Apple added biometryType not in 11.0.0 but a bit later.

Links:

https://developer.apple.com/documentation/localauthentication/lacontext/2867583-biometrytype

http://www.codeprocedures.com/question/nsinvalidargumentexception-unrecognized-selector-sent-to-instance-on-specific-phone-with-ios-11/

Body:
As @stonesam92 said, it is probably a bug in ios 11.0.0. The below code safeguards me against the crash.

if #available(iOS 11.0, *), authenticationContext.responds(to: #selector(getter: LAContext.biometryType))


问:
Laravel How to pass variable from select box to url?
What I am trying to do is basicly passing selected item's slug from a select box to route

```<code>{{ Form::open(['route' => 'list/{category->slug(here)}' ]) }}
<select name="" id="" class="form-control">
    @foreach($categories $category)
        <option value="{{$category->id}}">{{$category->name}}</option>
    @endforeach
</select>
{{ Form::submit('Send') }}
{{ Form::close() }}
</code>```

Can anyone help me?

答:
You need to use some javascript (jQuery) to do this</p>

```<code>$("#select").change(function() {
  var option = $(this).val();
  $("#form-id").attr("action", "list/" + option);
});
</code>```

Body:
What I am trying to do is basicly passing selected item's slug from a select box to route

{{ Form::open(['route' => 'list/{category->slug(here)}' ]) }}
<select name="" id="" class="form-control">
    @foreach($categories $category)
        <option value="{{$category->id}}">{{$category->name}}</option>
    @endforeach
</select>
{{ Form::submit('Send') }}
{{ Form::close() }}

Can anyone help me?

Body:
You need to use some javascript (jQuery) to do this

$("#select").change(function() {
  var option = $(this).val();
  $("#form-id").attr("action", "list/" + option);
});


问:
Cross-DLL calls
When considering cross-DLL calls, if I guarantee that both DLLs use the same compiler and dynamically link to the (same) run-time libraries, does that mean that things like delete and throw will work correctly across the boundary? If not, is there anything that can make such possible?</p>

答: Yes, no problem.  Do a clean build occasionally to catch circular dependencies.</p>

Title: Cross-DLL calls


问:
WPF .NET Popup - open on hover and keep open if mouse is over
I have a Textblock over which I'd like to open a Popup when the mouse is hovering above it. I have binded the IsOpen property using MultiBinding to Popup's IsMouseOver and to the TextBlock's IsMouseOver, and it works, except when the mouse is moved from the text to popup, the popup flickers.

The cause of flickering is the order of execution of events under the hood:

Mouse moves from textblock to popup-->IsMouseOver of textblock is set to false --> converter is called with both parameters being false --> only then IsMouseOver of popup is set to true --> converter is executed with both parameters being false, popup disappears --> Converter called and executed again because another event was raised for IsMouseOver of popup earlier, this time IsMouseOver of Popup True  --> popup appears again. I have tried adding StaysOpen=False, but then it never closes/behaves differently than expected.

Question: how do I avoid the flickering?

Code:

```<code><Grid>
    <ListBox ItemsSource="{Binding RandomNames}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition></ColumnDefinition>
                        <ColumnDefinition></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="Name: "
                               Grid.Column="0"/>
                    <TextBlock Grid.Column="1"
                               x:Name="NameBlock"
                               Text="{Binding}">
                        <TextBlock.Style>
                            <Style TargetType="TextBlock">
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Foreground" Value="Red" />
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                    <Popup x:Name="PopupX"
                           Grid.Column="1"
                           PlacementTarget="{Binding ElementName=NameBlock}"
                           Placement="Bottom">
                        <!--<Popup.IsOpen>
                            <MultiBinding Converter="{StaticResource PopupIsOpenConverter}">
                                <Binding ElementName="PopupX" Path="IsMouseOver" Mode="OneWay" />
                                <Binding ElementName="NameBlock" Path="IsMouseOver" Mode="OneWay" />
                            </MultiBinding>
                        </Popup.IsOpen>-->
                        <Popup.Style>
                            <Style TargetType="Popup">
                                <Setter Property="IsOpen" Value="True" />
                                <Style.Triggers>
                                    <MultiDataTrigger>
                                        <MultiDataTrigger.Conditions>
                                            <Condition Binding="{Binding IsMouseOver, ElementName=NameBlock}" Value="False" />
                                            <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="False" />
                                        </MultiDataTrigger.Conditions>
                                        <Setter Property="IsOpen" Value="False" />
                                    </MultiDataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Popup.Style>
                        <TextBlock Text="{Binding}"
                                   Foreground="Coral" />
                    </Popup>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
</code>```

Converter code

```<code>[ValueConversion(typeof(bool), typeof(bool))]
public class PopupIsOpenConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.Any(value => value is bool && (bool) value);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new ActionNotSupportedException();
    }
}
</code>```

答:
I stumbled over the same flicker problem, and was tempted to use your solution, but searched for something more lightweight first.

I solved it going another way (which I usually avoid like the plague): code behind.
In this case, of just having a popup being open / closed depending on MouseOver over several controls, with no change to the model, this is OK though imho.

Here my solution:

```<code>public class CodebehindOfSomeView
{
    private readonly DispatcherTimer m_ClosePopupTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1) };

    public CodebehindOfSomeView()
    {
        InitializeComponent();

        m_ClosePopupTimer.Tick += ClosePopupTimer_Tick;
    }

    private void ClosePopupTimer_Tick(object _sender, EventArgs _e)
    {
        SomePopup.IsOpen = false;
    }

    private void PopupMouseOverControls_MouseEnter(object _sender, System.Windows.Input.MouseEventArgs _e)
    {
        m_ClosePopupTimer.Stop();
        SomePopup.IsOpen = true;
    }
    private void PopupMouseOverControls_MouseLeave(object _sender, System.Windows.Input.MouseEventArgs _e)
    {
        m_ClosePopupTimer.Start();
    }
}
</code>```

No converter is used.
In the View, just add PopupMouseOverControls_MouseEnter and PopupMouseOverControls_MouseLeave to the MouseEnter and MouseLeave Events of every desired control. Thats it.

A timespan of one millisecond is actually enough to thoroughly get rid of the flickering, if the controls touch each other.

If you would like to give the user a little time to move the mouse from one control to another (over pixels of other controls), just raise the timespan.

Body:
I have a Textblock over which I'd like to open a Popup when the mouse is hovering above it. I have binded the IsOpen property using MultiBinding to Popup's IsMouseOver and to the TextBlock's IsMouseOver, and it works, except when the mouse is moved from the text to popup, the popup flickers.

The cause of flickering is the order of execution of events under the hood:

Mouse moves from textblock to popup-->IsMouseOver of textblock is set to false --> converter is called with both parameters being false --> only then IsMouseOver of popup is set to true --> converter is executed with both parameters being false, popup disappears --> Converter called and executed again because another event was raised for IsMouseOver of popup earlier, this time IsMouseOver of Popup True  --> popup appears again. I have tried adding StaysOpen=False, but then it never closes/behaves differently than expected.

Question: how do I avoid the flickering?

Code:

<Grid>
    <ListBox ItemsSource="{Binding RandomNames}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition></ColumnDefinition>
                        <ColumnDefinition></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="Name: "
                               Grid.Column="0"/>
                    <TextBlock Grid.Column="1"
                               x:Name="NameBlock"
                               Text="{Binding}">
                        <TextBlock.Style>

                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                    <Popup x:Name="PopupX"
                           Grid.Column="1"
                           PlacementTarget="{Binding ElementName=NameBlock}"
                           Placement="Bottom">

                        <Popup.Style>

                            </Style>
                        </Popup.Style>
                        <TextBlock Text="{Binding}"
                                   Foreground="Coral" />
                    </Popup>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Converter code

[ValueConversion(typeof(bool), typeof(bool))]
public class PopupIsOpenConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.Any(value => value is bool && (bool) value);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new ActionNotSupportedException();
    }
}

Body:
I stumbled over the same flicker problem, and was tempted to use your solution, but searched for something more lightweight first.

I solved it going another way (which I usually avoid like the plague): code behind.
In this case, of just having a popup being open / closed depending on MouseOver over several controls, with no change to the model, this is OK though imho.

Here my solution:

public class CodebehindOfSomeView
{
    private readonly DispatcherTimer m_ClosePopupTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1) };

    public CodebehindOfSomeView()
    {
        InitializeComponent();

        m_ClosePopupTimer.Tick += ClosePopupTimer_Tick;
    }

    private void ClosePopupTimer_Tick(object _sender, EventArgs _e)
    {
        SomePopup.IsOpen = false;
    }

    private void PopupMouseOverControls_MouseEnter(object _sender, System.Windows.Input.MouseEventArgs _e)
    {
        m_ClosePopupTimer.Stop();
        SomePopup.IsOpen = true;
    }
    private void PopupMouseOverControls_MouseLeave(object _sender, System.Windows.Input.MouseEventArgs _e)
    {
        m_ClosePopupTimer.Start();
    }
}

No converter is used.
In the View, just add PopupMouseOverControls_MouseEnter and PopupMouseOverControls_MouseLeave to the MouseEnter and MouseLeave Events of every desired control. Thats it.

A timespan of one millisecond is actually enough to thoroughly get rid of the flickering, if the controls touch each other.

If you would like to give the user a little time to move the mouse from one control to another (over pixels of other controls), just raise the timespan.


问:
QRegularExpression match pattern
I want to QRegularExpressionMatch returns true in the following cases:

The string starts with FO . "There is one space after FO"

The string starts with @FOOB.

The string contains FOOBAR.

So, I did:

```<code>QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");

QString string0 = "Anywhere FOOBAR in the string";
QString string1 = "FO in the beginning";
QString string2 = "@FOOB in the beginning";

QRegularExpressionMatch match = rx.match(string1);
if (match.hasMatch())
    QTextStream(stdout) << match.captured(0) << endl;
</code>```

in the code above, there is three patterns. the first and second match in the beginning of the string for FO and @FOOB, the third pattern match anywhere in the string.

Without the third pattern, the code works fine for string1 and string2. With the third pattern, it works just for string0 and string2 and not for string1. I guess the space after FO not match the third pattern then the all the match fails? There is | operator between [first, second] and the third pattern!

Or I miss something, someone can help?
Thank you !

Edit:
Find solution 30 seconds after I posted: These extras space are the problem

```<code>QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");
                                                     ^ ^
</code>```

But I'm not convinced ! Why we use parenthesis then?

答:
Brief

As you've mentioned, you have spaces in your regex, which is why your regex is not working. This solution reduces the number of steps required to return a match.

Code

The regex below can be used if you only want to ensure the string is valid. Note that if the \s is absolutely required (and a word boundary \b doesn't suffice after the ^FO option, you can simply add it to the regular expressions below so that FO becomes FO\s

See regex in use here

```<code>^(?:@FOOB|FO|.*\bFOOBAR)\b.*
</code>```

If you are looking for valid strings and trying to return the match as well, you can use the following regex instead.

```<code>(?:^(?:@FOOB|FO)|\bFOOBAR)\b
</code>```

Results

Input

```<code>Anywhere FOOBAR in the string
FO in the beginning
@FOOB in the beginning
FOOBAR is in the string
In the string is FOOBAR
@FOOBAR is valid because foobar (uppercase) exists

Anywhere FOOBARY in the string
Anywhere FOOBA in the string
FOO is not a valid start
@FOOBA is not a valid start
The @FOOB is not at the start
</code>```

Output

Below shows matches only

```<code>Anywhere FOOBAR in the string
FO in the beginning
@FOOB in the beginning
FOOBAR is in the string
In the string is FOOBAR
@FOOBAR is valid because foobar (uppercase) exists
</code>```

Explanation

^ Assert position at the start of the line

(?:@FOOB|FO|.*\bFOOBAR) Non-capture group to match either of the following

@FOOB Match this literally

FO Match this literally

.*\bFOOBAR Match the following

.* Any character any number of times

\b Assert position as a word boundary

FOOBAR Match this literally

\b Assert position as a word boundary

.* Match any character any number of times

Title: QRegularExpression match pattern

Body:
I want to QRegularExpressionMatch returns true in the following cases:

The string starts with FO . "There is one space after FO"

The string starts with @FOOB.

The string contains FOOBAR.

So, I did:

QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");

QString string0 = "Anywhere FOOBAR in the string";
QString string1 = "FO in the beginning";
QString string2 = "@FOOB in the beginning";

QRegularExpressionMatch match = rx.match(string1);
if (match.hasMatch())
    QTextStream(stdout) << match.captured(0) << endl;

in the code above, there is three patterns. the first and second match in the beginning of the string for FO and @FOOB, the third pattern match anywhere in the string.

Without the third pattern, the code works fine for string1 and string2. With the third pattern, it works just for string0 and string2 and not for string1. I guess the space after FO not match the third pattern then the all the match fails? There is | operator between [first, second] and the third pattern!

Or I miss something, someone can help?
Thank you !

Edit:
Find solution 30 seconds after I posted: These extras space are the problem

QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");
                                                     ^ ^

But I'm not convinced ! Why we use parenthesis then?

Body:
Brief

As you've mentioned, you have spaces in your regex, which is why your regex is not working. This solution reduces the number of steps required to return a match.

Code

The regex below can be used if you only want to ensure the string is valid. Note that if the \s is absolutely required (and a word boundary \b doesn't suffice after the ^FO option, you can simply add it to the regular expressions below so that FO becomes FO\s

See regex in use here

^(?:@FOOB|FO|.*\bFOOBAR)\b.*

If you are looking for valid strings and trying to return the match as well, you can use the following regex instead.

(?:^(?:@FOOB|FO)|\bFOOBAR)\b

Results

Input

Anywhere FOOBAR in the string
FO in the beginning
@FOOB in the beginning
FOOBAR is in the string
In the string is FOOBAR
@FOOBAR is valid because foobar (uppercase) exists

Anywhere FOOBARY in the string
Anywhere FOOBA in the string
FOO is not a valid start
@FOOBA is not a valid start
The @FOOB is not at the start

Output

Below shows matches only

Anywhere FOOBAR in the string
FO in the beginning
@FOOB in the beginning
FOOBAR is in the string
In the string is FOOBAR
@FOOBAR is valid because foobar (uppercase) exists

Explanation

^ Assert position at the start of the line

(?:@FOOB|FO|.*\bFOOBAR) Non-capture group to match either of the following

@FOOB Match this literally

FO Match this literally

.*\bFOOBAR Match the following

.* Any character any number of times

\b Assert position as a word boundary

FOOBAR Match this literally

\b Assert position as a word boundary

.* Match any character any number of times


问:
How to do str_extract with base R?
I am balancing several versions of R and want to change my R libraries loaded depending on which R and which operating system I'm using. As such, I want to stick with base R functions.

I was reading this page to see what the base R equivalent to stringr::str_extract was:

http://stat545.com/block022_regular-expression.html

It suggested I could replicate this functionality with grep. However, I haven't been able to get grep to do more than return the whole string if there is a match. Is this possible with grep alone, or do I need to combine it with another function? In my case I'm trying to distinguish between CentOS versions 6 and 7.

```<code>grep(pattern = "release ([0-9]+)", x = readLines("/etc/system-release"), value = TRUE)
</code>```

答:
```<code>txt <- c("foo release 123", "bar release", "foo release 123 bar release 123")
pattern <- "release ([0-9]+)"
</code>```

Extract first match

```<code>sapply(
    X = txt,
    FUN = function(x){
        tmp = regexpr(pattern, x)
        m = attr(tmp, "match.length")
        st = unlist(tmp)
        if (st == -1){NA}else{substr(x, start = st, stop = st + m - 1)}
    },
    USE.NAMES = FALSE)
#[1] "release 123" NA            "release 123"
</code>```

Extract all matches

```<code>sapply(
    X = txt,
    FUN = function(x){
        tmp = gregexpr(pattern, x)
        m = attr(tmp[[1]], "match.length")
        st = unlist(tmp)
        if (st[1] == -1){
            NA
        }else{
                sapply(seq_along(st), function(i) substr(x, st[i], st[i] + m[i] - 1))
            }
    },
    USE.NAMES = FALSE)
#[[1]]
#[1] "release 123"

#[[2]]
#[1] NA

#[[3]]
#[1] "release 123" "release 123"
</code>```

Title: How to do str_extract with base R?

Body:
I am balancing several versions of R and want to change my R libraries loaded depending on which R and which operating system I'm using. As such, I want to stick with base R functions.

I was reading this page to see what the base R equivalent to stringr::str_extract was:

http://stat545.com/block022_regular-expression.html

It suggested I could replicate this functionality with grep. However, I haven't been able to get grep to do more than return the whole string if there is a match. Is this possible with grep alone, or do I need to combine it with another function? In my case I'm trying to distinguish between CentOS versions 6 and 7.

grep(pattern = "release ([0-9]+)", x = readLines("/etc/system-release"), value = TRUE)

Body:
txt <- c("foo release 123", "bar release", "foo release 123 bar release 123")
pattern <- "release ([0-9]+)"

Extract first match

sapply(
    X = txt,
    FUN = function(x){
        tmp = regexpr(pattern, x)
        m = attr(tmp, "match.length")
        st = unlist(tmp)
        if (st == -1){NA}else{substr(x, start = st, stop = st + m - 1)}
    },
    USE.NAMES = FALSE)
#[1] "release 123" NA            "release 123"

Extract all matches

sapply(
    X = txt,
    FUN = function(x){
        tmp = gregexpr(pattern, x)
        m = attr(tmp[[1]], "match.length")
        st = unlist(tmp)
        if (st[1] == -1){
            NA
        }else{
                sapply(seq_along(st), function(i) substr(x, st[i], st[i] + m[i] - 1))
            }
    },
    USE.NAMES = FALSE)
#[[1]]
#[1] "release 123"

#[[2]]
#[1] NA

#[[3]]
#[1] "release 123" "release 123"


问:
Windows authentication using python
How to do windows authentication using python.. Any tools to debug ? I tried with request_ntlm, but its not helping. Even i'm not able to get www-authenticate header  from response.</p>

答: I fixed this issue, as it was a problem with client side certificate. As my server will authenticate based on client side certificate and private key.We need to set python Environ variable REQUEST_CA_BUNDLE to .pem certificate and passing client certificate and key along with request, it works. If certificate are properly autheticated then will see www-authenticate header from server.</p>

Title: Windows authentication using python


问:
How to add "node_modules" to a downloaded Git repository
I have several questions.

The most important one is what's in the title: How do I add node_modules to a downloaded Git repository? I know that "node_modules" has a lot of files and therefore cannot be held in a Git repository. Please list out step by step what I need to do on my Mac laptop.

Also, it seems like I was able to get node_modules when I create a new project like this

```<code>sudo ng new geckos.
</code>```

However, it comes with its own problems. I cannot create a new project in a directory I like. For example, I wanted to create a project in Documents/GitHub/geckos, but it didn't work. Also I got this warning:

Project name "Documents/GitHub/geckos" is not valid. New project names must start with a letter, and must contain only alphanumeric characters or dashes. When adding a dash the segment after the dash must also start with a letter.

I concluded that it's due to the / slash that I wasn't able to create a new folder. So what should I do to create a new project in the right folder I wanted it to be in?

Lastly, when I do create a new project with all the "node_modules" installed, how do I blend or add the repository that I downloaded to this new project? Is it even possible? I heard something about Git pull. How do I do that?

答:
Of course, you can add node_modules to your Git repository even if this is a bad practice. Firstly you should fetch all the modules using the following command.

```<code>npm install
</code>```

Then, make sure to remove node_modules folder from any .gitignore file in your project.

ContentLicense: CC BY-SA 4.0

Body:
I have several questions.

The most important one is what's in the title: How do I add node_modules to a downloaded Git repository? I know that "node_modules" has a lot of files and therefore cannot be held in a Git repository. Please list out step by step what I need to do on my Mac laptop.

Also, it seems like I was able to get node_modules when I create a new project like this

sudo ng new geckos.

However, it comes with its own problems. I cannot create a new project in a directory I like. For example, I wanted to create a project in Documents/GitHub/geckos, but it didn't work. Also I got this warning:

Project name "Documents/GitHub/geckos" is not valid. New project names must start with a letter, and must contain only alphanumeric characters or dashes. When adding a dash the segment after the dash must also start with a letter.

I concluded that it's due to the / slash that I wasn't able to create a new folder. So what should I do to create a new project in the right folder I wanted it to be in?

Lastly, when I do create a new project with all the "node_modules" installed, how do I blend or add the repository that I downloaded to this new project? Is it even possible? I heard something about Git pull. How do I do that?

Body:
Of course, you can add node_modules to your Git repository even if this is a bad practice. Firstly you should fetch all the modules using the following command.

npm install

Then, make sure to remove node_modules folder from any .gitignore file in your project.


问:
Is using reinterpret_cast after typeid check valid?
If I verify first that pointer to base class is of some type (using typeid), is it valid to do reinterpret_cast on it to save some performance?

```<code>class Base {
    virtual ~Base() {}
};
class A : Base {};
class B : Base {};
...
class Z : Base {};
</code>```

and later on somewhere:

```<code>void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = reinterpret_cast<A*>(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = reinterpret_cast<B*>(&msg);
    } ...
    ...
    } else if (tid == typeid(Z)) {
        Z * ptr = reinterpret_cast<Z*>(&msg);
    }
}
</code>```

As far as I can tell, this code works fine as I think it should. However, I'm curious if it's just because I'm lucky or is this actually well defined usage and all? Using reinterpret_cast this way.

And before you say to just use normal polymorphism for this, I'm not able to change classes as they are so I need to build this way around it.

答:
As with Bathsheba answer, you'll still have undefined behavior.

However, If you don't have virtual inheritance, you can use static_cast, which will offset the pointer to the child class correctly:

```<code>void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = static_cast<A*>(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = static_cast<B*>(&msg);
    } else if (tid == typeid(Z)) {
        Z * ptr = static_cast<Z*>(&msg);
    }
}
</code>```

Body:
If I verify first that pointer to base class is of some type (using typeid), is it valid to do reinterpret_cast on it to save some performance?

class Base {
    virtual ~Base() {}
};
class A : Base {};
class B : Base {};
...
class Z : Base {};

and later on somewhere:

void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = reinterpret_cast(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = reinterpret_cast(&msg);
    } ...
    ...
    } else if (tid == typeid(Z)) {
        Z * ptr = reinterpret_cast<Z*>(&msg);
    }
}

As far as I can tell, this code works fine as I think it should. However, I'm curious if it's just because I'm lucky or is this actually well defined usage and all? Using reinterpret_cast this way.

And before you say to just use normal polymorphism for this, I'm not able to change classes as they are so I need to build this way around it.

Body:
As with Bathsheba answer, you'll still have undefined behavior.

However, If you don't have virtual inheritance, you can use static_cast, which will offset the pointer to the child class correctly:

void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = static_cast<A*>(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = static_cast<B*>(&msg);
    } else if (tid == typeid(Z)) {
        Z * ptr = static_cast<Z*>(&msg);
    }
}


问:
Null Calculation With SQL Select Statement
I have Following Table

```<code>Input           Output
---------------------------------
12.22
                2.22
</code>```

If I pass Following Sql Statement:

Select Input,Output,Balance=sum(Input - Output) from Stock group by input,output

So The Output is:

```<code>Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL
</code>```

If I wants The Output Like Below:

```<code>Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00
</code>```

Than What is SQL Transact Statement?

My Table Structure is as Below:

```<code>companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal
</code>```

Note:- I have applied here Group By function on input and Output columns which doesn't make diference as there is transID columns which is autoincrement hence it should be display all the rows of the table.

答:
Any 'normal' operation involving a null yields null.

Read about COALESCE; use the fact that COALESCE(foo, 0) returns foo if it is not null and returns 0 if foo is null.

Body:
I have Following Table

Input           Output
---------------------------------
12.22
                2.22

If I pass Following Sql Statement:

Select Input,Output,Balance=sum(Input - Output) from Stock group by input,output

So The Output is:

Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL

If I wants The Output Like Below:

Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00

Than What is SQL Transact Statement?

My Table Structure is as Below:

companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal

Note:- I have applied here Group By function on input and Output columns which doesn't make diference as there is transID columns which is autoincrement hence it should be display all the rows of the table.


问:
Set the value in the SELECT map
I am trying to send map to the front end. If i put an atom in the key like in the code below it works fine.

```<code>defp build_select(queryable, opts_select) do
  if opts_select ==  nil do
    queryable
  else
    Enum.reduce opts_select, queryable, fn ({k, v}, queryable) ->
      a = from q in queryable,
        select: %{Data: field(q, ^(String.to_existing_atom k))}

    end
  end
end
</code>```

But i want to send the k value instead of Data. How would i do that? K is a string.

I tried converting the value of k into atom and using it but its not working.

答:
The %{key: value} syntax works for map only for hardcoded atoms as keys. For dynamic values, one should use the hashrocket syntax:

This won’t work:

```<code>key = :foo
%{key: :bar}
#⇒ %{key: :bar}
</code>```

This would:

```<code>key = :foo
%{key => :bar}
#⇒ %{foo: :bar} # NOTE :foo as a key
</code>```

So, turning back to your example:

```<code>- select: %{Data: field(q, ^(String.to_existing_atom k))}

+ key = String.to_existing_atom k
+ select: %{k => field(q, ^k)}
</code>```

Title: Set the value in the SELECT map

Body:
I am trying to send map to the front end. If i put an atom in the key like in the code below it works fine.

defp build_select(queryable, opts_select) do
  if opts_select ==  nil do
    queryable
  else
    Enum.reduce opts_select, queryable, fn ({k, v}, queryable) ->
      a = from q in queryable,
        select: %{Data: field(q, ^(String.to_existing_atom k))}

    end
  end
end

But i want to send the k value instead of Data. How would i do that? K is a string.

I tried converting the value of k into atom and using it but its not working.

Body:
The %{key: value} syntax works for map only for hardcoded atoms as keys. For dynamic values, one should use the hashrocket syntax:

This won’t work:

key = :foo
%{key: :bar}
#⇒ %{key: :bar}

This would:

key = :foo
%{key => :bar}
#⇒ %{foo: :bar} # NOTE :foo as a key

So, turning back to your example:

- select: %{Data: field(q, ^(String.to_existing_atom k))}

+ key = String.to_existing_atom k
+ select: %{k => field(q, ^k)}


问:
Highlight area programmatically - Chart.js
I'm using Chart.js (doughnut chart) and I would like to ask if is there any choice to highlight area programmatically? I mean - when I click on a button, then the specific area will be highlighted.

Thanks for your reply.

答:
FYI the fiddles are no longer working, you'll need to replace the links to the Chart.min.js
I used these to get them working: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js</p>


问:
AddTransient: Is there a difference?
Question(s) related to the IServiceCollection.AddTransient method.

Do the below 2 lines of code basically do the same thing?  Are they different? Is there an advantage to using one verses the other?

```<code>services.AddTransient<MyService,MyService>();
services.AddTransient<MyService>();
</code>```

I originally had my code set up with the first line and everything worked.  But then I was investigating another issue and I saw an example of the second line. So, I changed my code out of curiosity and everything still worked.

Just curious.

答:
From sources:

```<code>public static IServiceCollection AddTransient<TService>(this IServiceCollection services) where TService : class
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  return services.AddTransient(typeof (TService));
}
</code>```

call services.AddTransient(typeof (TService))

that is:

```<code>public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType)
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  if (serviceType == (Type) null)
    throw new ArgumentNullException(nameof (serviceType));
  return services.AddTransient(serviceType, serviceType);
}
</code>```

which is exactly the same call that method with 2 arguments do:

```<code>public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  return services.AddTransient(typeof (TService), typeof (TImplementation));
}
</code>```

So this is just shortcut for case when you want register implementation to self.
Usually you will use different types for service and implementation (interface and implementation or abstract class and derived class with implementation).

Title: AddTransient: Is there a difference?

Body:
Question(s) related to the IServiceCollection.AddTransient method.

Do the below 2 lines of code basically do the same thing?  Are they different? Is there an advantage to using one verses the other?

services.AddTransient<MyService,MyService>();
services.AddTransient<MyService>();

I originally had my code set up with the first line and everything worked.  But then I was investigating another issue and I saw an example of the second line. So, I changed my code out of curiosity and everything still worked.

Just curious.

Body:
From sources:

public static IServiceCollection AddTransient<TService>(this IServiceCollection services) where TService : class
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  return services.AddTransient(typeof (TService));
}

call services.AddTransient(typeof (TService))

that is:

public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType)
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  if (serviceType == (Type) null)
    throw new ArgumentNullException(nameof (serviceType));
  return services.AddTransient(serviceType, serviceType);
}

which is exactly the same call that method with 2 arguments do:

public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
{
  if (services == null)
    throw new ArgumentNullException(nameof (services));
  return services.AddTransient(typeof (TService), typeof (TImplementation));
}

So this is just shortcut for case when you want register implementation to self.
Usually you will use different types for service and implementation (interface and implementation or abstract class and derived class with implementation).


问:
Why return type of AKKA actor postStop not void?
In overriding the postStop method I got this very strange:
error message from illelliJ

the class is very simple:

```<code>public class TempClass extends AbstractActor {
      @Override
      public void postStop(){}
}
</code>```

the api indicates the return type is void, do I miss something in my code?

答:
Answer my own question:
The problem is the scala-library.jar is not added scala-library</p>

Body:
In overriding the postStop method I got this very strange:
error message from illelliJ

the class is very simple:

public class TempClass extends AbstractActor {
      @Override
      public void postStop(){}
}

the api indicates the return type is void, do I miss something in my code?


问:
Setting up a personal (Java) workspace: What do I need?
I want to set up a personal workspace on my home machine. I mainly intend to use it for Java development on home projects. Which tools do you recommend me to use? (I prefer free tools, since this is just for home use.)

I hope you could recommend some tools for me, and I'd be grateful if you could give me a brief comparison of some tools in each category. For example, I'm thinking about source control and issue tracking tools, but any other categories are welcome.

I also hope to get some information about the ability to move between suggested tools (e.g. migrate between CVS and SVN), and even between operating systems if applicable. (I'm currently using Windows Vista, but I may want to switch to Linux sometime soon.) Maybe even information about how easy it would be to move the project to an open-source repository (e.g. SF.net).

Thank you.

(P.S. Any comments on how to enhance/clarify my question are more than welcome.)

答:
Version Control

I would recommend SVN over CVS, although distributed version tracking tools like Git and Mercurial seem to be very popular among open source projects.

Importing into a public repository should be easy; if you don't want to keep the revision history, just 'export' a clean copy of the repository, and check it in to the new one.

If you do want to keep the revision history, there are tools for cloning repositories, although converting from one type to another might be more tricky.

Bug tracking

The most well-known system is possibly Bugzilla - it's the only one I've used on a local system myself. Others can possibly recommend a better single-person tracker. Bugzilla is hosted on a MySQL database, so you should be able to move it to another server easily enough. Moving between bug tracking systems may need a more complicated script though.

OwnerDisplayName: Hosam Aly

OwnerDisplayName: Mike Houston


问:
tf.estimator shuffle - random seed?
When I repeatedly run tf.estimator.LinearRegressor the results are slightly different each time. I'm guessing that's because of the shuffle=True here:

```<code>input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)
</code>```

Which is fine as far as it goes, but when I try to make it deterministic by seeding the random number generators in both np and tf:

```<code>np.random.seed(1)
tf.set_random_seed(1)
</code>```

The results are still slightly different each time. What am I missing?

答:
tf.set_random_seed sets the graph-level seed, but it's not the only source of randomness, because there is also an operation-level seed, which needs to be provided for each op.

Unfortunately, tf.estimator.inputs.numpy_input_fn does not provide the seed argument along with shuffle to pass them to the underlying ops (source code). As a result, _enqueue_data function always gets the seed=None, which will reset any seed you set in advance. By the way, it's interesting to note that many of the underlying feed functions use standard python random.seed for shuffle, not tensorflow random (see _ArrayFeedFn, _OrderedDictNumpyFeedFn, etc).

Summary: currently there's no way to guarantee stable execution with shuffle=True, at least with the current API. The only option you have is to shuffle the data yourself and pass shuffle=False.

Title: tf.estimator shuffle - random seed?

Body:
When I repeatedly run tf.estimator.LinearRegressor the results are slightly different each time. I'm guessing that's because of the shuffle=True here:

input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)

Which is fine as far as it goes, but when I try to make it deterministic by seeding the random number generators in both np and tf:

np.random.seed(1)
tf.set_random_seed(1)

The results are still slightly different each time. What am I missing?


问:
Trigger jquery function from select dropdown
This should be really easy, but I have been going around in circles with it for the past three hours... I know that I should change the ID of SELECT to match that of the jquery function, but there is another step (obviously) that I am missing.

I am using the jqueryui datepicker, and I simply want it to pop up when a particular value is chosen with a 'select' dropdown, rather than when an 'input' field is clicked. Here is the code, thanks in advance for your help:

```<code>    <SELECT id="">
        <option value="1">TODAY</option>
        <option value="2">TOMORROW</option>
        <option selected value="3">THIS WEEK</option>
        <option value="4">NEXT WEEK</option>
        <option value="5">THIS MONTH</option>
        <option value="6">NEXT MONTH</option>
        <option value="7">CALENDAR SHOULD POP UP WHEN THIS OPTION IS SELECTED</option>
    </SELECT>

<input type="text" id="datepicker" value="INSTEAD OF THIS">

  <script>
  $( function() {
    $( "#datepicker" ).datepicker({
      minDate: 0, maxDate: "+2Y"
    });
  } );
  </script>
</code>```

答:
Sure, you can bind a change handler to the select element and trigger the datepicker's show method like:

```<code>$('select').change(function() {
  if ($(this).val() == 7) {
    $("#datepicker").datepicker("show")
  }
})
</code>```

jsFiddle example

Body:
This should be really easy, but I have been going around in circles with it for the past three hours... I know that I should change the ID of SELECT to match that of the jquery function, but there is another step (obviously) that I am missing.

I am using the jqueryui datepicker, and I simply want it to pop up when a particular value is chosen with a 'select' dropdown, rather than when an 'input' field is clicked. Here is the code, thanks in advance for your help:

    <SELECT id="">
        <option value="1">TODAY</option>
        <option value="2">TOMORROW</option>
        <option selected value="3">THIS WEEK</option>
        <option value="4">NEXT WEEK</option>
        <option value="5">THIS MONTH</option>
        <option value="6">NEXT MONTH</option>
        <option value="7">CALENDAR SHOULD POP UP WHEN THIS OPTION IS SELECTED</option>
    </SELECT>

<input type="text" id="datepicker" value="INSTEAD OF THIS">

Body:
Sure, you can bind a change handler to the select element and trigger the datepicker's show method like:

$('select').change(function() {
  if ($(this).val() == 7) {
    $("#datepicker").datepicker("show")
  }
})

jsFiddle example


问:
returning single result using LINQ
I have a query

```<code>row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))
</code>```

This query returns an IEnumerable. I am expecting an 'int'

Help me modify my LINQ query

答:
just SingleOrDefault() instead of Select(), keep in mind if there more than one result you will get an exception, you can also useFirstOrDefault(),so it will look like:

```<code>row.GetChildRows("EventCategoryRelation")
.Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
.SingleOrDefault(x => Int32.Parse(x["category_id"].ToString()))
</code>```

Title: returning single result using LINQ

Body:
I have a query

row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))

This query returns an IEnumerable. I am expecting an 'int'

Help me modify my LINQ query

Body:
just SingleOrDefault() instead of Select(), keep in mind if there more than one result you will get an exception, you can also useFirstOrDefault(),so it will look like:

row.GetChildRows("EventCategoryRelation")
.Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
.SingleOrDefault(x => Int32.Parse(x["category_id"].ToString()))


答:
You can prune the regex a bit more after remiving unnecessary spaces:

```<code>QRegularExpression rx("^(?:FO\\s|@FOOB\\b)|\\bFOOBAR\\b");
</code>```

Details:

^(?:FO\\s|@FOOB\\b) - FO and any whitespace or a whole word @FOOB at the start of the string

| - or

\\bFOOBAR\\b - a whole word FOOBAR

Title: QRegularExpression match pattern

Body:
I want to QRegularExpressionMatch returns true in the following cases:

The string starts with FO . "There is one space after FO"

The string starts with @FOOB.

The string contains FOOBAR.

So, I did:

QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");

QString string0 = "Anywhere FOOBAR in the string";
QString string1 = "FO in the beginning";
QString string2 = "@FOOB in the beginning";

QRegularExpressionMatch match = rx.match(string1);
if (match.hasMatch())
    QTextStream(stdout) << match.captured(0) << endl;

in the code above, there is three patterns. the first and second match in the beginning of the string for FO and @FOOB, the third pattern match anywhere in the string.

Without the third pattern, the code works fine for string1 and string2. With the third pattern, it works just for string0 and string2 and not for string1. I guess the space after FO not match the third pattern then the all the match fails? There is | operator between [first, second] and the third pattern!

Or I miss something, someone can help?
Thank you !

Edit:
Find solution 30 seconds after I posted: These extras space are the problem

QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");
                                                     ^ ^

But I'm not convinced ! Why we use parenthesis then?

Body:
You can prune the regex a bit more after remiving unnecessary spaces:

QRegularExpression rx("^(?:FO\\s|@FOOB\\b)|\\bFOOBAR\\b");

Details:

^(?:FO\\s|@FOOB\\b) - FO and any whitespace or a whole word @FOOB at the start of the string

| - or

\\bFOOBAR\\b - a whole word FOOBAR