问:
Method not found using DigestUtils in Android
I am trying to use the library DigestUtils in Android 2.3.1 using JDK 1.6, however I get the following error when executing the app:

Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex

Here you have the stacktrace:

```<code>02-03 10:25:45.153: I/dalvikvm(1230): Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex
02-03 10:25:45.153: W/dalvikvm(1230): VFY: unable to resolve static method 329: Lorg/apache/commons/codec/binary/Hex;.encodeHexString ([B)Ljava/lang/String;
02-03 10:25:45.153: D/dalvikvm(1230): VFY: replacing opcode 0x71 at 0x0004
02-03 10:25:45.153: D/dalvikvm(1230): VFY: dead code 0x0007-0008 in Lorg/apache/commons/codec/digest/DigestUtils;.shaHex ([B)Ljava/lang/String;
02-03 10:25:45.163: D/AndroidRuntime(1230): Shutting down VM
02-03 10:25:45.163: W/dalvikvm(1230): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-03 10:25:45.173: E/AndroidRuntime(1230): FATAL EXCEPTION: main
02-03 10:25:45.173: E/AndroidRuntime(1230): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Hex.encodeHexString
02-03 10:25:45.173: E/AndroidRuntime(1230):     at org.apache.commons.codec.digest.DigestUtils.md5Hex(DigestUtils.java:226)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at com.caumons.trainingdininghall.ConnectionProfileActivity.onCreate(ConnectionProfileActivity.java:20)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.os.Looper.loop(Looper.java:123)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.main(ActivityThread.java:3647)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at java.lang.reflect.Method.invokeNative(Native Method)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at java.lang.reflect.Method.invoke(Method.java:507)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at dalvik.system.NativeStart.main(Native Method)
</code>```

The line of code which causes the exception is:

String hash = DigestUtils.shaHex("textToHash");

I have executed the same code in a Java class outside Android and it works! So, I do not know why when working with Android it does not work... I put the libraty inside a new libs/ folder in my app and updated the BuildPath to use it. If I try to use md5 instead of sha1 I get the same exception. Any help would be appreciated! Thank you.

UPDATE:

As this is a very active question, I've changed the accepted answer in favour of @DA25, as his solution is straightforward and the high number of upvotes prove that it works.

答:
Add method </p>

```<code>public static String byteArrayToHexString(byte[] bytes) {
    final char[] toDigits = "0123456789abcdef".toCharArray();
    int l = bytes.length;
    char[] out = new char[l << 1];

    int i = 0; for (int j = 0; i < l; ++i) {
        out[(j++)] = toDigits[((0xF0 & bytes[i]) >>> 4)];
        out[(j++)] = toDigits[(0xF & bytes[i])];
    }
    return new String(out);
}
</code>```

Body:
I am trying to use the library DigestUtils in Android 2.3.1 using JDK 1.6, however I get the following error when executing the app:

Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex

Here you have the stacktrace:

02-03 10:25:45.153: I/dalvikvm(1230): Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex
02-03 10:25:45.153: W/dalvikvm(1230): VFY: unable to resolve static method 329: Lorg/apache/commons/codec/binary/Hex;.encodeHexString ([B)Ljava/lang/String;
02-03 10:25:45.153: D/dalvikvm(1230): VFY: replacing opcode 0x71 at 0x0004
02-03 10:25:45.153: D/dalvikvm(1230): VFY: dead code 0x0007-0008 in Lorg/apache/commons/codec/digest/DigestUtils;.shaHex ([B)Ljava/lang/String;
02-03 10:25:45.163: D/AndroidRuntime(1230): Shutting down VM
02-03 10:25:45.163: W/dalvikvm(1230): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-03 10:25:45.173: E/AndroidRuntime(1230): FATAL EXCEPTION: main
02-03 10:25:45.173: E/AndroidRuntime(1230): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Hex.encodeHexString
02-03 10:25:45.173: E/AndroidRuntime(1230):     at org.apache.commons.codec.digest.DigestUtils.md5Hex(DigestUtils.java:226)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at com.caumons.trainingdininghall.ConnectionProfileActivity.onCreate(ConnectionProfileActivity.java:20)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.os.Looper.loop(Looper.java:123)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at android.app.ActivityThread.main(ActivityThread.java:3647)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at java.lang.reflect.Method.invokeNative(Native Method)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at java.lang.reflect.Method.invoke(Method.java:507)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-03 10:25:45.173: E/AndroidRuntime(1230):     at dalvik.system.NativeStart.main(Native Method)

The line of code which causes the exception is:

String hash = DigestUtils.shaHex("textToHash");

I have executed the same code in a Java class outside Android and it works! So, I do not know why when working with Android it does not work... I put the libraty inside a new libs/ folder in my app and updated the BuildPath to use it. If I try to use md5 instead of sha1 I get the same exception. Any help would be appreciated! Thank you.

UPDATE:

As this is a very active question, I've changed the accepted answer in favour of @DA25, as his solution is straightforward and the high number of upvotes prove that it works.

Body:
Add method

public static String byteArrayToHexString(byte[] bytes) {
    final char[] toDigits = "0123456789abcdef".toCharArray();
    int l = bytes.length;
    char[] out = new char[l << 1];

    int i = 0; for (int j = 0; i < l; ++i) {
        out[(j++)] = toDigits[((0xF0 & bytes[i]) >>> 4)];
        out[(j++)] = toDigits[(0xF & bytes[i])];
    }
    return new String(out);
}


来源: stackexchange

问:
Creating a service that streams video: Where to start?
I want to create a service that streams live traffic video to either a client browser or a client processor (which will actually process the video).  I want real video, not just images that update periodically.  Assume I know the basic concepts of web design (both front and back end).  But assume I know nothing about streaming media.

Can someone point me in the direction to get started?

I need information concerning software, frameworks (especially if it's compatible with Ruby on Rails), encoders, converters, protocols, ...  - thanks!

答:
What about something like tokbox?

http://www.tokbox.com/

I havent personally used it. However I have visited an on line video podcast that uses this technology. Good quality streaming.

ContentLicense: CC BY-SA 2.5


问:
VBA trying to specify a newly created workbook rather than activeworkbook (to paste some data into the new one)
I've got some code that copies some data, then I want it to create a new workbook and paste the copied data into the new workbook. At the moment the code uses ActiveSheet.Range("A1").PasteSpecial etc which is fine if the newly created workbook is the active sheet but if it isnt that obviously doesn't work. here's the entire sub (with some stop markers as i've been debugging it):

```<code>Sub ExportToCSV()
Dim ws As Worksheet, xFolder As String, xName As String
Dim InitialFoldr$

InitialFoldr$ = "L:\107xxx\1077898 A34 Oxford junctions 1718\200 M & A"

MsgBox ("Choose where to save the Paramics demands")
xFolder = GetFolder(InitialFoldr$)

For Each ws In ThisWorkbook.Worksheets
    If ws.Name Like "*PDMND" Then
        xName = ws.Name
        ws.Range("BJ4:CK82").Copy
        'Stop
        With CreateObject("Excel.Application")
            .Workbooks.Add
            .Visible = True
        End With
        ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteValues
        Stop
        ActiveWorkbook.SaveAs Filename:=xFolder + "\" + xName + ".csv", FileFormat:=xlCSV, CreateBackup:=False

        Application.DisplayAlerts = False
        ActiveWorkbook.Close
        Application.DisplayAlerts = True
    End If
    'Stop
Next
End Sub
</code>```

After the with loop to create the new workbook, i want to make a variable that refers to the new workbook and then i can use the variable to paste the data in the right place - or something akin to this - to replace the ActiveSheet.Paste bit. How do I accomplish this?

Edit: I have used the information in the similar answer here so my code now looks like this:

```<code>xFolder = GetFolder(InitialFoldr$)

For Each ws In ThisWorkbook.Worksheets
    If ws.Name Like "*PDMND" Then
        xName = ws.Name
    ws.Range("BJ4:CK82").Copy

    Set oWb = Workbooks.Add

            oWb.Range("A1").PasteSpecial Paste:=xlPasteValues
            Stop
</code>```

But now Excel crashes without fail after I select the save folder. Is there an obvious reason for this?

答:
When you create the new workbook, save the workbook object so you can reference it later... like this:

Before you start your loop add:

```<code>    Dim wbNew as Workbook
</code>```

Then inside your loop...

```<code>    With CreateObject("Excel.Application")
        Set wbNew = .Workbooks.Add
        .Visible = True
    End With
    wbNew.WorkSheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got some code that copies some data, then I want it to create a new workbook and paste the copied data into the new workbook. At the moment the code uses ActiveSheet.Range("A1").PasteSpecial etc which is fine if the newly created workbook is the active sheet but if it isnt that obviously doesn't work. here's the entire sub (with some stop markers as i've been debugging it):

Sub ExportToCSV()
Dim ws As Worksheet, xFolder As String, xName As String
Dim InitialFoldr$

InitialFoldr$ = "L:\107xxx\1077898 A34 Oxford junctions 1718\200 M & A"

MsgBox ("Choose where to save the Paramics demands")
xFolder = GetFolder(InitialFoldr$)

For Each ws In ThisWorkbook.Worksheets
    If ws.Name Like "*PDMND" Then
        xName = ws.Name
        ws.Range("BJ4:CK82").Copy
        'Stop
        With CreateObject("Excel.Application")
            .Workbooks.Add
            .Visible = True
        End With
        ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteValues
        Stop
        ActiveWorkbook.SaveAs Filename:=xFolder + "\" + xName + ".csv", FileFormat:=xlCSV, CreateBackup:=False

        Application.DisplayAlerts = False
        ActiveWorkbook.Close
        Application.DisplayAlerts = True
    End If
    'Stop
Next
End Sub

After the with loop to create the new workbook, i want to make a variable that refers to the new workbook and then i can use the variable to paste the data in the right place - or something akin to this - to replace the ActiveSheet.Paste bit. How do I accomplish this?

Edit: I have used the information in the similar answer here so my code now looks like this:

xFolder = GetFolder(InitialFoldr$)

For Each ws In ThisWorkbook.Worksheets
    If ws.Name Like "*PDMND" Then
        xName = ws.Name
    ws.Range("BJ4:CK82").Copy

    Set oWb = Workbooks.Add

            oWb.Range("A1").PasteSpecial Paste:=xlPasteValues
            Stop

But now Excel crashes without fail after I select the save folder. Is there an obvious reason for this?

Body:
When you create the new workbook, save the workbook object so you can reference it later... like this:

Before you start your loop add:

    Dim wbNew as Workbook

Then inside your loop...

    With CreateObject("Excel.Application")
        Set wbNew = .Workbooks.Add
        .Visible = True
    End With
    wbNew.WorkSheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues


问:
matplotlib legend avoids points when manually setting coordinates
In the following code, I generate a scatterplot where the legend is manually placed:

```<code>#!/usr/bin/env python3

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

frame = frame = pd.DataFrame({"x": [1, 2, 3, 4], "y": [4, 3, 2, 1]})
ax = frame.plot.scatter(x="x", y="y", label="dots")
plt.savefig("dots.pdf")
for y in [0.6, 0.7, 0.8]:
    ax.legend(bbox_to_anchor=(0.5, y), bbox_transform=ax.transAxes)
    plt.savefig("dots_{}.png".format(y))
</code>```

It looks like the legend does not obey  the placement instructions when it would make it hide a point:

Is there a way to avoid this? I mean, how to really force the placement of the legend?

答:
You may be interested in reading my answer to "How to put the legend out of the plot". While it handles the case of putting the legend outside of the plot, most of it is applicable to placing the legend just anywhere, including inside the plot.

Most imporantly, the legend position is determined by the loc parameter. If you do not specify this parameter in the call to legend(), matplotlib will try to place the legend whereever it thinks it's best, (default is loc ="best").

In case you want to place the legend at a certain position, you may specify the coordinates of its lower left corner to loc:

```<code>ax.legend(loc=(0.5, 0.6))
</code>```

If you want to specify another corner of the legend to be at a certain position, you need to specify the corner with the loc argument and the position using bbox_to_anchor:

```<code>ax.legend(loc="upper right", bbox_to_anchor=(0.5, 0.6))
</code>```

Body:
In the following code, I generate a scatterplot where the legend is manually placed:

#!/usr/bin/env python3

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

frame = frame = pd.DataFrame({"x": [1, 2, 3, 4], "y": [4, 3, 2, 1]})
ax = frame.plot.scatter(x="x", y="y", label="dots")
plt.savefig("dots.pdf")
for y in [0.6, 0.7, 0.8]:
    ax.legend(bbox_to_anchor=(0.5, y), bbox_transform=ax.transAxes)
    plt.savefig("dots_{}.png".format(y))

It looks like the legend does not obey  the placement instructions when it would make it hide a point:

Is there a way to avoid this? I mean, how to really force the placement of the legend?

Body:
You may be interested in reading my answer to "How to put the legend out of the plot". While it handles the case of putting the legend outside of the plot, most of it is applicable to placing the legend just anywhere, including inside the plot.

Most imporantly, the legend position is determined by the loc parameter. If you do not specify this parameter in the call to legend(), matplotlib will try to place the legend whereever it thinks it's best, (default is loc ="best").

In case you want to place the legend at a certain position, you may specify the coordinates of its lower left corner to loc:

ax.legend(loc=(0.5, 0.6))

If you want to specify another corner of the legend to be at a certain position, you need to specify the corner with the loc argument and the position using bbox_to_anchor:

ax.legend(loc="upper right", bbox_to_anchor=(0.5, 0.6))


问:
Compressing a JPG image to a given size in KB?
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

```<code>public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}
</code>```

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

答:
You could use Magick.NET (https://github.com/dlemstra/Magick.NET) for this:</p>

```<code>using (var image = new MagickImage(capture))
{
    return image.ToByteArray(new JpegWriteDefines()
    {
        // Will make the maximum size 500KB (it might be smaller)
        Extent = 500
    });
}
</code>```

Body:
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

Body:
You could use Magick.NET (https://github.com/dlemstra/Magick.NET) for this:

using (var image = new MagickImage(capture))
{
    return image.ToByteArray(new JpegWriteDefines()
    {
        // Will make the maximum size 500KB (it might be smaller)
        Extent = 500
    });
}


问:
LC-3 Operands that only use registers
Hi i had a quick question

Which of the following LC-3 instructions can only have operands that are in registers (i.e. cannot have
immediate or memory operands)?

a. ADD b. NOT c. LD d. AND

From what I can tell this would be NOT as ADD and AND use registers along with immediate values. While LD has the pcoffset? So I was wondering if this is correct?

答:
If you look up the NOT instruction for LC-3, you'll see that the opcode takes the format:

```<code>opcode   destination-reg   source-reg
 1001       xxx                yyy      111111
</code>```

or:

```<code>1001xxxyyy111111
</code>```

ADD takes the form:

```<code>0001xxxyyy000zzz for register values
0001xxxyyy1zzzzz for immediate values
</code>```

AND takes the form:

```<code>0101xxxyyy000zzz for register values
0101xxxyyy1zzzzz for immediate values
</code>```

LD takes a register to load into and an offset to the memory:

```<code>0010xxxyyyyyyyyy
</code>```

If you count the offset as an operand, then the answer is NOT and LD, otherwise, it's just NOT.

Title: LC-3 Operands that only use registers

Body:
If you look up the NOT instruction for LC-3, you'll see that the opcode takes the format:

opcode   destination-reg   source-reg
 1001       xxx                yyy      111111

or:

1001xxxyyy111111

ADD takes the form:

0001xxxyyy000zzz for register values
0001xxxyyy1zzzzz for immediate values

AND takes the form:

0101xxxyyy000zzz for register values
0101xxxyyy1zzzzz for immediate values

LD takes a register to load into and an offset to the memory:

0010xxxyyyyyyyyy

If you count the offset as an operand, then the answer is NOT and LD, otherwise, it's just NOT.


问:
Autogenerate primitive byte array generics with jsonschema2pojo
Is there a way to autogenerate java classes from json with jsonschema2pojo where the generics include a primitive byte array? For example i want to generate this private Map<String, byte[]> mappy; and so far I managed to generate private Map<String, Byte[]> mappy; by using this:

```<code>"properties": {
  "mappy": {
    "id": "/response/images",
    "title": "(images) The images property.",
    "javaType" : "java.util.Map<String, Byte[]>",
    "type" : "object"
  }
}
</code>```

but I'd rather use the primitive byte array instead of the Byte array. If i try to use byte[] instead of Byte[] jsonschema2pojo throws an exception.

答:
OK. I figured a way by using the replacer plugin in the pom.xml file like this:

```<code>        <plugin>
            <groupId>com.google.code.maven-replacer-plugin</groupId>
            <artifactId>replacer</artifactId>
            <version>1.5.3</version>
            <executions>
                <execution>
                    <id>Convert commons-lang to commons-lang3</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>replace</goal>
                    </goals>
                    <configuration>
                        <includes>
                            <include>${basedir}/target/java-gen/*.java</include>
                        </includes>
                        <replacements>
                            <replacement>
                                <token>Byte</token>
                                <value>byte</value>
                            </replacement>
                        </replacements>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Body:
Is there a way to autogenerate java classes from json with jsonschema2pojo where the generics include a primitive byte array? For example i want to generate this private Map<String, byte[]> mappy; and so far I managed to generate private Map<String, Byte[]> mappy; by using this:

"properties": {
  "mappy": {
    "id": "/response/images",
    "title": "(images) The images property.",
    "javaType" : "java.util.Map<String, Byte[]>",
    "type" : "object"
  }
}

but I'd rather use the primitive byte array instead of the Byte array. If i try to use byte[] instead of Byte[] jsonschema2pojo throws an exception.

Body:
OK. I figured a way by using the replacer plugin in the pom.xml file like this:

        <plugin>
            <groupId>com.google.code.maven-replacer-plugin</groupId>
            <artifactId>replacer</artifactId>
            <version>1.5.3</version>
            <executions>
                <execution>
                    <id>Convert commons-lang to commons-lang3</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>replace</goal>
                    </goals>
                    <configuration>
                        <includes>
                            <include>${basedir}/target/java-gen/*.java</include>
                        </includes>
                        <replacements>
                            <replacement>
                                <token>Byte</token>
                                <value>byte</value>
                            </replacement>
                        </replacements>
                    </configuration>
                </execution>
            </executions>
        </plugin>


问:
How to show different Views on different Drupal Themes
Say I have a default theme for my drupal site. Here I have created views, blocks, etc and styled everything the way I want for the public. Now, as the admin I would like to have an entirely separate theme. No problem, I create a second theme in the themes directory and switch my admin user theme configuration to the second theme. But, what if in my second theme I want to show entirely different content (i.e. Views, blocks, etc).
Let's use my front page as an example (front).
Right now my front page has a slideshow using Views. This view obviously shows up on the front page no matter what theme I'm using. So for my front page, how could I show an entirely different View (say a list of blog posts) for the second theme than the slideshow View I'm using for the first theme?</p>

答:
This seams like a wonder application of two fairly new but very powerful modules.

Context - http://drupal.org/project/context in conjunction with Spaces - http://drupal.org/project/spaces

or

Panels http://drupal.org/project/panels

Both have concepts that allow you to set a context for pages that changes the output based on a variety of criteria. In your case the criteria would be the role of the user viewing the page. Both more less unwieldy than the tricks that CurtainDog offered up, which btw are all very valid approaches. The advantage of these two modules is that they make the organization and selection process much more sane and simple.

It's difficult to advise one over the other, but in a nutshell: Panels has more options in the interface, but has a bit of a learning curve on the code level. Context / Spaces is very easy to work with on the programing level, but required more coding to accomplish most tasks. I would suggest trying both before committing to either. For a wonderful discussion of both listen to this podcast.


问:
difference between input:disabled and input[disabled] CSS selector
I'm wondering is there any difference between using the :disabled CSS pseudo-class selector and the [disabled] CSS attribute selector (e.g. different browsers support or whatever) to apply styles on a disabled HTML input element or are they totally equivalent?

答:
:disabled is introduced in css3. [disabled] exists from css2.

I would prefer :disabled over [disabled], see this question from: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


问:
Usage of jacococli.jar with multiple classfiles
As in most cases my class files are at 2 locations inside tomcat at, lib and classes. Now once .exec file is created I need to pull a report referencing both the locations classes and a few jars in lib, for this I am using the below command

```<code>java -jar jacococli.jar report /local/jacoco.exec --html /jacocoReport/html --name MergeCode --classfiles /tomcat/webapps/<app>/WEB-INF/lib/new.jar /tomcat/webapps/<app>/WEB-INF/classes
</code>```

but it is throwing error, and from the error it looks like it is considering the second location/jar from --classfiles option as an exec file.

```<code>[INFO] Loading execution data file /local/jacoco.exec.
[INFO] Loading execution data file /tomcat/webapps/<app>/WEB-INF/classes.
Exception in thread "main" java.io.FileNotFoundException: /tomcat/webapps/<app>/WEB-INF/classes (Is a directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:71)
at org.jacoco.cli.internal.commands.Report.loadExecutionData(Report.java:98)
at org.jacoco.cli.internal.commands.Report.execute(Report.java:82)
at org.jacoco.cli.internal.Main.execute(Main.java:89)
at org.jacoco.cli.internal.Main.main(Main.java:104)
</code>```

I have tried moving classes before the jar file, the exception is different

```<code>[INFO] Loading execution data file /local/jacoco.exec.
[INFO] Loading execution data file /tomcat/webapps/<app>/WEB-INF/lib/new.jar.
Exception in thread "main" java.io.IOException: Invalid execution data file.
at org.jacoco.cli.internal.core.data.ExecutionDataReader.read(ExecutionDataReader.java:89)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:59)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:73)
at org.jacoco.cli.internal.commands.Report.loadExecutionData(Report.java:98)
at org.jacoco.cli.internal.commands.Report.execute(Report.java:82)
at org.jacoco.cli.internal.Main.execute(Main.java:89)
at org.jacoco.cli.internal.Main.main(Main.java:104)
</code>```

for

```<code>java -jar jacococli.jar classinfo /tomcat/webapps/<app>/WEB-INF/lib/new.jar /tomcat/webapps/<app>/WEB-INF/classes /tomcat/webapps/<app>/WEB-INF/lib/new1.jar
</code>```

multiple files work fine all classes in the classes folder and set of jar files in lib folder are listed,

Documentation at http://www.jacoco.org/jacoco/trunk/doc/cli.html states that --classfiles for report can have multiple files but does not state example or delimiter. I tried with comma, semicolon but it does not work ' '[space] works with classinfo so I am assuming it should work with report also.

Googling also did not result in any examples for jacococli.jar.

答:
Documentation at http://www.jacoco.org/jacoco/trunk/doc/cli.html states that --classfiles for report can have multiple files

This is wrong - documentation at http://www.jacoco.org/jacoco/trunk/doc/cli.html actually states that

Some parameters can be specified multiple times to provide multiple values.

And

```<code>--classfiles <path>
</code>```

can be specified multiple times literally, i.e.

```<code>--classfiles path1 --classfiles path2
</code>```

When you omit prefix --classfiles, then it is interpreted as

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

giving exceptions

```<code>Exception in thread "main" java.io.FileNotFoundException: /tomcat/webapps/<app>/WEB-INF/classes (Is a directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:71)
</code>```

and

```<code>Exception in thread "main" java.io.IOException: Invalid execution data file.
at org.jacoco.cli.internal.core.data.ExecutionDataReader.read(ExecutionDataReader.java:89)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:59)
</code>```

as expected - as in one case it is not a file and in another case it is not valid exec file.

' '[space] works with classinfo so I am assuming it should work with report also

report and classinfo are two different commands and have different arguments with all the consequences. Space works with classinfo command, because it allows multiple specifications of

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

note absence of need to specify prefix in comparison to report command.

Body:
As in most cases my class files are at 2 locations inside tomcat at, lib and classes. Now once .exec file is created I need to pull a report referencing both the locations classes and a few jars in lib, for this I am using the below command

java -jar jacococli.jar report /local/jacoco.exec --html /jacocoReport/html --name MergeCode --classfiles /tomcat/webapps/<app>/WEB-INF/lib/new.jar /tomcat/webapps/<app>/WEB-INF/classes

but it is throwing error, and from the error it looks like it is considering the second location/jar from --classfiles option as an exec file.

[INFO] Loading execution data file /local/jacoco.exec.
[INFO] Loading execution data file /tomcat/webapps/<app>/WEB-INF/classes.
Exception in thread "main" java.io.FileNotFoundException: /tomcat/webapps/<app>/WEB-INF/classes (Is a directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:71)
at org.jacoco.cli.internal.commands.Report.loadExecutionData(Report.java:98)
at org.jacoco.cli.internal.commands.Report.execute(Report.java:82)
at org.jacoco.cli.internal.Main.execute(Main.java:89)
at org.jacoco.cli.internal.Main.main(Main.java:104)

I have tried moving classes before the jar file, the exception is different

[INFO] Loading execution data file /local/jacoco.exec.
[INFO] Loading execution data file /tomcat/webapps/<app>/WEB-INF/lib/new.jar.
Exception in thread "main" java.io.IOException: Invalid execution data file.
at org.jacoco.cli.internal.core.data.ExecutionDataReader.read(ExecutionDataReader.java:89)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:59)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:73)
at org.jacoco.cli.internal.commands.Report.loadExecutionData(Report.java:98)
at org.jacoco.cli.internal.commands.Report.execute(Report.java:82)
at org.jacoco.cli.internal.Main.execute(Main.java:89)
at org.jacoco.cli.internal.Main.main(Main.java:104)

for

java -jar jacococli.jar classinfo /tomcat/webapps/<app>/WEB-INF/lib/new.jar /tomcat/webapps/<app>/WEB-INF/classes /tomcat/webapps/<app>/WEB-INF/lib/new1.jar

multiple files work fine all classes in the classes folder and set of jar files in lib folder are listed,

Documentation at http://www.jacoco.org/jacoco/trunk/doc/cli.html states that --classfiles for report can have multiple files but does not state example or delimiter. I tried with comma, semicolon but it does not work ' '[space] works with classinfo so I am assuming it should work with report also.

Googling also did not result in any examples for jacococli.jar.

Body:
Documentation at http://www.jacoco.org/jacoco/trunk/doc/cli.html states that --classfiles for report can have multiple files

This is wrong - documentation at http://www.jacoco.org/jacoco/trunk/doc/cli.html actually states that

Some parameters can be specified multiple times to provide multiple values.

And

--classfiles <path>

can be specified multiple times literally, i.e.

--classfiles path1 --classfiles path2

When you omit prefix --classfiles, then it is interpreted as

<execfiles>

giving exceptions

Exception in thread "main" java.io.FileNotFoundException: /tomcat/webapps/<app>/WEB-INF/classes (Is a directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:71)

and

Exception in thread "main" java.io.IOException: Invalid execution data file.
at org.jacoco.cli.internal.core.data.ExecutionDataReader.read(ExecutionDataReader.java:89)
at org.jacoco.cli.internal.core.tools.ExecFileLoader.load(ExecFileLoader.java:59)

as expected - as in one case it is not a file and in another case it is not valid exec file.

' '[space] works with classinfo so I am assuming it should work with report also

report and classinfo are two different commands and have different arguments with all the consequences. Space works with classinfo command, because it allows multiple specifications of

<classlocations>

note absence of need to specify prefix in comparison to report command.


问:
Leaflet put grid layer above GeJson LayerGroup
After upgrade leaflet 0.7 to 1, I get multiple errors. Until I finished the migration I have an error that I can't solve: I have two GeoJson objects inside a LayerGroup that draws the map.

And a GridLayer that get geolocated points from a backend.

The problem is that the GridLayer is always under the LayerGroup, instead of be above. I tried lots of things and I don't realize how to do that...:

```<code>// Using geojson implies drawing vectors and that pane is usually
// over the tile pane with the canvas.
this._map.getPanes()['tilePane'].style.zIndex = 5;
var colorsPromise = $.getJSON('colors.json');
var fitoPromise = $.getJSON('fitoepisodis.json');
var furniturePromise = $.getJSON('baranes.json');
$.when(colorsPromise, fitoPromise, furniturePromise)
 .then(function(colorsResponse, fitoepisodisResponse, furnitureResponse) {

   self._geoJsonGroup = new L.LayerGroup();

    self._fitoColors = colorsResponse[0];
    L.geoJson(fitoepisodisResponse[0], {
        minZoom : MapCtrl._INITIAL_ZOOM,
        maxZoom : 24,
        touchZoom : true,
        attributionControl : false,
        style: function (feature) {
            var color = self._fitoColors[feature.properties.ID];
            var style = {
                   "clickable": false,
                   "color": color ? color.stroke : 'darkgray',
                   "fillColor": color ? color.fill : 'lightgray',
                   "weight": 3.0,
                   "opacity": 0.8,
                   "fillOpacity": 0.8
               };
               return style;
        }
    }).addTo(self._geoJsonGroup);
    L.geoJson(furnitureResponse[0], {
        minZoom : MapCtrl._INITIAL_ZOOM,
        maxZoom : 24,
        touchZoom : true,
        attributionControl : false,
        style: function (feature) {
            var style = {
                   "clickable": false,
                   "color": 'darkgray',
                   "weight": 3.5,
                   "opacity": 0.7
               };
               return style;
        }
    }).addTo(self._map);

    self._geoJsonGroup.addTo(self._map);
});

// Canvas layer where to draw feature points on zoom
self._canvasLayer = new L.GridLayer({
    minZoom : MapCtrl._INITIAL_ZOOM,
    maxZoom : 22,
    async   : true,
    zIndex  : 900,
    updateWhenZooming : false
});
self._canvasLayer.createTile = function(coords) {
  // create a <canvas> element for drawing
  var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  // setup tile width and height according to the options
  var size = this.getTileSize();
  tile.width = size.x;
  tile.height = size.y;

  setTimeout(function() {
    self._drawTiles(tile, coords, coords.z);
    self._canvasLayer.setZIndex(999999);
    self._canvasLayer.bringToFront();
    self._geoJsonGroup.setZIndex(200);
    }, 1000);

  // return the tile so it can be rendered on screen
  return  tile
};
self._canvasLayer.addTo(self._map );
</code>```

Here is how is shown: the green polygon and lines are the GeoJson, the circles are in the GridLayer.

答:
I found the solution working with panes, the code became: </p>

```<code>    // Use this pane to put the GridLayer (html canvas element) of feature points above of GeoJson elements
    this._map.createPane('pointsFeatures');
    this._map.getPane('pointsFeatures').style.zIndex = 650;
    this._map.getPane('pointsFeatures').style.pointerEvents = 'none';
    // Canvas layer where to draw feature points on zoom
    self._canvasLayer = new L.GridLayer({
        minZoom : MapCtrl._INITIAL_ZOOM,
        maxZoom : 22,
        async   : true,
        updateWhenZooming : false,
        pane: 'pointsFeatures'
    });
</code>```

Body:
After upgrade leaflet 0.7 to 1, I get multiple errors. Until I finished the migration I have an error that I can't solve: I have two GeoJson objects inside a LayerGroup that draws the map.

And a GridLayer that get geolocated points from a backend.

The problem is that the GridLayer is always under the LayerGroup, instead of be above. I tried lots of things and I don't realize how to do that...:

// Using geojson implies drawing vectors and that pane is usually
// over the tile pane with the canvas.
this._map.getPanes()['tilePane'].style.zIndex = 5;
var colorsPromise = $.getJSON('colors.json');
var fitoPromise = $.getJSON('fitoepisodis.json');
var furniturePromise = $.getJSON('baranes.json');
$.when(colorsPromise, fitoPromise, furniturePromise)
 .then(function(colorsResponse, fitoepisodisResponse, furnitureResponse) {

   self._geoJsonGroup = new L.LayerGroup();

    self._fitoColors = colorsResponse[0];
    L.geoJson(fitoepisodisResponse[0], {
        minZoom : MapCtrl._INITIAL_ZOOM,
        maxZoom : 24,
        touchZoom : true,
        attributionControl : false,
        style: function (feature) {
            var color = self._fitoColors[feature.properties.ID];
            var style = {
                   "clickable": false,
                   "color": color ? color.stroke : 'darkgray',
                   "fillColor": color ? color.fill : 'lightgray',
                   "weight": 3.0,
                   "opacity": 0.8,
                   "fillOpacity": 0.8
               };
               return style;
        }
    }).addTo(self._geoJsonGroup);
    L.geoJson(furnitureResponse[0], {
        minZoom : MapCtrl._INITIAL_ZOOM,
        maxZoom : 24,
        touchZoom : true,
        attributionControl : false,
        style: function (feature) {
            var style = {
                   "clickable": false,
                   "color": 'darkgray',
                   "weight": 3.5,
                   "opacity": 0.7
               };
               return style;
        }
    }).addTo(self._map);

    self._geoJsonGroup.addTo(self._map);
});

// Canvas layer where to draw feature points on zoom
self._canvasLayer = new L.GridLayer({
    minZoom : MapCtrl._INITIAL_ZOOM,
    maxZoom : 22,
    async   : true,
    zIndex  : 900,
    updateWhenZooming : false
});
self._canvasLayer.createTile = function(coords) {
  // create a <canvas> element for drawing
  var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  // setup tile width and height according to the options
  var size = this.getTileSize();
  tile.width = size.x;
  tile.height = size.y;

  setTimeout(function() {
    self._drawTiles(tile, coords, coords.z);
    self._canvasLayer.setZIndex(999999);
    self._canvasLayer.bringToFront();
    self._geoJsonGroup.setZIndex(200);
    }, 1000);

  // return the tile so it can be rendered on screen
  return  tile
};
self._canvasLayer.addTo(self._map );

Here is how is shown: the green polygon and lines are the GeoJson, the circles are in the GridLayer.

Body:
I found the solution working with panes, the code became:

    // Use this pane to put the GridLayer (html canvas element) of feature points above of GeoJson elements
    this._map.createPane('pointsFeatures');
    this._map.getPane('pointsFeatures').style.zIndex = 650;
    this._map.getPane('pointsFeatures').style.pointerEvents = 'none';
    // Canvas layer where to draw feature points on zoom
    self._canvasLayer = new L.GridLayer({
        minZoom : MapCtrl._INITIAL_ZOOM,
        maxZoom : 22,
        async   : true,
        updateWhenZooming : false,
        pane: 'pointsFeatures'
    });


问:
How to use update source trigger on Wpf Combobox which is editable?
I have a combo box (in my wpf-mvvm app). I have set IsEditable = true. But the "property changed  event" is getting fired when I start typing.

How can I set UpdateSourceTrigger = Propertychanged here ?

Also..I need to call a validation function if user has entered new value ( i mean other than those available in list ..using edit functionality).

Any help will be appreciated.

```<code>    <ComboBox ItemsSource="{Binding Path = PlanTypeBasedContractNumberList }" Width="90" IsEditable="True"
SelectedValue="{Binding GeneralCharacteristicsDataContext.ContractNumber.Value}">
                            </ComboBox>
</code>```

答:
In an editable ComboBox, the SelectedItem and SelectedValue properties refer to the Popup items, not the editable item.  Once you start typing, the SelectedItem becomes "unselected" and that's why the event fires.

To bind to the value of the TextBox of the ComboBox, use the Text property:

```<code><ComboBox IsEditable="True" Text="{Binding Path=..., UpdateSourceTrigger=...}">
</code>```

Body:
I have a combo box (in my wpf-mvvm app). I have set IsEditable = true. But the "property changed  event" is getting fired when I start typing.

How can I set UpdateSourceTrigger = Propertychanged here ?

Also..I need to call a validation function if user has entered new value ( i mean other than those available in list ..using edit functionality).

Any help will be appreciated.

    <ComboBox ItemsSource="{Binding Path = PlanTypeBasedContractNumberList }" Width="90" IsEditable="True"
SelectedValue="{Binding GeneralCharacteristicsDataContext.ContractNumber.Value}">
                            </ComboBox>

Body:
In an editable ComboBox, the SelectedItem and SelectedValue properties refer to the Popup items, not the editable item.  Once you start typing, the SelectedItem becomes "unselected" and that's why the event fires.

To bind to the value of the TextBox of the ComboBox, use the Text property:

<ComboBox IsEditable="True" Text="{Binding Path=..., UpdateSourceTrigger=...}">


问:
Pass click event to nested component - React | Material-UI
Im having an issue. When you click listItem (whole separated li element) I want to call the onChange function on the checkbox component inside listItem.

I could easily move that function from checkbox to parent but I will loose the checked prop.

Checking the checkbox itself doesnt work, but just open the console to see the results. I want handleToggle function to fire properly when whole element is clicked (not only checkbox)

```<code>  <List>
    {['first', 'second', 'third'].map((name, i) => (
      <ListItem key={i} dense button>
        <ListItemText primary={name} />
        <Checkbox
          disableRipple
          checked={false}
          onChange={(evt, checked) => this.handleToggle(evt, checked, name)}
        />
      </ListItem>
    ))}
  </List>
</code>```

Code SandBox

Edit

I don't want to use state in this component at all. Summarizing - how to pass event from ListItem (parent) to it's children (Checkbox)?

Final edit: I've found out the way how to deal with it. No state needed. Just two simple lines of code.

Since checkbox state is fully controlled by redux, I just moved the onClick func to the ListItem element with one line on code in it's body:

...dispatch(toggle(!this.props.elements[nameOfElement], name));

Anyways thanks to everyone for help. Upvoted every answer.

答:
Since you are planning to use Redux, I would suggest a simplest implementation of your case in terms of React Redux.

Reducer

```<code>const inititalState = {
  list: [ // keep all your data in redux store
    { id: 1, name: 'first', checked: false },
    { id: 2, name: 'second', checked: false },
    { id: 3, name: 'third', checked: false }
  ]
};

export function list(state = inititalState, action) {
  switch (action.type) {
    case 'CHANGE': // changing the list of items (checked property)
      return {
        ...state,
        list: state.list.map(i =>
          i.id === action.item.id ? { ...action.item, checked: action.value } : i
        )
      };
    default:
      return state
  }
}
</code>```

Action

```<code>// just the only action to change 'checked' property of a given item in the list
export function change(item, value) {
  return { type: 'CHANGE', item, value };
}
</code>```

At last, the Component connected with redux store:

```<code>class App extends React.Component {
  handleToggle = (item) => {
    // dispatching the "change" redux-action
    this.props.dispatch(change(item, !item.checked)); // here's the toggling logic (!)
  }

  render() {
    return (
      <List>
        {this.props.list.map((item, i) => ( // map the list from the redux store
          <ListItem key={item.id} dense button // (i)ndex for the key value would be ok too
            onClick={() => this.handleToggle(item)}> // to call the redux-action by click
            <ListItemText primary={item.name} />
            <Checkbox
              disableRipple
              checked={item.checked} // this is the main binding
            />                       // with no need of onChange handling
          </ListItem>
        ))}
      </List>
    )
  }
};

// pass the list from the redux-store to the component
function mapStateToProps(state, ownProps) {
  return { list: state.list };
}

const _App = connect(mapStateToProps)(App); // connect the component to the redux store
</code>```

This is very basic implementation, I'd recommend to follow best practices, move App component out of index.js, the state logic (!item.checked) could be placed in the action creator or reducer etc... Also, I created a working demo based on your codesandbox: https://codesandbox.io/s/xpk099y40w.

Body:
Im having an issue. When you click listItem (whole separated li element) I want to call the onChange function on the checkbox component inside listItem.

I could easily move that function from checkbox to parent but I will loose the checked prop.

Checking the checkbox itself doesnt work, but just open the console to see the results. I want handleToggle function to fire properly when whole element is clicked (not only checkbox)

  <List>
    {['first', 'second', 'third'].map((name, i) => (
      <ListItem key={i} dense button>
        <ListItemText primary={name} />
        <Checkbox
          disableRipple
          checked={false}
          onChange={(evt, checked) => this.handleToggle(evt, checked, name)}
        />
      </ListItem>
    ))}
  </List>

Code SandBox

Edit

I don't want to use state in this component at all. Summarizing - how to pass event from ListItem (parent) to it's children (Checkbox)?

Final edit: I've found out the way how to deal with it. No state needed. Just two simple lines of code.

Since checkbox state is fully controlled by redux, I just moved the onClick func to the ListItem element with one line on code in it's body:

...dispatch(toggle(!this.props.elements[nameOfElement], name));

Anyways thanks to everyone for help. Upvoted every answer.

Body:
Since you are planning to use Redux, I would suggest a simplest implementation of your case in terms of React Redux.

Reducer

const inititalState = {
  list: [ // keep all your data in redux store
    { id: 1, name: 'first', checked: false },
    { id: 2, name: 'second', checked: false },
    { id: 3, name: 'third', checked: false }
  ]
};

export function list(state = inititalState, action) {
  switch (action.type) {
    case 'CHANGE': // changing the list of items (checked property)
      return {
        ...state,
        list: state.list.map(i =>
          i.id === action.item.id ? { ...action.item, checked: action.value } : i
        )
      };
    default:
      return state
  }
}

Action

// just the only action to change 'checked' property of a given item in the list
export function change(item, value) {
  return { type: 'CHANGE', item, value };
}

At last, the Component connected with redux store:

class App extends React.Component {
  handleToggle = (item) => {
    // dispatching the "change" redux-action
    this.props.dispatch(change(item, !item.checked)); // here's the toggling logic (!)
  }

  render() {
    return (
      <List>
        {this.props.list.map((item, i) => ( // map the list from the redux store
          <ListItem key={item.id} dense button // (i)ndex for the key value would be ok too
            onClick={() => this.handleToggle(item)}> // to call the redux-action by click
            <ListItemText primary={item.name} />
            <Checkbox
              disableRipple
              checked={item.checked} // this is the main binding
            />                       // with no need of onChange handling
          </ListItem>
        ))}
      </List>
    )
  }
};

// pass the list from the redux-store to the component
function mapStateToProps(state, ownProps) {
  return { list: state.list };
}

const _App = connect(mapStateToProps)(App); // connect the component to the redux store

This is very basic implementation, I'd recommend to follow best practices, move App component out of index.js, the state logic (!item.checked) could be placed in the action creator or reducer etc... Also, I created a working demo based on your codesandbox: https://codesandbox.io/s/xpk099y40w.


问:
How can a package hierarchy contain another package class
I am not sure about the java.lang Hierarchy. How can it contain java.security.Permission class? Follow the link and search for java.security.Permission.

答:
It doesn't contain that class. It's there just to show that java.lang.RuntimePermission is derived from java.security.BasicPermission, which is derived from java.security.Permission.

The class contained in the java.lang package is java.lang.RuntimePermission, but that webpage shows you the full class hierarchy, even if those class are not contained in the java.lang package.


问:
Nested router infinite loop Angular

I'm trying to do a simple page with a header, a menu and a content div
When someone click on a ancor of the menu, I want the content div to be populated with the page corresponding to the route associated.
And, for now, I'd just want for this commun page (header, menu and content) to match any routes.

The appComponent is just here to route to other components :

app-component.html

```<code><router-outlet></router-outlet>
</code>```

The component containing the header, menu and content is called LayoutComponent :

layout-component.html

```<code><div>
    <app-menu></app-menu>
    <router-outlet></router-outlet>
</div>
</code>```

and my routing configuration is as follow :

```<code>export const routes: Routes = [
  {
    path: 'login',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: 'common',
    loadChildren: 'app/dsia-common/dsia-common.module'
  },
  {
   path: 'home',
   redirectTo: '',
   pathMatch: 'full'
  },
  {
   path: '',
   component: LayoutComponent,
   children: [
  {
    path: '**',
    pathMatch: 'full',
    canActivate: [AuthGuardService],
    component: GenericPageComponent
  }
]
</code>```

When browsing on my site, on localhost:4200/,

I'm expecting a login page to popup up (the AuthGuardService is redirecting me to the login route).
And after a successful login, the login component is redirecting to the home page.
And the home page should use the LayoutComponent to display the header, the menu and the content in the nested router-outlet.
And it should do so for every url.
So to sum up

/ -> (trigger) canActivate[AuthGuardService] --> (redirect to) /login --> (on success redirect to) /home --> (redirect to) / --> LayoutComponent

Unfortunaley my page isn't loading as the login page get called recursively (a navigation cancel event is always called). And I think this is due to the fact that the AuthGuardService is used when the /login path is called (so the login route get cancelled and it's redirected to the login route, and so on...). Which should be the case as per my understanding.

Can someone point me to what I'm obviously missing here ?

Thanks you very much.

Regards.
Benjamin

答:
You redirect login to login. It is normal that there is an infinite loop. Try changing your routing configuration. Here is a sample.</p>

```<code>export const routes: Routes = [
{
  path: '',
  redirectTo: 'login',
  pathMatch: 'full'
},
{
  path: 'login',
  component: LoginComponent,
}
]
</code>```

Title: Nested router infinite loop Angular

Body:
I'm trying to do a simple page with a header, a menu and a content div
When someone click on a ancor of the menu, I want the content div to be populated with the page corresponding to the route associated.
And, for now, I'd just want for this commun page (header, menu and content) to match any routes.

The appComponent is just here to route to other components :

app-component.html

<router-outlet></router-outlet>

The component containing the header, menu and content is called LayoutComponent :

layout-component.html

    <app-menu></app-menu>
    <router-outlet></router-outlet>

and my routing configuration is as follow :

export const routes: Routes = [
  {
    path: 'login',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: 'common',
    loadChildren: 'app/dsia-common/dsia-common.module'
  },
  {
   path: 'home',
   redirectTo: '',
   pathMatch: 'full'
  },
  {
   path: '',
   component: LayoutComponent,
   children: [
  {
    path: '**',
    pathMatch: 'full',
    canActivate: [AuthGuardService],
    component: GenericPageComponent
  }
]

When browsing on my site, on localhost:4200/,

I'm expecting a login page to popup up (the AuthGuardService is redirecting me to the login route).
And after a successful login, the login component is redirecting to the home page.
And the home page should use the LayoutComponent to display the header, the menu and the content in the nested router-outlet.
And it should do so for every url.
So to sum up

/ -> (trigger) canActivate[AuthGuardService] --> (redirect to) /login --> (on success redirect to) /home --> (redirect to) / --> LayoutComponent

Unfortunaley my page isn't loading as the login page get called recursively (a navigation cancel event is always called). And I think this is due to the fact that the AuthGuardService is used when the /login path is called (so the login route get cancelled and it's redirected to the login route, and so on...). Which should be the case as per my understanding.

Can someone point me to what I'm obviously missing here ?

Thanks you very much.

Regards.
Benjamin

Body:
You redirect login to login. It is normal that there is an infinite loop. Try changing your routing configuration. Here is a sample.

export const routes: Routes = [
{
  path: '',
  redirectTo: 'login',
  pathMatch: 'full'
},
{
  path: 'login',
  component: LoginComponent,
}
]


问:
jQuery deferreds and promises - .then() vs .done()
I've been reading about jQuery deferreds and promises and I can't see the difference between using .then() & .done() for successful callbacks. I know Eric Hynds mentions that .done() and .success() map to the same functionality but I'm guessing so does .then() as all the callbacks are all invoked on a completion of a successful operation.

Can anyone please enlighten me to the correct usage?

答:
There is a very simple mental mapping in response that was a bit hard to find in the other answers:

done implements tap as in bluebird Promises

then implements then as in ES6 Promises

ContentLicense: CC BY-SA 4.0


问:
why remove "\n","\r","\t" in phalcon？
I found that in the muilti-module which is created by phalcon-tool has these code:

```<code>$application = new Application($di);
echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());
</code>```

Why remove "\n","\r","\t"?

答:
As Spangen pointed out, these are the escape sequences for some special 'whitespace' characters.

This link here has more information on them: http://us3.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Now, an important note: for them to work as intended in PHP, you need to enclose them in double quotes, like: "\t", "\n". Single quotes won't produce the intended effects of these escape sequences: '\t', '\n'.

To illustrate this more, you can run this code and see the results. Running it from console like php myfile.php might cause some visual glitches, and running it in the browser will need that you view the 'source code'.

```<code>echo "Let's test... ";
echo "Because no new line characters were added, this sentence will be printed in the same line as the previous phrase.";
echo "\n";
echo "But now a new line was added, by typing \\n enclosed in double quotes.";
echo "\n";
echo "Now, let's add a tab, between the next two words: hello \t there.";
echo "\n";
echo "Now, let's add a carriage return, which will 'force' the 'cursor' in this string to move to the beginning, thus 'splitting' this string into two. Adding it now: \r There, I just added it before this last sentence.";
echo "\n";
echo 'Finally, these special characters will not work as intended if we just enclose the string with single quotes, as done in this string: \n \t \r';
</code>```

This link here has more information on the difference between new lines and carriage returns: https://stackoverflow.com/a/12747850/466395

So yeah, in the original code that you posted, the person removed those special characters using str_replace(), because they tend to produce 'visual glitches' (unintented malformed output) in console.

Title: why remove "\n","\r","\t" in phalcon？

Body:
I found that in the muilti-module which is created by phalcon-tool has these code:

$application = new Application($di);
echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());

Why remove "\n","\r","\t"?

Body:
As Spangen pointed out, these are the escape sequences for some special 'whitespace' characters.

This link here has more information on them: http://us3.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Now, an important note: for them to work as intended in PHP, you need to enclose them in double quotes, like: "\t", "\n". Single quotes won't produce the intended effects of these escape sequences: '\t', '\n'.

To illustrate this more, you can run this code and see the results. Running it from console like php myfile.php might cause some visual glitches, and running it in the browser will need that you view the 'source code'.

echo "Let's test... ";
echo "Because no new line characters were added, this sentence will be printed in the same line as the previous phrase.";
echo "\n";
echo "But now a new line was added, by typing \\n enclosed in double quotes.";
echo "\n";
echo "Now, let's add a tab, between the next two words: hello \t there.";
echo "\n";
echo "Now, let's add a carriage return, which will 'force' the 'cursor' in this string to move to the beginning, thus 'splitting' this string into two. Adding it now: \r There, I just added it before this last sentence.";
echo "\n";
echo 'Finally, these special characters will not work as intended if we just enclose the string with single quotes, as done in this string: \n \t \r';

This link here has more information on the difference between new lines and carriage returns: https://stackoverflow.com/a/12747850/466395

So yeah, in the original code that you posted, the person removed those special characters using str_replace(), because they tend to produce 'visual glitches' (unintented malformed output) in console.


问:
PHP File Real Mime
I have done functions to upload files to DB. User (uploader) can upload pdf png or jpeg files. All others are not allowed. But there is way to 'hack' it. User can have a file (for example PHP file) on own computer. He will rename the file to 'test.jpg' from 'test.php'. Then he will upload renamed file as jpg and when the program will check file, it will upload it because it will return, that it is jpg (image/jpeg). Is there a way to check if file is realy jpeg/png/...?

E: I don't want to upload only images. File to upload generaly can be in another format, so I can not use function imagesize().

答:
For PHP < 5.3 use mime_content_type()

For PHP > 5.3 use finfo_fopen()

Maybe this answer will help you. click here

Title: PHP File Real Mime


问:
Insert multiple rows for each of a result set?
my google-fu is failing me.
I'm trying to do the following in a more automatic way:

1) select a set of fields from 1 table

```<code>select ACCT_ID from MASTER_ACCT where CUST_NBR like '%ABC';
</code>```

2) use the results of that in a multiple row insert

```<code>// for each ACCT_ID in (1)
insert into TOGGLES (FIELD1, FIELD2, FIELD3)
values('abc', '123', ACCT_ID[i]);
</code>```

Is there a way to execute the 2nd statement for ACCT_ID[i] in each of the ACCT_ID results from the 1st statement?

答:
You would use an INSERT INTO...SELECT statement:

```<code>INSERT INTO toggles (field1, field2, field3)
SELECT 'abc', '123', acct_id
FROM master_acct
WHERE cust_nbr LIKE '%ABC';
</code>```

Body:
my google-fu is failing me.
I'm trying to do the following in a more automatic way:

1) select a set of fields from 1 table

select ACCT_ID from MASTER_ACCT where CUST_NBR like '%ABC';

2) use the results of that in a multiple row insert

// for each ACCT_ID in (1)
insert into TOGGLES (FIELD1, FIELD2, FIELD3)
values('abc', '123', ACCT_ID[i]);

Is there a way to execute the 2nd statement for ACCT_ID[i] in each of the ACCT_ID results from the 1st statement?

Body:
You would use an INSERT INTO...SELECT statement:

INSERT INTO toggles (field1, field2, field3)
SELECT 'abc', '123', acct_id
FROM master_acct
WHERE cust_nbr LIKE '%ABC';


问:
Handling multiple connection strings in ONE DataAccess Layer
I have an interesting dilemma. I currently have a DataAccess layer that has to work with multiple Domains and each one of those domains has multiple Database repositories depending on the stored procedure called. AS of right now I simply use a SWITCH statement to determine the Machine the application is running on and return the appropriate connection string from the Web.config. Now I have the daunting task of dealing with multiple database repositories in the same SQL server and id like to dynamically determine the connection string based on the stored procedure called. Maybe I'm over thinking this, but I just cannot wrap my head around how I'm going to deal with this.</p>

答:
Assuming that your DAL is only one Assembly that is trying to manipulate data for several different databases. I would suggest, splitting up the code into separate assemblies for each database.  Then you can have specific configuration information for each assembly, and the code will just look at the specific configuration information for the executing assembly.

For example, assuming you have a Movies database, and a Books database. You would create a library that knows how to manipulate data in your Movies Database and all of the code and stored procedures necessary for creating,editing, and querying movies would be in that library. This library would have it's own configuration information including the connection string to the database.

Similarly for interacting with your books database you would have a separate library that contains all the stored procedures for creating,editing, and querying information about your books. Again this would have it's own configuration information including the connection string.

This approach will allow for flexibility for adding more data sources, and configuring them independently of each other.

If you so desired you could of course have another library that would deal with transactions that might require access to both databases and would reference the code in the libraries previously mentioned.


问:
Why is there no transform_if in the C++ standard library?
A use case emerged when wanting to do a contitional copy (1. doable with copy_if) but from a container of values to a container of pointers to those values (2. doable with transform).

With the available tools I can't do it in less than two steps :

```<code>#include <vector>
#include <algorithm>

using namespace std;

struct ha {
    int i;
    explicit ha(int a) : i(a) {}
};

int main()
{
    vector<ha> v{ ha{1}, ha{7}, ha{1} }; // initial vector
    // GOAL : make a vector of pointers to elements with i < 2
    vector<ha*> ph; // target vector
    vector<ha*> pv; // temporary vector
    // 1.
    transform(v.begin(), v.end(), back_inserter(pv),
        [](ha &arg) { return &arg; });
    // 2.
    copy_if(pv.begin(), pv.end(), back_inserter(ph),
        [](ha *parg) { return parg->i < 2;  }); // 2.

    return 0;
}
</code>```

Ofcourse we could call remove_if on pv and eliminate the need for a temporary, better yet though, it's not difficult to implement (for unary operations) something like this :

```<code>template <
    class InputIterator, class OutputIterator,
    class UnaryOperator, class Pred
>
OutputIterator transform_if(InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperator op, Pred pred)
{
    while (first1 != last1)
    {
        if (pred(*first1)) {
            *result = op(*first1);
            ++result;
        }
        ++first1;
    }
    return result;
}

// example call
transform_if(v.begin(), v.end(), back_inserter(ph),
[](ha &arg) { return &arg;      }, // 1.
[](ha &arg) { return arg.i < 2; });// 2.
</code>```

Is there a more elegant workaround with the available C++ standard library tools ?

Is there a reason why transform_if does not exist in the library? Is the combination of the existing tools a sufficient workaround and/or considered performance wise well behaved ?

答:
You may use copy_if along. Why not? Define OutputIt (see copy):

```<code>struct my_inserter: back_insert_iterator<vector<ha *>>
{
  my_inserter(vector<ha *> &dst)
    : back_insert_iterator<vector<ha *>>(back_inserter<vector<ha *>>(dst))
  {
  }
  my_inserter &operator *()
  {
    return *this;
  }
  my_inserter &operator =(ha &arg)
  {
    *static_cast< back_insert_iterator<vector<ha *>> &>(*this) = &arg;
    return *this;
  }
};
</code>```

and rewrite your code:

```<code>int main()
{
    vector<ha> v{ ha{1}, ha{7}, ha{1} }; // initial vector
    // GOAL : make a vector of pointers to elements with i < 2
    vector<ha*> ph; // target vector

    my_inserter yes(ph);
    copy_if(v.begin(), v.end(), yes,
        [](const ha &parg) { return parg.i < 2;  });

    return 0;
}
</code>```

Body:
A use case emerged when wanting to do a contitional copy (1. doable with copy_if) but from a container of values to a container of pointers to those values (2. doable with transform).

With the available tools I can't do it in less than two steps :

#include <vector>
#include <algorithm>

using namespace std;

struct ha {
    int i;
    explicit ha(int a) : i(a) {}
};

int main()
{
    vector<ha> v{ ha{1}, ha{7}, ha{1} }; // initial vector
    // GOAL : make a vector of pointers to elements with i < 2
    vector<ha*> ph; // target vector
    vector<ha*> pv; // temporary vector
    // 1.
    transform(v.begin(), v.end(), back_inserter(pv),
        [](ha &arg) { return &arg; });
    // 2.
    copy_if(pv.begin(), pv.end(), back_inserter(ph),
        [](ha *parg) { return parg->i < 2;  }); // 2.

    return 0;
}

Ofcourse we could call remove_if on pv and eliminate the need for a temporary, better yet though, it's not difficult to implement (for unary operations) something like this :

template <
    class InputIterator, class OutputIterator,
    class UnaryOperator, class Pred
>
OutputIterator transform_if(InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperator op, Pred pred)
{
    while (first1 != last1)
    {
        if (pred(*first1)) {
            *result = op(*first1);
            ++result;
        }
        ++first1;
    }
    return result;
}

// example call
transform_if(v.begin(), v.end(), back_inserter(ph),
[](ha &arg) { return &arg;      }, // 1.
[](ha &arg) { return arg.i < 2; });// 2.

Is there a more elegant workaround with the available C++ standard library tools ?

Is there a reason why transform_if does not exist in the library? Is the combination of the existing tools a sufficient workaround and/or considered performance wise well behaved ?

Body:
You may use copy_if along. Why not? Define OutputIt (see copy):

struct my_inserter: back_insert_iterator<vector<ha *>>
{
  my_inserter(vector<ha *> &dst)
    : back_insert_iterator<vector<ha *>>(back_inserter<vector<ha *>>(dst))
  {
  }
  my_inserter &operator *()
  {
    return *this;
  }
  my_inserter &operator =(ha &arg)
  {
    *static_cast< back_insert_iterator<vector<ha *>> &>(*this) = &arg;
    return *this;
  }
};

and rewrite your code:

int main()
{
    vector<ha> v{ ha{1}, ha{7}, ha{1} }; // initial vector
    // GOAL : make a vector of pointers to elements with i < 2
    vector<ha*> ph; // target vector

    my_inserter yes(ph);
    copy_if(v.begin(), v.end(), yes,
        [](const ha &parg) { return parg.i < 2;  });

    return 0;
}


问:
iTextSharp: Header on only First Page
I am using iTextSharp for a project in ASP.NET.
I have generated what I want so far.

The Issue
1. I want the HEADER to be displayed ONLY on First Page of my PDF. But, the Header content appears on every new page generated.

Also, The table being generated has to have 60 rows on first page and about 65 rows on all other pages (since the header will not be there).

Code so Far:

```<code>PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
Phrase phrase = null;
PdfPCell cell = null;
Color color = null;
pdfDoc.Open();

int columns = grdGridPrint.Columns.Count;
// Table and PdfTable classes removed in version 5.XXX
PdfPTable table = new PdfPTable(columns);
// table.TotalWidth = 500f;

// Draw first-page-only header
//ColumnText ct = new ColumnText(writer.DirectContent);
//XMLWorkerHelper.GetInstance().ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(html));
//ct.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-PDFMarginTop), 0, Element.ALIGN_MIDDLE);
//ct.Go();

phrase = new Phrase();

phrase.Add(new Chunk("Elam Fataka\u00AE \n", FontFactory.GetFont("Arial", 15, Font.BOLD, Color.BLACK)));
phrase.Add(new Chunk("Mahakali Complex, Tarsa Road,Kanhan \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("Proprietor : Liladhar Barve, ", FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK)));
phrase.Add(new Chunk("(M) 9326560090 | (O) 07102-236297  \n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("\n\n", FontFactory.GetFont("Arial", 7, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("All Agent List - Total Agent :" + grdGridPrint.Rows.Count.ToString() + "\n", FontFactory.GetFont("Arial", 15, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("Printing Date : " + DateTime.Today.ToString("dd/MM/yyyy") + "\n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("\n\n", FontFactory.GetFont("Arial", 7, Font.NORMAL, Color.BLACK)));

cell = ClsPDF.PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
cell.VerticalAlignment = PdfCell.CHUNK;
</code>```

答:
Just create a paragraph on the first page.

```<code>pdfDoc.Add(new Paragraph("This Is My Header"));
</code>```

Your rows will automatically spill over to the next page as needed.

Title: iTextSharp: Header on only First Page

Body:
I am using iTextSharp for a project in ASP.NET.
I have generated what I want so far.

The Issue
1. I want the HEADER to be displayed ONLY on First Page of my PDF. But, the Header content appears on every new page generated.

Also, The table being generated has to have 60 rows on first page and about 65 rows on all other pages (since the header will not be there).

Code so Far:

PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
Phrase phrase = null;
PdfPCell cell = null;
Color color = null;
pdfDoc.Open();

int columns = grdGridPrint.Columns.Count;
// Table and PdfTable classes removed in version 5.XXX
PdfPTable table = new PdfPTable(columns);
// table.TotalWidth = 500f;

// Draw first-page-only header
//ColumnText ct = new ColumnText(writer.DirectContent);
//XMLWorkerHelper.GetInstance().ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(html));
//ct.SetSimpleColumn(document.Left, document.Top, document.Right, document.GetTop(-PDFMarginTop), 0, Element.ALIGN_MIDDLE);
//ct.Go();

phrase = new Phrase();

phrase.Add(new Chunk("Elam Fataka\u00AE \n", FontFactory.GetFont("Arial", 15, Font.BOLD, Color.BLACK)));
phrase.Add(new Chunk("Mahakali Complex, Tarsa Road,Kanhan \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("Proprietor : Liladhar Barve, ", FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK)));
phrase.Add(new Chunk("(M) 9326560090 | (O) 07102-236297  \n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("\n\n", FontFactory.GetFont("Arial", 7, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("All Agent List - Total Agent :" + grdGridPrint.Rows.Count.ToString() + "\n", FontFactory.GetFont("Arial", 15, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("Printing Date : " + DateTime.Today.ToString("dd/MM/yyyy") + "\n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
phrase.Add(new Chunk("\n\n", FontFactory.GetFont("Arial", 7, Font.NORMAL, Color.BLACK)));

cell = ClsPDF.PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
cell.VerticalAlignment = PdfCell.CHUNK;

Body:
Just create a paragraph on the first page.

pdfDoc.Add(new Paragraph("This Is My Header"));

Your rows will automatically spill over to the next page as needed.


问:
What happen when we do AND operation of 4 byte number with 2 byte number
I am trying to write a piece of code to extract every single byte of data out of a 4 byte integer

after little bit of searching i actually found the code with which this can be achieved , but i am just curious to know why it behaves the way output is created , below is the code

```<code>#include <stdio.h>

int getByte(int x, int n);

void main()
{
    int x = 0xAABBCCDD;
    int n;

    for (n=0; n<=3; n++) {
        printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
    }

}

// extract byte n from word x
// bytes numbered from 0 (LSByte) to 3 (MSByte)
int getByte(int x, int n)
{
    return (x >> (n << 3)) & 0xFF;
}
</code>```

Output:

```<code>byte 0 of 0xAABBCCDD is 0xDD
byte 1 of 0xAABBCCDD is 0xCC
byte 2 of 0xAABBCCDD is 0xBB
byte 3 of 0xAABBCCDD is 0xAA
</code>```

the result is self explanatory but why the compiler didn't converted 0xFF into 0x000000FF , since it has to perform AND operation with a 4 byte number and instead generated the output consisting of only 1 byte of data and not 4 byte of data.

答:
0xFF and 0x000000FF are both exactly the same thing, by default the formatting will drop the leading 0's if you want to print them in your output, you just need to specify it:

```<code>printf("byte %d of 0x%X is 0x08%X\n",n,x,getByte(x,n));
</code>```

But since you are printing Bytes I'm not quite sure why you would expect the leading 0's.

Body:
I am trying to write a piece of code to extract every single byte of data out of a 4 byte integer

after little bit of searching i actually found the code with which this can be achieved , but i am just curious to know why it behaves the way output is created , below is the code

#include <stdio.h>

int getByte(int x, int n);

void main()
{
    int x = 0xAABBCCDD;
    int n;

    for (n=0; n<=3; n++) {
        printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
    }

}

// extract byte n from word x
// bytes numbered from 0 (LSByte) to 3 (MSByte)
int getByte(int x, int n)
{
    return (x >> (n << 3)) & 0xFF;
}

Output:

byte 0 of 0xAABBCCDD is 0xDD
byte 1 of 0xAABBCCDD is 0xCC
byte 2 of 0xAABBCCDD is 0xBB
byte 3 of 0xAABBCCDD is 0xAA

the result is self explanatory but why the compiler didn't converted 0xFF into 0x000000FF , since it has to perform AND operation with a 4 byte number and instead generated the output consisting of only 1 byte of data and not 4 byte of data.

Body:
0xFF and 0x000000FF are both exactly the same thing, by default the formatting will drop the leading 0's if you want to print them in your output, you just need to specify it:

printf("byte %d of 0x%X is 0x08%X\n",n,x,getByte(x,n));

But since you are printing Bytes I'm not quite sure why you would expect the leading 0's.


问:
Windows .batch Choice command always chooses the same choice no matter input
I'm doing a project to help myself learn batch a little better. I have code which is meant to be a "UI" of sorts.

The snippet I have an issue with is this:

```<code>:install_check
if exist UI (
echo UI is already installed; reinstall?
CHOICE
if Errorlevel 1 goto :del
if Errorlevel 2 goto :return
cls && goto :install_check
)
goto :install_yes
</code>```

I know the naming conventions and some of the coding stuff isn't perfect, but I really see no reason why every time it runs it goes to :del no matter what I type in for choice.

I've changed the choice switches and moved it around to be all in one line but it still doesn't want to work. The if that it is nested in is meant to check if a file is present on the computer, so it is a requirement but also may be the issue?

I tried looking around on this site but nothing will help my issue, any help is gladly accepted!!

答:
Check the errorlevels in reverse-order.

```<code>if errorlevel n
</code>```

means if errorlevel is n or greater

hence, errorlevel 2 will be interpreted as true for if errorlevel 1

Body:
I'm doing a project to help myself learn batch a little better. I have code which is meant to be a "UI" of sorts.

The snippet I have an issue with is this:

:install_check
if exist UI (
echo UI is already installed; reinstall?
CHOICE
if Errorlevel 1 goto :del
if Errorlevel 2 goto :return
cls && goto :install_check
)
goto :install_yes

I know the naming conventions and some of the coding stuff isn't perfect, but I really see no reason why every time it runs it goes to :del no matter what I type in for choice.

I've changed the choice switches and moved it around to be all in one line but it still doesn't want to work. The if that it is nested in is meant to check if a file is present on the computer, so it is a requirement but also may be the issue?

I tried looking around on this site but nothing will help my issue, any help is gladly accepted!!

Body:
Check the errorlevels in reverse-order.

if errorlevel n

means if errorlevel is n or greater

hence, errorlevel 2 will be interpreted as true for if errorlevel 1


问:
wicket DropDownChoice No get method defined for class
I am using a DropDownChoice, its key and value are username property of User object. But when I submit I get the following error No get method defined for class: class java.lang.String expression: username.

When the form is submitted, I want the form input to be set onto name property of the SearchPerson object, I am loading the dropdown using the users(list of user). My select box's display and value are both username

```<code><select name="select" wicket:id="name" id="select">
                    <option value="test">test</option>
                </select>

form.add(new DropDownChoice("name",new PropertyModel(searchPerson, "name"),users,new ChoiceRenderer( "username", "username" )));
</code>```

答:
You're trying to inject an User into a String property (searchPerson.name). Either make users a List<Strings>, or make the DropDownChoice have a IModel<User>.

[edited]

And, that error probably is happening because the component is trying to get the current model value's key property. So, it takes searchPerson.name and try to get the value of the property username from it, which obviously doesn't exist, since it's a String, not an User.

[updated]

If what you want is auto-complete of a text field, you could try DefaultCssAutocompleteTextField from wicket-extensions. And you could query the database (Hibernate, I suppose) for usernames directly instead of Users, instead of iterating the users list in memory.

Body:
I am using a DropDownChoice, its key and value are username property of User object. But when I submit I get the following error No get method defined for class: class java.lang.String expression: username.

When the form is submitted, I want the form input to be set onto name property of the SearchPerson object, I am loading the dropdown using the users(list of user). My select box's display and value are both username

<select name="select" wicket:id="name" id="select">
                    <option value="test">test</option>
                </select>

form.add(new DropDownChoice("name",new PropertyModel(searchPerson, "name"),users,new ChoiceRenderer( "username", "username" )));


问:
Python - Can't open lib 'libtdsodbc.so' : file not found
Any help with this issue is much appreciated.

Goal: Connect Django to MSSQL server using FreeTDS. I'm using a Debian x64 box.

Problem: When trying to make a connection I get the following.

```<code>('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'libtdsodbc.so' : file not found (0) (SQLDriverConnect)")
</code>```

My /etc/odbcinst.ini is configured as followed

```<code>[FreeTDS]
Description = FreeTDS
driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
</code>```

The files do exist and have 777 access for testing.

The connection string is like

```<code>cnxn = pyodbc.connect(
        'DRIVER={FreeTDS};SERVER=' + server + ';PORT=1443;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
    cursor = cnxn.cursor()
</code>```

My odbcinst -j reads (since adding symlink)

```<code>unixODBC 2.3.1
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
</code>```

答:
If anyone else runs into this hurdle, check out this blog post.

https://emacstragic.net/2017/11/06/mssql-odbc-client-on-debian-9-stretch/

Essentially, I had to target a specific libssl version for it to work.

Looking at the installed versions i found:

```<code>ldd /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.9.1 | grep 'not found'
libcrypto.so.1.0.0 => not found
libssl.so.1.0.0 => not found
</code>```

and manually installing a previous version fixed the issue

```<code>wget "http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb"
sudo apt install ./libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb
</code>```

Body:
Any help with this issue is much appreciated.

Goal: Connect Django to MSSQL server using FreeTDS. I'm using a Debian x64 box.

Problem: When trying to make a connection I get the following.

('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'libtdsodbc.so' : file not found (0) (SQLDriverConnect)")

My /etc/odbcinst.ini is configured as followed

[FreeTDS]
Description = FreeTDS
driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so

The files do exist and have 777 access for testing.

The connection string is like

cnxn = pyodbc.connect(
        'DRIVER={FreeTDS};SERVER=' + server + ';PORT=1443;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
    cursor = cnxn.cursor()

My odbcinst -j reads (since adding symlink)

unixODBC 2.3.1
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

Body:
If anyone else runs into this hurdle, check out this blog post.

https://emacstragic.net/2017/11/06/mssql-odbc-client-on-debian-9-stretch/

Essentially, I had to target a specific libssl version for it to work.

Looking at the installed versions i found:

ldd /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.9.1 | grep 'not found'
libcrypto.so.1.0.0 => not found
libssl.so.1.0.0 => not found

and manually installing a previous version fixed the issue

wget "http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb"
sudo apt install ./libssl1.0.0_1.0.1t-1+deb8u7_amd64.deb


问:
Mysqli bind parameters not working
I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:

```<code>$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
</code>```

Unprepared version:

```<code>  $sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
          $date', 'Nominator/$location$newstring')";
  mysqli_query($mysqli, $sql);
</code>```

答:
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.</p>

```<code> //Prepare your query first
 $stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
    VALUES (?, ?, ?, ?)");

//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
</code>```

Title: Mysqli bind parameters not working

Body:
I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:

$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();

Unprepared version:

  $sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
          $date', 'Nominator/$location$newstring')";
  mysqli_query($mysqli, $sql);

Body:
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.

 //Prepare your query first
 $stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
    VALUES (?, ?, ?, ?)");

//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);


问:
ActivatedRoute isn't working in Service

ActivatedRoute in Services

The Problem

I was trying to use ActivatedRoute in a service and was noticing that it didn't seem to be tracking the route that I was currently on. In fact it wouldn't seem to pick up any route. It took me far too long to figure out what was going on and I wasn't able to find many helpful answers online(probably because most people are a lot quicker than me :) ).

Just wanted to make sure that I posted something so that some others can find the solution faster.

Here's what my code looked like when I was having the issue.

```<code>@Injectable()
export class ImdbService {

  constructor(private router: Router,
    private route: ActivatedRoute) {
  }

  closeDetails(): void {
    this.detailsOpened = false;
    this.router.navigate(['../'], {relativeTo: this.route});
  }
</code>```

答:
My Solution

Because the services seem to not have the same interaction with ActivatedRoute when injected as the components do my solution was to pass the ActivatedRoute as a param in the service call I was using.

Here's what the solution that worked for me looks like:

```<code>@Injectable()
export class ImdbService {

  constructor(private router: Router) {
  }

  closeDetails(currentRoute): void {
    this.detailsOpened = false;
    this.router.navigate(['../'], {relativeTo: currentRoute});
  }
</code>```

And in the component:

```<code>export class MovieDetailsComponent implements OnInit, OnDestroy {

  constructor(..., private route: ActivatedRoute ) { }

  closeDetails() {
    this.imdbService.closeDetails(this.route);
  }
</code>```

Got something better?

If anyone has a better or even just a different solution to this issue or if there's a good reason to do this in an entirely different way I'd love to see it.

Title: ActivatedRoute isn't working in Service

Body:
ActivatedRoute in Services

The Problem

I was trying to use ActivatedRoute in a service and was noticing that it didn't seem to be tracking the route that I was currently on. In fact it wouldn't seem to pick up any route. It took me far too long to figure out what was going on and I wasn't able to find many helpful answers online(probably because most people are a lot quicker than me :) ).

Just wanted to make sure that I posted something so that some others can find the solution faster.

Here's what my code looked like when I was having the issue.

@Injectable()
export class ImdbService {

  constructor(private router: Router,
    private route: ActivatedRoute) {
  }

  closeDetails(): void {
    this.detailsOpened = false;
    this.router.navigate(['../'], {relativeTo: this.route});
  }

Body:
My Solution

Because the services seem to not have the same interaction with ActivatedRoute when injected as the components do my solution was to pass the ActivatedRoute as a param in the service call I was using.

Here's what the solution that worked for me looks like:

@Injectable()
export class ImdbService {

  constructor(private router: Router) {
  }

  closeDetails(currentRoute): void {
    this.detailsOpened = false;
    this.router.navigate(['../'], {relativeTo: currentRoute});
  }

And in the component:

export class MovieDetailsComponent implements OnInit, OnDestroy {

  constructor(..., private route: ActivatedRoute ) { }

  closeDetails() {
    this.imdbService.closeDetails(this.route);
  }

Got something better?

If anyone has a better or even just a different solution to this issue or if there's a good reason to do this in an entirely different way I'd love to see it.


问:
Using vertex buffers in jogl, crash when too many triangles
I have written a simple application in Java using Jogl which draws a 3d geometry. The camera can be rotated by dragging the mouse. The application works fine, but drawing the geometry with glBegin(GL_TRIANGLE) ... calls ist too slow.

So I started to use vertex buffers. This also works fine until the number of triangles gets larger than 1000000. If that happens, the display driver suddenly crashes and my montior gets dark. Is there a limit of how many triangles fit in the buffer? I hoped to get 1000000 triangles rendered at a reasonable frame rate.

I have no idea on how to debug this problem. The nasty thing is that I have to reboot Windows after each launch, since I have no other way to get my display working again. Could anyone give me some advice?

The vertices, triangles and normals are stored in arrays float[][] m_vertices, int[][] m_triangles, float[][] m_triangleNormals.
I initialized the buffer with:

```<code>        // generate a VBO pointer / handle
        if (m_vboHandle <= 0) {
            int[] vboHandle = new int[1];
            m_gl.glGenBuffers(1, vboHandle, 0);
            m_vboHandle = vboHandle[0];
        }

        // interleave vertex / normal data
        FloatBuffer data = Buffers.newDirectFloatBuffer(m_triangles.length * 3*3*2);
        for (int t=0; t<m_triangles.length; t++)
            for (int j=0; j<3; j++) {
                int v = m_triangles[t][j];
                data.put(m_vertices[v]);
                data.put(m_triangleNormals[t]);
            }
        data.rewind();

        // transfer data to VBO
        int numBytes = data.capacity() * 4;
        m_gl.glBindBuffer(GL.GL_ARRAY_BUFFER, m_vboHandle);
        m_gl.glBufferData(GL.GL_ARRAY_BUFFER, numBytes, data, GL.GL_STATIC_DRAW);
        m_gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);
</code>```

Then, the scene gets rendered with:

```<code>        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, m_vboHandle);
        gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL2.GL_NORMAL_ARRAY);
        gl.glVertexPointer(3, GL.GL_FLOAT, 6*4, 0);
        gl.glNormalPointer(GL.GL_FLOAT, 6*4, 3*4);
        gl.glDrawArrays(GL.GL_TRIANGLES, 0, 3*m_triangles.length);
        gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL2.GL_NORMAL_ARRAY);
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);
</code>```

答: Try checking the return value of calling glBufferData.  It will return GL_OUT_OF_MEMORY if it cannot satisfy numBytes.

Body:
I have written a simple application in Java using Jogl which draws a 3d geometry. The camera can be rotated by dragging the mouse. The application works fine, but drawing the geometry with glBegin(GL_TRIANGLE) ... calls ist too slow.

So I started to use vertex buffers. This also works fine until the number of triangles gets larger than 1000000. If that happens, the display driver suddenly crashes and my montior gets dark. Is there a limit of how many triangles fit in the buffer? I hoped to get 1000000 triangles rendered at a reasonable frame rate.

I have no idea on how to debug this problem. The nasty thing is that I have to reboot Windows after each launch, since I have no other way to get my display working again. Could anyone give me some advice?

The vertices, triangles and normals are stored in arrays float[][] m_vertices, int[][] m_triangles, float[][] m_triangleNormals.
I initialized the buffer with:

        // generate a VBO pointer / handle
        if (m_vboHandle <= 0) {
            int[] vboHandle = new int[1];
            m_gl.glGenBuffers(1, vboHandle, 0);
            m_vboHandle = vboHandle[0];
        }

        // interleave vertex / normal data
        FloatBuffer data = Buffers.newDirectFloatBuffer(m_triangles.length * 3*3*2);
        for (int t=0; t<m_triangles.length; t++)
            for (int j=0; j<3; j++) {
                int v = m_triangles[t][j];
                data.put(m_vertices[v]);
                data.put(m_triangleNormals[t]);
            }
        data.rewind();

        // transfer data to VBO
        int numBytes = data.capacity() * 4;
        m_gl.glBindBuffer(GL.GL_ARRAY_BUFFER, m_vboHandle);
        m_gl.glBufferData(GL.GL_ARRAY_BUFFER, numBytes, data, GL.GL_STATIC_DRAW);
        m_gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);

Then, the scene gets rendered with:

        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, m_vboHandle);
        gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL2.GL_NORMAL_ARRAY);
        gl.glVertexPointer(3, GL.GL_FLOAT, 6*4, 0);
        gl.glNormalPointer(GL.GL_FLOAT, 6*4, 3*4);
        gl.glDrawArrays(GL.GL_TRIANGLES, 0, 3*m_triangles.length);
        gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL2.GL_NORMAL_ARRAY);
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);