问:
EnvInject Error using Jenkins evaluated Groovy script
We have a evaluated Groovy script in Jenkins below:-
;

But the build is failing with error [EnvInject] - [ERROR] - [EnvInject] - [ERROR] - Problems occurs on injecting env vars as a build wrap: null
17:04:06 Finished: FAILURE.
Also how can I call the variable from Jenkins shell script to get last successful build date. -Thanks

```<code>def env = System.getenv()
def item = Jenkins.instance.getItem("")
 def  f=item.getLastFailedBuild()

 println f.getTime()

 def  ff=env['item.getLastSuccessfulBuild()]
  println ff.getTime().format("YYYY-MMM-dd HH:MM:SS")
  println ff.getTime().format("dd-MM-yyyy")

  def pa = new ParametersAction([new          StringParameterValue('PARAMETER_NAME', ff)]);
</code>```

Thread.currentThread().executable.addAction(pa)
println 'Script finished! \nenv variable

答:
The easy answer is that on line 7 you have no closing quote here:

def  ff=env['item.getLastSuccessfulBuild()]

However, that is not the last of your issues:

I don't think you want to use ff = env['item.getLastSuccessfulBuild()]'] but rather just a simple ff = item.getLastSuccessfulBuild()

You need to include the following import lines to be able to use the associated classes:

import jenkins.model.Jenkins
import hudson.model.ParametersAction
import hudson.model.StringParameterValue

The line item = Jenkins.instance.getItem("Fastlane_Test") doesn't work in my environment, even replacing "Fastlane_Test" with a job that exists.
I've replaced it with item = Jenkins.instance.getItemByFullName("Fastlane_Test").

Also, for safety, you should test to ensure item isn't null

Finally, have you missed the Thread.currentThread().executable.addAction(pa) line out for a reason? You need to use it to add the new parameter to the running environment.

The following code should hopefully be a reasonable starting point, however please note that I've removed the line def env = System.getenv() since env isn't used anywhere else in the code later:

```<code>import jenkins.model.Jenkins
import hudson.model.ParametersAction
import hudson.model.StringParameterValue

def item = Jenkins.instance.getItemByFullName("Fastlane_Test")

if (item) {
    def  f=item.getLastFailedBuild()

    println f.getTime()

    def  ff=item.getLastSuccessfulBuild()
    println ff.getTime().format("YYYY-MMM-dd HH:MM:SS")
    println ff.getTime().format("dd-MM-yyyy")

    def pa = new ParametersAction([new StringParameterValue("LAST_GOOD", ff.getTime().toString())])
    Thread.currentThread().executable.addAction(pa)
}
</code>```

Hope you find this of assistance, although I see it's been a while since you posted the question.

Kind Regards

Body:
We have a evaluated Groovy script in Jenkins below:-
;

But the build is failing with error [EnvInject] - [ERROR] - [EnvInject] - [ERROR] - Problems occurs on injecting env vars as a build wrap: null
17:04:06 Finished: FAILURE.
Also how can I call the variable from Jenkins shell script to get last successful build date. -Thanks

def env = System.getenv()
def item = Jenkins.instance.getItem("")
 def  f=item.getLastFailedBuild()

 println f.getTime()

 def  ff=env['item.getLastSuccessfulBuild()]
  println ff.getTime().format("YYYY-MMM-dd HH:MM:SS")
  println ff.getTime().format("dd-MM-yyyy")

  def pa = new ParametersAction([new          StringParameterValue('PARAMETER_NAME', ff)]);

Thread.currentThread().executable.addAction(pa)
println 'Script finished! \nenv variable

Body:
The easy answer is that on line 7 you have no closing quote here:

def  ff=env['item.getLastSuccessfulBuild()]

However, that is not the last of your issues:

I don't think you want to use ff = env['item.getLastSuccessfulBuild()]'] but rather just a simple ff = item.getLastSuccessfulBuild()

You need to include the following import lines to be able to use the associated classes:

import jenkins.model.Jenkins
import hudson.model.ParametersAction
import hudson.model.StringParameterValue

The line item = Jenkins.instance.getItem("Fastlane_Test") doesn't work in my environment, even replacing "Fastlane_Test" with a job that exists.
I've replaced it with item = Jenkins.instance.getItemByFullName("Fastlane_Test").

Also, for safety, you should test to ensure item isn't null

Finally, have you missed the Thread.currentThread().executable.addAction(pa) line out for a reason? You need to use it to add the new parameter to the running environment.

The following code should hopefully be a reasonable starting point, however please note that I've removed the line def env = System.getenv() since env isn't used anywhere else in the code later:

import jenkins.model.Jenkins
import hudson.model.ParametersAction
import hudson.model.StringParameterValue

def item = Jenkins.instance.getItemByFullName("Fastlane_Test")

if (item) {
    def  f=item.getLastFailedBuild()

    println f.getTime()

    def  ff=item.getLastSuccessfulBuild()
    println ff.getTime().format("YYYY-MMM-dd HH:MM:SS")
    println ff.getTime().format("dd-MM-yyyy")

    def pa = new ParametersAction([new StringParameterValue("LAST_GOOD", ff.getTime().toString())])
    Thread.currentThread().executable.addAction(pa)
}

Hope you find this of assistance, although I see it's been a while since you posted the question.

Kind Regards


来源: stackexchange

问:
Python: How to pip install opencv2 with specific version 2.4.9?
I know that I could pip install opencv-python which installs opencv3, but is there a separate command or name for opencv specific version such as 2.4.9?

If not, how can I specify which version to install?

Thanks.

答:
Via pip you can specify the package version to install using the following:

```<code>pip install opencv-python==2.4.9
</code>```

However, that package does not seem to be available on pypi.

A little trick for checking available versions:

pip install opencv-python==

Which returns:

Could not find a version that satisfies the requirement opencv-python==
(from versions: 3.1.0.0, 3.1.0.1, 3.1.0.2, 3.1 .0.3, 3.1.0.5, 3.2.0.6, 3.2.0.7) No matching distribution found for opencv-python==

ContentLicense: CC BY-SA 4.0

Body:
Via pip you can specify the package version to install using the following:

pip install opencv-python==2.4.9

However, that package does not seem to be available on pypi.

A little trick for checking available versions:

pip install opencv-python==

Which returns:

Could not find a version that satisfies the requirement opencv-python==
(from versions: 3.1.0.0, 3.1.0.1, 3.1.0.2, 3.1 .0.3, 3.1.0.5, 3.2.0.6, 3.2.0.7) No matching distribution found for opencv-python==

ContentLicense: CC BY-SA 3.0


问:
Python: find consecutive values in 3D numpy array without using groupby?
Say that you have the following 3D numpy array:

```<code>matrices=
numpy.array([[[1, 0, 0], #Level 0
              [1, 1, 1],
              [0, 1, 1]],

             [[0, 1, 0], #Level 1
              [1, 1, 0],
              [0, 0, 0]],

             [[0, 0, 1], #Level 2
              [0, 1, 1],
              [1, 0, 1]]])
</code>```

And that you want to compute the number of times you get consecutive values of 1 for each cell. Let's say you want to count the number of occurrences of 2 and 3 consecutive values of 1 for each cell. The result should be something like this:

```<code>two_cons=([[0,0,0],
           [1,1,0],
           [0,0,0]])
three_cons=([[0,0,0],
             [0,1,0],
             [0,0,0]])
</code>```

meaning that two cells have had at least 2 consecutive values of 1, and only one has had 3 consecutive values.

I know this could be done by using groupby, extracting the "vertical" series of values for each cell, and counting how many times you get n consecutive ones:

```<code>import numpy
two_cons=numpy.zeros((3,3))
for i in range(0,matrices.shape[0]): #Iterate through each "level"
    for j in range(0,matrices.shape[1]):
        vertical=matrices[:,i,j] #Extract the series of 0-1 for each cell of the matrix
        #Determine the occurrence of 2 consecutive values
        cons=numpy.concatenate([numpy.cumsum(c) if c[0] == 1 else c for c in numpy.split(vertical, 1 + numpy.where(numpy.diff(vertical))[0])])
        two_cons[i][j]=numpy.count_nonzero(cons==2)
</code>```

In this example, you get that:

```<code>two_cons=
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  0.],
       [ 0.,  0.,  0.]])
</code>```

My question: how can I do this if I cannot access vertical? In my real case, the 3D numpy array is too large for me to extract vertical series across many levels, so I have to loop through each level at once, and kind of keep memory of what happened at the previous n levels. What do you suggest to do?

答:
I haven't checked the code, but something like this should work... the idea is to scan the matrix along the third dimension and have 2 helper matrices, one keeping track of the length of the actual sequence of ones, and one keeping track of the best sequence encountered so far.</p>

```<code>bests = np.zeros(matrices.shape[:-1])
counter = np.zeros(matrices.shape[:-1])

for depth in range(matrices.shape[0]):
    this_level = matrices[depth, :, :]
    counter = counter * this_level + this_level
    bests = (np.stack([bests, counter], axis=0)).max(axis=0)

two_con = bests > 1
three_con = bests > 2
</code>```

Body:
Say that you have the following 3D numpy array:

matrices=
numpy.array([[[1, 0, 0], #Level 0
              [1, 1, 1],
              [0, 1, 1]],

             [[0, 1, 0], #Level 1
              [1, 1, 0],
              [0, 0, 0]],

             [[0, 0, 1], #Level 2
              [0, 1, 1],
              [1, 0, 1]]])

And that you want to compute the number of times you get consecutive values of 1 for each cell. Let's say you want to count the number of occurrences of 2 and 3 consecutive values of 1 for each cell. The result should be something like this:

two_cons=([[0,0,0],
           [1,1,0],
           [0,0,0]])
three_cons=([[0,0,0],
             [0,1,0],
             [0,0,0]])

meaning that two cells have had at least 2 consecutive values of 1, and only one has had 3 consecutive values.

I know this could be done by using groupby, extracting the "vertical" series of values for each cell, and counting how many times you get n consecutive ones:

import numpy
two_cons=numpy.zeros((3,3))
for i in range(0,matrices.shape[0]): #Iterate through each "level"
    for j in range(0,matrices.shape[1]):
        vertical=matrices[:,i,j] #Extract the series of 0-1 for each cell of the matrix
        #Determine the occurrence of 2 consecutive values
        cons=numpy.concatenate([numpy.cumsum(c) if c[0] == 1 else c for c in numpy.split(vertical, 1 + numpy.where(numpy.diff(vertical))[0])])
        two_cons[i][j]=numpy.count_nonzero(cons==2)

In this example, you get that:

two_cons=
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  0.],
       [ 0.,  0.,  0.]])

My question: how can I do this if I cannot access vertical? In my real case, the 3D numpy array is too large for me to extract vertical series across many levels, so I have to loop through each level at once, and kind of keep memory of what happened at the previous n levels. What do you suggest to do?

Body:
I haven't checked the code, but something like this should work... the idea is to scan the matrix along the third dimension and have 2 helper matrices, one keeping track of the length of the actual sequence of ones, and one keeping track of the best sequence encountered so far.

bests = np.zeros(matrices.shape[:-1])
counter = np.zeros(matrices.shape[:-1])

for depth in range(matrices.shape[0]):
    this_level = matrices[depth, :, :]
    counter = counter * this_level + this_level
    bests = (np.stack([bests, counter], axis=0)).max(axis=0)

two_con = bests > 1
three_con = bests > 2


问:
Python: building an LRU cache
I have around 6,00,000 entries in MongoDB in the following format:

```<code>feature:category:count
</code>```

where

feature could be any word,

category is positive or negative, and

count tells how many times a feature occurred in a document for that category.

I want to cache the top 1000 tuples, let's say so as not to query database each time.

How does one build an LRU cache in Python?  Or are there any known solutions to this?

答: Python 3.2 functools includes an LRU cache. You could easily cherrypick it from repo, check if you have to adjust it to work with Python 2 (shouldn't be too hard - perhaps using itertools instead of certain builtins - ask if you need help) and be done. You need to wrap the query it into a callable and make sure it depends on the (hashable) function arguments, though.

Title: Python: building an LRU cache

Body:
I have around 6,00,000 entries in MongoDB in the following format:

feature:category:count

where

feature could be any word,

category is positive or negative, and

count tells how many times a feature occurred in a document for that category.

I want to cache the top 1000 tuples, let's say so as not to query database each time.

How does one build an LRU cache in Python?  Or are there any known solutions to this?

ContentLicense: CC BY-SA 2.5


问:
Javascript regex find a string like htttp://domain.com/file.zip
I have a string which is basically a body of a page, and I would like to find all links that contains .zip, but I need the whole link.</p>

答:
Something like this you mean?

```<code>https?:\/\/.+?\.zip
</code>```

This will match anything that starts with http:// or https:// and ends with .zip.

Body:
Something like this you mean?

https?:\/\/.+?\.zip

This will match anything that starts with http:// or https:// and ends with .zip.


问:
MiniProfiler not showing up in ASP.NET Core
I'm trying to plumb MiniProfiler into my ASP.NET Core MVC web app. I'm not using Entity Framework, I'm using Dapper.

Following the sample app, here are my changes:

Added to Startup.cs ConfigureServices

services.AddMiniProfiler();

Added to Startup.cs Configure

app.UseMiniProfiler(new MiniProfilerOptions
{
// Path to use for profiler URLs
RouteBasePath = "~/profiler",

```<code> // Control which SQL formatter to use
 SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(),

 // Control storage
 Storage = new MemoryCacheStorage(cache, TimeSpan.FromMinutes(60)),

 // To control which requests are profiled, use the Func<HttpRequest, bool> option:
 ShouldProfile = request => true,

 // Profiles are stored under a user ID, function to get it:
 //UserIdProvider =  request => MyGetUserIdFunction(request),
</code>```

});

Configured the tag helper in my _ViewImports as per the sample

Added the tag helper to my _Layout file, just before the close of the body tag:

<mini-profiler position="@RenderPosition.Left" max-traces="5" show-controls="true" start-hidden="false" />
```

Made sure my controller produces some output for MiniProfiler:

using (MiniProfiler.Current.Step("Example step"))
{ ... }

Despite all this, I get nothing. When I view source, I see that the tag helper has not produced any HTML.

答: I'd added the tag helper to the wrong layout file.</p>

Body:
I'm trying to plumb MiniProfiler into my ASP.NET Core MVC web app. I'm not using Entity Framework, I'm using Dapper.

Following the sample app, here are my changes:

Added to Startup.cs ConfigureServices

services.AddMiniProfiler();

Added to Startup.cs Configure

app.UseMiniProfiler(new MiniProfilerOptions
{
// Path to use for profiler URLs
RouteBasePath = "~/profiler",

 // Control which SQL formatter to use
 SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(),

 // Control storage
 Storage = new MemoryCacheStorage(cache, TimeSpan.FromMinutes(60)),

 // To control which requests are profiled, use the Func<HttpRequest, bool> option:
 ShouldProfile = request => true,

 // Profiles are stored under a user ID, function to get it:
 //UserIdProvider =  request => MyGetUserIdFunction(request),

});

Configured the tag helper in my _ViewImports as per the sample

Added the tag helper to my _Layout file, just before the close of the body tag:

<mini-profiler position="@RenderPosition.Left" max-traces="5" show-controls="true" start-hidden="false" />

Made sure my controller produces some output for MiniProfiler:

using (MiniProfiler.Current.Step("Example step"))
{ ... }

Despite all this, I get nothing. When I view source, I see that the tag helper has not produced any HTML.


问:
Solve a Non-linear Equation of one variable but written in a summation form, in "R"

This is the Non-Linear Equation in "mu" which I want to solve numerically using R. All of the paired (x, y) are known. So the only variable is "mu"

Now, I have written the function in R. Then, I am trying to get the root by using "rootSolve" package. But it is giving an error.

This is my code of the function:

```<code>f = function(k){
sum(((2*exp(-x) - 1)*(2*exp(-y)- 1))/
    (1 + k*(2*exp(-x) - 1)*(2*exp(-y)- 1)))
}
</code>```

This is the error after running "uniroot.all" from the "rootSolve" package:

```<code>> library(rootSolve)
> uniroot.all(f, interval = c(-1, 1))
numeric(0)
Warning message:
In k * (2 * exp(-x) - 1) :
longer object length is not a multiple of shorter object length
</code>```

Also, I am searching my root in the interval (-1, 1).

Can someone please help? I think, my way of defining the function is wrong. Hence this error is coming.

Can anyone confirm that my way of defining the function in the picture is correct or not?

Thank you in advance!

Let me add something more:

The way I have defined my function (chances are high that the way is wrong) and given my data (x, y), I have f(-1) < f(1) and also f(-1) * f(1) < 0. These conditions are satisfied.

Additional Problem that makes me question my way of writing the function:

I cannot run curve function in R. e.g., curve(f, from = -1, to = 1)
But, if I plot Vectorize(f), then the curve function works.

Can anyone please help me in correcting the way of defining the function?

Thank you very much!

答:
It seems that uniroot.all wants a vectorized function. I have tried to use it and get the same error as you do. I can't find anything in the documentation of uniroot.all about this.

I have tried package nleqslv and can get a solution.
I have rewritten your function as follows (I think you made some errors in setting up the equation):

```<code>f <- function(k){
    A <- 2*exp(-x)-1
    B <- 2*exp(-y)-1
    sum((A*B)/(1+k*A*B))
}
</code>```

and run the function with these data

```<code>set.seed(13)
x <- runif(10)*10
y <- runif(10)*5
</code>```

and the solved your function as follows:

```<code>library(nleqslv)
nleqslv(0,f)
</code>```

with the following output:

```<code>$x
[1] 1.42992

$fvec
[1] 2.300633e-09

$termcd
[1] 1

$message
[1] "Function criterion near zero"

$scalex
[1] 1

$nfcnt
[1] 7

$njcnt
[1] 1

$iter
[1] 7
</code>```

This solves with a Secant method. If you want to try other methods you can use testnslv to explore.

** Addition **

Function uniroot.all will work in my example as long as you do:

```<code>fvec <- Vectorize(f)
</code>```

and change the interval to c(-1,1.7).

OwnerDisplayName: Soumojit Das

Body:
This is the Non-Linear Equation in "mu" which I want to solve numerically using R. All of the paired (x, y) are known. So the only variable is "mu"

Now, I have written the function in R. Then, I am trying to get the root by using "rootSolve" package. But it is giving an error.

This is my code of the function:

f = function(k){
sum(((2*exp(-x) - 1)*(2*exp(-y)- 1))/
    (1 + k*(2*exp(-x) - 1)*(2*exp(-y)- 1)))
}

This is the error after running "uniroot.all" from the "rootSolve" package:

> library(rootSolve)
> uniroot.all(f, interval = c(-1, 1))
numeric(0)
Warning message:
In k * (2 * exp(-x) - 1) :
longer object length is not a multiple of shorter object length

Also, I am searching my root in the interval (-1, 1).

Can someone please help? I think, my way of defining the function is wrong. Hence this error is coming.

Can anyone confirm that my way of defining the function in the picture is correct or not?

Thank you in advance!

Let me add something more:

The way I have defined my function (chances are high that the way is wrong) and given my data (x, y), I have f(-1) < f(1) and also f(-1) * f(1) < 0. These conditions are satisfied.

Additional Problem that makes me question my way of writing the function:

I cannot run curve function in R. e.g., curve(f, from = -1, to = 1)
But, if I plot Vectorize(f), then the curve function works.

Can anyone please help me in correcting the way of defining the function?

Thank you very much!

Body:
It seems that uniroot.all wants a vectorized function. I have tried to use it and get the same error as you do. I can't find anything in the documentation of uniroot.all about this.

I have tried package nleqslv and can get a solution.
I have rewritten your function as follows (I think you made some errors in setting up the equation):

f <- function(k){
    A <- 2*exp(-x)-1
    B <- 2*exp(-y)-1
    sum((A*B)/(1+k*A*B))
}

and run the function with these data

set.seed(13)
x <- runif(10)*10
y <- runif(10)*5

and the solved your function as follows:

library(nleqslv)
nleqslv(0,f)

with the following output:

$x
[1] 1.42992

$fvec
[1] 2.300633e-09

$termcd
[1] 1

$message
[1] "Function criterion near zero"

$scalex
[1] 1

$nfcnt
[1] 7

$njcnt
[1] 1

$iter
[1] 7

This solves with a Secant method. If you want to try other methods you can use testnslv to explore.

** Addition **

Function uniroot.all will work in my example as long as you do:

fvec <- Vectorize(f)

and change the interval to c(-1,1.7).


问:
Object variable or With block variable not set Access vba
I'm working with a couple tables, CTOL and CTOL_Asbuilt in Access. I'm trying to run a query to join these two tables together using VBA code. I ran the query in Access and it works. I'm using DAO for the database library to retrieve data from the local Access database (code is in the same database project as the database), and I'm new to VBA Access scripting.

SELECT CTOL.ID, CTOL.BOM_PART_NAME, CTOL.CII, CTOL.[PART FIND NO], CTOL.CSN,
       CTOL.AFS, CTOL.EQP_POS_CD, CTOL.LCN, CTOL.POS_CT, CTOL.SERIAL_NO,
       CTOL.PART_NO_LLP, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO],
       [CTOL_PW-E750207_Asbuilt].[PW-PART-NO]
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];
```

<p>This is the code below:</p>

```Option Compare Database
Option Explicit

'Const adOpenStatic = 3
'Const adLockOptimistic = 3

Function queryDatabase()

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsQuery As DAO.Recordset

Dim part_find_no() As String
Dim eqp_pos() As Integer
'Dim strSQL As String
Dim i As Integer
Dim j As Integer
'Set objConnection = CurrentDb.OpenRecordset("CTOL")

Set db = CurrentDb

Set rsQuery = db.OpenRecordset("SicrProcess", dbOpenDynaset)

rs.Close
db.Close

Set rs = Nothing
Set db = Nothing

End Function
```

I'm getting the following error when I run this code with a macro that calls the function:

Run time error '91':

Object variable or With block variable not set

I'm trying to use the code with the query to loop through two fields and increment the value of the EQP_POS_CD field when the PART FIND NO entry matches the last (else, it just moves to the next record until it reaches the end of the result set). I want to test-run this query to make sure that the code retrieves the result that is output by running the query manually in Access.

Can you help me in fixing this error so I can run my code to retrieve the data? Thanks!

答:
Open a recordset and loop through records.  </p>

```<code>Sub queryDatabase()
    On Error GoTo ErrProc

    Dim db As DAO.Database
    Set db = CurrentDb

    Dim qdf As DAO.QueryDef
    Set qdf = db.QueryDefs("SicrProcess") 'set your query name here

    Dim rs As DAO.Recordset
    Set rs = qdf.OpenRecordset(dbOpenDynaset)

    Dim part_find_no() As String
    Dim eqp_pos() As Integer, i As Integer

    If rs.EOF Then GoTo Leave
    rs.MoveLast
    rs.MoveFirst

    For i = 1 To rs.RecordCount

        '...
        'Do work here
        '...

        rs.MoveNext
    Next i

Leave:
    On Error Resume Next
    rs.Close
    Set rs = Nothing
    qdf.Close
    Set qdf = Nothing
    Set db = Nothing
    On Error GoTo 0
    Exit Sub

ErrProc:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Sub
</code>```

Body:
I'm working with a couple tables, CTOL and CTOL_Asbuilt in Access. I'm trying to run a query to join these two tables together using VBA code. I ran the query in Access and it works. I'm using DAO for the database library to retrieve data from the local Access database (code is in the same database project as the database), and I'm new to VBA Access scripting.

SELECT CTOL.ID, CTOL.BOM_PART_NAME, CTOL.CII, CTOL.[PART FIND NO], CTOL.CSN,
       CTOL.AFS, CTOL.EQP_POS_CD, CTOL.LCN, CTOL.POS_CT, CTOL.SERIAL_NO,
       CTOL.PART_NO_LLP, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO],
       [CTOL_PW-E750207_Asbuilt].[PW-PART-NO]
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];

This is the code below:

Option Compare Database
Option Explicit

'Const adOpenStatic = 3
'Const adLockOptimistic = 3

Function queryDatabase()

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsQuery As DAO.Recordset

Dim part_find_no() As String
Dim eqp_pos() As Integer
'Dim strSQL As String
Dim i As Integer
Dim j As Integer
'Set objConnection = CurrentDb.OpenRecordset("CTOL")

Set db = CurrentDb

Set rsQuery = db.OpenRecordset("SicrProcess", dbOpenDynaset)

rs.Close
db.Close

Set rs = Nothing
Set db = Nothing

End Function

I'm getting the following error when I run this code with a macro that calls the function:

Run time error '91':

Object variable or With block variable not set

I'm trying to use the code with the query to loop through two fields and increment the value of the EQP_POS_CD field when the PART FIND NO entry matches the last (else, it just moves to the next record until it reaches the end of the result set). I want to test-run this query to make sure that the code retrieves the result that is output by running the query manually in Access.

Can you help me in fixing this error so I can run my code to retrieve the data? Thanks!

Body:
Open a recordset and loop through records.

Sub queryDatabase()
    On Error GoTo ErrProc

    Dim db As DAO.Database
    Set db = CurrentDb

    Dim qdf As DAO.QueryDef
    Set qdf = db.QueryDefs("SicrProcess") 'set your query name here

    Dim rs As DAO.Recordset
    Set rs = qdf.OpenRecordset(dbOpenDynaset)

    Dim part_find_no() As String
    Dim eqp_pos() As Integer, i As Integer

    If rs.EOF Then GoTo Leave
    rs.MoveLast
    rs.MoveFirst

    For i = 1 To rs.RecordCount

        '...
        'Do work here
        '...

        rs.MoveNext
    Next i

Leave:
    On Error Resume Next
    rs.Close
    Set rs = Nothing
    qdf.Close
    Set qdf = Nothing
    Set db = Nothing
    On Error GoTo 0
    Exit Sub

ErrProc:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Sub


问:
Java Send Mail Function
Does anybody has a proper java send mail function that works 100 % and can share it with me. I am getting some problem with mine!!!</p>

答: I'm not a Java developer by trade, but Java Mail seems to do the job quite nicely.  The "works 100%" requirement is going to depend a lot on your implementation and on the availability of the mail server.</p>

Title: Java Send Mail Function


问:
How to get ajax accordion selected index from javascript
Hi I have used Ajax accordion. what I need is to get current selected index when I click on accordion tab that is on billing information I should get selectedindex=0 in Javascript or in jquery

I have set javascript as

Note : billing information is a class which is set in OPCPanels

```<code><script type="text/javascript">
    function pageLoad(sender, args) {

        $(".billinginformation").click(function (event, ui) {
            alert("hi");

            alert($(".billinginformation").accordion("option", "active"))
        });
    }
</script>
</code>```

HTML code

```<code> <ajax:Accordion ID="OPCPanels" runat="server" SelectedIndex="0" HeaderCssClass="widget billinginformation" ContentCssClass="content" AutoSize="None">
        <Panes>
        <ajax:AccordionPane ID="BillingInformation" runat="server" CssClass="widget">
            <Header><h2>Billing Information</h2></Header>
            <Content>HI</Content>
        </ajax:AccordionPane>
        <ajax:AccordionPane ID="ShippingInformation" runat="server" CssClass="widget">
            <Header>Shipping Information</Header>
            <Content>hello</content>
        </ajax:AccordionPane>
    </Panes>
</ajax:Accordion>
</code>```

I have set billinginformation class to my main accordion and on click of any accordion I get the alert of "hi".

but how should I get that which selected Index I have selected in JavaScript?

答:
Seeing the example code (and the source) at http://www.newschool.edu/ajax/Accordion/Accordion.aspx, you need to use

```<code>var behavior = $find("<%=OPCPanels.ClientID%>_AccordionExtender");
alert( behavior.get_SelectedIndex() );
</code>```

you can view the actual source code to make sure what the id of the accordion extender element is.

Body:
Hi I have used Ajax accordion. what I need is to get current selected index when I click on accordion tab that is on billing information I should get selectedindex=0 in Javascript or in jquery

I have set javascript as

Note : billing information is a class which is set in OPCPanels

HTML code

 <ajax:Accordion ID="OPCPanels" runat="server" SelectedIndex="0" HeaderCssClass="widget billinginformation" ContentCssClass="content" AutoSize="None">
        <Panes>
        <ajax:AccordionPane ID="BillingInformation" runat="server" CssClass="widget">

Billing Information

            <Content>HI</Content>
        </ajax:AccordionPane>
        <ajax:AccordionPane ID="ShippingInformation" runat="server" CssClass="widget">
            Shipping Information
            <Content>hello</content>
        </ajax:AccordionPane>
    </Panes>
</ajax:Accordion>

I have set billinginformation class to my main accordion and on click of any accordion I get the alert of "hi".

but how should I get that which selected Index I have selected in JavaScript?

Body:
Seeing the example code (and the source) at http://www.newschool.edu/ajax/Accordion/Accordion.aspx, you need to use

var behavior = $find("<%=OPCPanels.ClientID%>_AccordionExtender");
alert( behavior.get_SelectedIndex() );

you can view the actual source code to make sure what the id of the accordion extender element is.


问:
Collect phone number with PayPal Express checkout
I recently added a paypal express checkout to the ecommerce site I work for. So far so good. Unfortunately our courier company like to have a phone number, and this is not included in the data object the express checkout returns.

I have tried the website prefs change outlined here, it made no difference to the checkout or the returned data: How can I require a buyer's phone number with Paypal Express Checkout?

There does not seem to be any documentation on developer.paypal.com that indicates any other change is needed.

Does anybody have any further information?

答: Sorted it. You don't get the phone number immediately, but it is available via a request to /v1/payments/payment/PAYMENT_ID via the REST API. Payer-PayerInfo->Phone.</p>


问:
Maven crashes when trying to compile a project "Error executing Maven."
I'm trying to compile a project that uses maven.

Running mvn compile results in the following error:

```<code>[ERROR] Error executing Maven.
[ERROR] java.lang.IllegalStateException: Unable to load cache item
[ERROR] Caused by: Unable to load cache item
[ERROR] Caused by: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils
</code>```

This happens anywhere that I run this, it doesn't have to be in the project directory.

What am I doing wrong?

maven 3.3.9, ubuntu 17.04

Full output from mvn -X:

```<code>Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 9-Ubuntu, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-9-openjdk-amd64
Default locale: en_GB, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-21-generic", arch: "amd64", family: "unix"
[ERROR] Error executing Maven.
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Unable to load cache item
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2205)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3951)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3955)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4870)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4876)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)
    at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:137)
    at com.google.inject.internal.InjectorImpl.initializeBinding(InjectorImpl.java:533)
    at com.google.inject.internal.AbstractBindingProcessor$Processor$1.run(AbstractBindingProcessor.java:160)
    at com.google.inject.internal.ProcessedBindingData.initializeBindings(ProcessedBindingData.java:44)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:123)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:99)
    at com.google.inject.Guice.createInjector(Guice.java:73)
    at com.google.inject.Guice.createInjector(Guice.java:62)
    at org.codehaus.plexus.DefaultPlexusContainer.addPlexusInjector(DefaultPlexusContainer.java:481)
    at org.codehaus.plexus.DefaultPlexusContainer.<init>(DefaultPlexusContainer.java:206)
    at org.apache.maven.cli.MavenCli.container(MavenCli.java:545)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:281)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:547)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.IllegalStateException: Unable to load cache item
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:79)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.get(LoadingCache.java:34)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.create(FastClass.java:65)
    at com.google.inject.internal.BytecodeGen.newFastClass(BytecodeGen.java:204)
    at com.google.inject.internal.DefaultConstructionProxyFactory.create(DefaultConstructionProxyFactory.java:55)
    at com.google.inject.internal.ProxyFactory.create(ProxyFactory.java:159)
    at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:90)
    at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3540)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2321)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2284)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2199)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils
    at com.google.inject.internal.cglib.reflect.$FastClassEmitter.<init>(FastClassEmitter.java:67)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.generateClass(FastClass.java:77)
    at com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache$2.call(LoadingCache.java:54)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:61)
    ... 44 more
</code>```

答:
Looks like that version of maven doesn't work on Java 9, but it does on Java 8.

Ensure that you have the relevant packages installed, e.g...

```<code>sudo apt install openjdk-8-jre openjdk-8-jdk
</code>```

And then make sure that maven uses the correct version. The simplest way to do this is to add the following line to the end of ~/.mavenrc (Creating it if needed):

```<code>export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
</code>```

(You might need to look around in /usr/lib/jvm/ for the exact name you need as it might be different for your system)

Body:
I'm trying to compile a project that uses maven.

Running mvn compile results in the following error:

[ERROR] Error executing Maven.
[ERROR] java.lang.IllegalStateException: Unable to load cache item
[ERROR] Caused by: Unable to load cache item
[ERROR] Caused by: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils

This happens anywhere that I run this, it doesn't have to be in the project directory.

What am I doing wrong?

maven 3.3.9, ubuntu 17.04

Full output from mvn -X:

Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 9-Ubuntu, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-9-openjdk-amd64
Default locale: en_GB, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-21-generic", arch: "amd64", family: "unix"
[ERROR] Error executing Maven.
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Unable to load cache item
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2205)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3951)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3955)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4870)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4876)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)
    at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:137)
    at com.google.inject.internal.InjectorImpl.initializeBinding(InjectorImpl.java:533)
    at com.google.inject.internal.AbstractBindingProcessor$Processor$1.run(AbstractBindingProcessor.java:160)
    at com.google.inject.internal.ProcessedBindingData.initializeBindings(ProcessedBindingData.java:44)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:123)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:99)
    at com.google.inject.Guice.createInjector(Guice.java:73)
    at com.google.inject.Guice.createInjector(Guice.java:62)
    at org.codehaus.plexus.DefaultPlexusContainer.addPlexusInjector(DefaultPlexusContainer.java:481)
    at org.codehaus.plexus.DefaultPlexusContainer.<init>(DefaultPlexusContainer.java:206)
    at org.apache.maven.cli.MavenCli.container(MavenCli.java:545)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:281)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:547)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.IllegalStateException: Unable to load cache item
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:79)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.get(LoadingCache.java:34)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.create(FastClass.java:65)
    at com.google.inject.internal.BytecodeGen.newFastClass(BytecodeGen.java:204)
    at com.google.inject.internal.DefaultConstructionProxyFactory.create(DefaultConstructionProxyFactory.java:55)
    at com.google.inject.internal.ProxyFactory.create(ProxyFactory.java:159)
    at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:90)
    at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3540)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2321)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2284)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2199)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.google.inject.internal.cglib.core.$ReflectUtils
    at com.google.inject.internal.cglib.reflect.$FastClassEmitter.<init>(FastClassEmitter.java:67)
    at com.google.inject.internal.cglib.reflect.$FastClass$Generator.generateClass(FastClass.java:77)
    at com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at com.google.inject.internal.cglib.core.$AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache$2.call(LoadingCache.java:54)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at com.google.inject.internal.cglib.core.internal.$LoadingCache.createEntry(LoadingCache.java:61)
    ... 44 more

Body:
Looks like that version of maven doesn't work on Java 9, but it does on Java 8.

Ensure that you have the relevant packages installed, e.g...

sudo apt install openjdk-8-jre openjdk-8-jdk

And then make sure that maven uses the correct version. The simplest way to do this is to add the following line to the end of ~/.mavenrc (Creating it if needed):

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/

(You might need to look around in /usr/lib/jvm/ for the exact name you need as it might be different for your system)


问:
How do I get hardware info such as CPU name, total RAM, etc. with VB6?
Title pretty much explains it all. I need to get some hardware information such as CPU info, and total RAM with VB6. Ideally, it would return something like this for the CPU:

Intel Core 2 Quad Q8500 2.66 GHz

and for the RAM something simple like an integer for the amount of MB the computer has total.

答:
You could use WMI to get this information:
http://msdn.microsoft.com/en-us/library/aa394084(v=VS.85).aspx

This information is also available in the registry (if WMI isn't to your liking):
HKLM/HARDWARE/DESCRIPTION/System/CentralProcessor

NOTE: Registry keys and locations may change. The WMI API is designed as a more stable source for this kind of information.


问:
ios - making app delete and update core data in the background (objective c)
I want my app in objective-c to delete the core data and then reload it in the background, so the user can still use the current core data. I want this to happen every 30 seconds then have it update on screen, is this possible?</p>

答:
You can accomplish this by having a multithread that makes the call to the api and updates core data while running the app

```<code>dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});
</code>```

Inside the dispatch_async you can have it call himself with a timer, that way, when finished updating the database, it will wait for more 30 seconds until the next call

```<code>[self performSelector:@selector(YourFunctionName)
       withObject:(can be Self or Object from other Classes)
       afterDelay:(Time Of Delay)];
</code>```

Now, be careful as this can create some memory management issues

Body:
You can accomplish this by having a multithread that makes the call to the api and updates core data while running the app

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

Inside the dispatch_async you can have it call himself with a timer, that way, when finished updating the database, it will wait for more 30 seconds until the next call

[self performSelector:@selector(YourFunctionName)
       withObject:(can be Self or Object from other Classes)
       afterDelay:(Time Of Delay)];

Now, be careful as this can create some memory management issues


问:
JMeter error : java.net.SocketException: Unexpected end of file from server
I have read and tried the solutions shared in the previous posts for this error but nothing helped me to fix this. Kindly help.

I am making a HTTPS API call. A very simple call which accepts a 2 KB JSON message via POST method and sends a one word acknowledgement. It works perfectly fine in Postman tool. In JMeter, no. of threads (users) is kept as 25. It works perfectly fine one time with all 25 success response and at times getting few failure  response as

Response code: Non HTTP response code: java.net.SocketException

Response message: Non HTTP response message: Unexpected end of file from server

No consistency at all. I have also tried with both enabling and disabling "use keepalive" checkbox. Both giving me all success one time ; few/all failure at another time with the above error. Please help. Thank you.

Below are the JMeter settings:

HTTP Header Manager : Content-Type - application/json

HTTPRequest sampler : protocol - HTTPS

Server Name or IP : project server name

Method : POST

PATH : The required path with https authentication details passed as parameters

IMPLEMENTATION : Set to JAVA (HTTPCLIENT4 was giving me “443 failed to respond” error)

答:
Both errors (Java implementation and Apache HTTPClient4 implementation), are essentially saying the same thing: The server closed the connection, without providing any response. I think there could be the following reasons:

Authentication problem. If server side checks authentication before processing a request (e.g. using Spring), it may be rejecting your request, it may be not bothering with any response if authentication is not considered correct.

Request Issue. Some less noticeable properties of the request you send via Jmeter are different from what you send in Postman. It could be some minor thing with formatting, or some headers server expects. Some of such inconsistencies can also cause Load Balancer (if you use one) to reject request before it's delivered to the server.

Certificate issues. Since you are using HTTPS, you need to make sure your certificate is setup correctly on JMeter side.

So I suggest:

Review server logs and see if your request makes it to the server. If yes, you might be able to see how it was rejected. If not, you need to trace back and see who rejected it (LB, authentication, etc)

Compare headers and body sent by JMeter vs Postman line to line (use TCPDump for example to obtain it).


问:
filtering out specific keys in an object
I am writing out the key/value pair of an object.  I'm trying to filter out 2 of the keys in the object like this:

```<code>{Object.entries(params.char).filter('Attribute1').filter('Attribute2').map(([key,value], index) => <Text key={key}>{key}</Text>)}
</code>```

Here is one of the objects in "paramas":

```<code>{
    id: 1,
    Name: "Drax Bravesword",
    Rating: "*****",
    XP: 392
Age: 34
    Avatar: require('./images/profile1.png'),
    Map: require('./images/map_1.png'),
    Attribute1: "Power",
    Attribute2: "Knowledge",
    Attribute3: "Family"
}
</code>```

However when I run this, I get this error:

"Array.prototype.filter callback must be a function"

I'm not quite sure how to fix this, but is there a way to fix it or am I doing this all wrong?

Thanks!

答:
filter array method accepts function as argument, not string. So please use this:

```<code>Object.entries(params.char).filter((item) => (item.indexOf('Attribute1') || item.indexOf('Attribute2') > -1 ))...
</code>```

let ob = {
  Attribute1: 11,
  Attribute2: 22,
  Attribute3: 33
};

console.log('Not filtered', Object.entries(ob));
let result = Object.entries(ob).filter((item) => (item.indexOf('Attribute1') > -1 || item.indexOf('Attribute2') > -1 ));

console.log('Filtered:', result)```

Body:
I am writing out the key/value pair of an object.  I'm trying to filter out 2 of the keys in the object like this:

{Object.entries(params.char).filter('Attribute1').filter('Attribute2').map(([key,value], index) => <Text key={key}>{key}</Text>)}

Here is one of the objects in "paramas":

{
    id: 1,
    Name: "Drax Bravesword",
    Rating: "*****",
    XP: 392
Age: 34
    Avatar: require('./images/profile1.png'),
    Map: require('./images/map_1.png'),
    Attribute1: "Power",
    Attribute2: "Knowledge",
    Attribute3: "Family"
}

However when I run this, I get this error:

"Array.prototype.filter callback must be a function"

I'm not quite sure how to fix this, but is there a way to fix it or am I doing this all wrong?

Thanks!

Body:
filter array method accepts function as argument, not string. So please use this:

Object.entries(params.char).filter((item) => (item.indexOf('Attribute1') || item.indexOf('Attribute2') > -1 ))...

let ob = {
  Attribute1: 11,
  Attribute2: 22,
  Attribute3: 33
};

console.log('Not filtered', Object.entries(ob));
let result = Object.entries(ob).filter((item) => (item.indexOf('Attribute1') > -1 || item.indexOf('Attribute2') > -1 ));

console.log('Filtered:', result)


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答: In cases like that, your key values plus their indexes can be considerably larger than the data itself.  Another model of doing simple codes like that is to have a table of codes and then an insert and update check constraint to validate them.  That also avoids a join in order to get the genre data out.  Which way you do it is kind of a toss up and would depend on what your application queries tend to be.</p>


问:
Prime Numbers JavaScript
Can someone please give me guidance on getting the primenumbers here? This is homework so I don't want the answer but some pointers would be greatly appreciated. It's really annoying me :(

I think I'm close. But this problems I have are number 25 and 35. These are not prime but this function is returning them

```<code>var getPrimeNumber = function(n) {
    if(n === 1) return "";
    else if(n == 2) return 2;
    else if(n == 3) return 3;
    else {
        for(i=Math.floor(Math.sqrt(n)); i>=2; i--){
            //console.log(i);//maybe another var in here?
            if(n%i !==0 && n%2 !==0 && n%3 !== 0)
                return n; // 25/Math.sqrt(25) will be equal to zero this is what gives me 25 !!!
        }
    }
};
</code>```

答:
```<code>function isPrime(number) {

  // Immediate exit cases
  switch(true){
    case (number < 2):
      return console.log("Please enter a number greater than or equal to 2.")
    case (number === 2 || number === 3):
      return console.log(number + " is a prime number!")
  }

  // Process number if it does not meet above requirements
  var num = Math.floor(Math.sqrt(number))

  for(var i = 2; i <= num; i++) {
    if(number % i === 0)
      return console.log(number + " is not a prime number")
    else
      return console.log(number + " is a prime number!")
  }
}

isPrime(27) // 27 is a prime number!
isPrime(30) // 30 is not a prime number
isPrime(55) // 55 is a prime number!
isPrime(2)  // 2 is a prime number!
</code>```

Title: Prime Numbers JavaScript

Body:
Can someone please give me guidance on getting the primenumbers here? This is homework so I don't want the answer but some pointers would be greatly appreciated. It's really annoying me :(

I think I'm close. But this problems I have are number 25 and 35. These are not prime but this function is returning them

var getPrimeNumber = function(n) {
    if(n === 1) return "";
    else if(n == 2) return 2;
    else if(n == 3) return 3;
    else {
        for(i=Math.floor(Math.sqrt(n)); i>=2; i--){
            //console.log(i);//maybe another var in here?
            if(n%i !==0 && n%2 !==0 && n%3 !== 0)
                return n; // 25/Math.sqrt(25) will be equal to zero this is what gives me 25 !!!
        }
    }
};


问:
Artifactory JAR signing virtual repo not caching local snapshot repo
I have a local Artifactory server that has a bunch of local repositories defined. I've set up a virtual repository and configured it to sign any JAR files that are retrieved through it.

The libs-signed virtual repository is connected to libs-staging-local and libs-snapshot-local so you can fetch any jar from those two repositories and have them signed by our certificate.

If I fetch a JAR from the staging repo via the signing virtual repo, the first time I have to wait until the signing process is finished but any request after that for the same artifact is fast due to the virtual repository cache.

However, if I fetch a JAR from the snapshot repository via the signing virtual repo, I always get that waiting time while the JAR is being signed (and I've verified that the jarsigner process is fired up on the server every time). So signed artifacts that originate from the snapshot repository are not being cached. I've made sure that there aren't any new snapshot versions being added between the two fetches so the original (unsigned) files are exactly the same.

Does anybody know what's going on with that? How can I have the virtual repository cache the signed snapshot JARs?

答:
Caching behavior depends on how the non-unique snapshot is being resolved.

If the snapshot is being resolved by requesting the concrete timestamped artifact the signed .jar will be cached, for example:

```<code>http://localhost:8081/artifactory/libs-snapshot/org/jfrog/test/multi1/3.5-SNAPSHOT/multi1-3.5-20170105.183200-4.jar
</code>```

However if the snapshot is resolved by requesting - the signed .jar will not be cached, for example:

```<code>http://localhost:8081/artifactory/libs-snapshot/org/jfrog/test/multi1/3.5-SNAPSHOT/multi1-3.5-SNAPSHOT.jar
</code>```

The reason is that the returned artifact for such a request may change and by caching it, Artifactory might return a wrong Artifact.

Body:
Caching behavior depends on how the non-unique snapshot is being resolved.

If the snapshot is being resolved by requesting the concrete timestamped artifact the signed .jar will be cached, for example:

http://localhost:8081/artifactory/libs-snapshot/org/jfrog/test/multi1/3.5-SNAPSHOT/multi1-3.5-20170105.183200-4.jar

However if the snapshot is resolved by requesting - the signed .jar will not be cached, for example:

http://localhost:8081/artifactory/libs-snapshot/org/jfrog/test/multi1/3.5-SNAPSHOT/multi1-3.5-SNAPSHOT.jar

The reason is that the returned artifact for such a request may change and by caching it, Artifactory might return a wrong Artifact.


问:
Delphi Printing Techniques
Where can I find a good resource for adding print capabilities to my program?

I found this page: http://efg2.com/Lab/Library/Delphi/Printing/index.html but it hasn't been updated in 5 years, and I'd like to know if, with Delphi 2009, StretchDIBits is still preferred to StretchDrawMap, how to best support pagination, preview, etc.

To date, I've cheated by creating html or pdf documents than printing those, but it is a bit onerous to go this far for all print tasks.

答:
I suggest Fast Report http://fast-report.com/en/ the best Report tool I have used.

I have used QuickReport, Fortes Report, Report Builder and Rave before Fast Report.

OwnerDisplayName: Zartog

Title: Delphi Printing Techniques

OwnerDisplayName: Cesar Romero


问:
Video streaming through web service and rendering - Any Issues?
We have a web service that sends the video content in the response as binary (in different formats asx, asf, ram, mpeg, mpg, mpe, qt, mov, avi, movie, wmv, smil, mp4, mxf, gxf, flv, 3gp, f4v, mj2, omf, dv, vob).

Do you see any issue with performance, if I have an intermediate application which makes a request to web service to retrieve video content and render in browser?

Thanks

答:
As long as the web service returns binary data directly, then there will be no performance hit.  If this is an XML or SOAP web service that wraps the whole thing in a SOAP envelope and bae64 encodes it to make it all text, then you will not be able to play it directly and it will have a big impact on bandwidth, cpu, and memory.

Also note that by serving the video directly instead of using a true streaming protocol the user will only be able to seek within the portion downloaded so far.  A streaming protocol like RTSP, RTMP, or the many varieties of HTTP Streaming allow seeking to any part of the file and only downloading the part seeked to.


问:
Overwrite output filename of xgettext
I am using xgettext with standard input because the input is not available in a file. However, I'd like it to output a filename I specify as a comment above each string.

Current behaviour

```<code>#: Standardinput:13
msgid "User"
msgstr ""

#: Standardinput:13
msgid "Invite"
msgstr ""

#: Standardinput:14
msgid "Group"
msgstr ""
</code>```

Expected behaviour

If I could set a filename to path/to/file.txt, it should output this instead:

```<code>#: path/to/file.txt:13
msgid "User"
msgstr ""

#: path/to/file.txt:13
msgid "Invite"
msgstr ""

#: path/to/file.txt:14
msgid "Group"
msgstr ""
</code>```

I read every option that I can set in the docs and found nothing about it.

答:
The #: path/to/file.txt:14 text is called "location" and the most control you have over this is the --no-location and --add-location flags. See xgettext.c:xgettext_open() for the source code reason why.

Meanwhile, the obvious thing to do is take your input from standard in, pipe the output to standard out, substitute manually, then store in a target PO file. Example:

```<code>xgettext -k_ -Lc -o- - < hello.c \
    | sed 's@#: standard input:@#: path/to/file.c:@g' \
    > messages.po
</code>```

Obviously change the patterns inside the sed call to match your xgettext's format and the file you want to represent.

Less obvious is to symlink standard in to a file name that looks like your target. Example:

```<code>$ ln -s /dev/stdin file.c
$ echo 'int main() { printf(gettext("Hello World\n")); return 0; }' \
      | xgettext --omit-header -o- file.c
#: file.c:1
#, c-format
msgid "Hello World\n"
msgstr ""
</code>```

Being able to name, for output purposes, the file when input is standard in seems like a reasonable feature. I suggest opening a request at GNU.

Title: Overwrite output filename of xgettext

Body:
I am using xgettext with standard input because the input is not available in a file. However, I'd like it to output a filename I specify as a comment above each string.

Current behaviour

#: Standardinput:13
msgid "User"
msgstr ""

#: Standardinput:13
msgid "Invite"
msgstr ""

#: Standardinput:14
msgid "Group"
msgstr ""

Expected behaviour

If I could set a filename to path/to/file.txt, it should output this instead:

#: path/to/file.txt:13
msgid "User"
msgstr ""

#: path/to/file.txt:13
msgid "Invite"
msgstr ""

#: path/to/file.txt:14
msgid "Group"
msgstr ""

I read every option that I can set in the docs and found nothing about it.

Body:
The #: path/to/file.txt:14 text is called "location" and the most control you have over this is the --no-location and --add-location flags. See xgettext.c:xgettext_open() for the source code reason why.

Meanwhile, the obvious thing to do is take your input from standard in, pipe the output to standard out, substitute manually, then store in a target PO file. Example:

xgettext -k_ -Lc -o- - < hello.c \
    | sed 's@#: standard input:@#: path/to/file.c:@g' \
    > messages.po

Obviously change the patterns inside the sed call to match your xgettext's format and the file you want to represent.

Less obvious is to symlink standard in to a file name that looks like your target. Example:

$ ln -s /dev/stdin file.c
$ echo 'int main() { printf(gettext("Hello World\n")); return 0; }' \
      | xgettext --omit-header -o- file.c
#: file.c:1
#, c-format
msgid "Hello World\n"
msgstr ""

Being able to name, for output purposes, the file when input is standard in seems like a reasonable feature. I suggest opening a request at GNU.


问:
PyVISA SerialInstrument requires hard reset to connect after failure
I am working with a Keysight waveform generator and pyVisa and I notice that if my code doesn't complete successfully and ends I need to perform a hard reset of the device to attempt my code again.

I have tried resetting the device under the __del__ method so that the device is in a known state but that doesn't seem to work. I've also tried using pyvisa.resources.SerialInstrument.clear(). Has anyone else had a problem like this and how did you solve it?

The host computer is running windows 7. PyVISA version is 1.8. After the program fails by me cancelling the python script I will try to send a simple *IDN? SCPI command to the device and I get error:

pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.

If I try to call pyvisa.resources.SerialInstrument.clear() on the device I get error
pyvisa.errors.VisaIOError: VI_ERROR_INV_SETUP (-1073807302): Unable to start operation because setup is invalid (usually due to attributes being set to an inconsistent state).

答:
The problem was that the device was still being connected to by another instance. The cause of that was because running visa.ResourceManager().list_resources() was listing the device twice, once as a USB device and also as an ASRL.

The solution was to call visa.ResourceManager().list_resources(query='USB?*') to make sure that the instrument is only listed once in my results. (Alternately, I could have disabled USB or GPIB in the device settings.) Then call device.clear() immediately after opening the resource to make sure that the buffers were empty because at the error there might have been unread data there. This solved the problem.


问:
angular 2 ngif not working even though function return true
I'm using Angular 2. I have an array and I am looping through each item and setting a boolean. I'm console logging to make sure it's being set properly.  However when I use this function against an *ngif it doesn't work. What crucial piece am I missing here?

template:

```<code> <div *ngFor="let item of viewableItems>
        <div class="thermometerMercury" *ngIf="showThermometer"></div>
 </div>
</code>```

.ts

```<code>  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        this.showThermometer = true;
      } else {
        this.showThermometer = false;
      }
      console.log(i, this.showThermometer);
    }
  }
</code>```

答:
```<code><div *ngIf ="showThermometer"></div>
</code>```

Body:
I'm using Angular 2. I have an array and I am looping through each item and setting a boolean. I'm console logging to make sure it's being set properly.  However when I use this function against an *ngif it doesn't work. What crucial piece am I missing here?

template:

.ts

  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        this.showThermometer = true;
      } else {
        this.showThermometer = false;
      }
      console.log(i, this.showThermometer);
    }
  }

Body: <div *ngIf ="showThermometer"></div>


问:
Get Source of Current Tab in Google Chrome via Applescript
It's child's play to do this in Safari, which has good Applescript support. Google Chrome's AS support has just arrived so I'm giving them the benefit of the doubt. I am basically trying to grab the current HTML via the clipboard so I can get information out. We have some nifty commands like this:

```<code>tell application "Google Chrome"
 view source of active tab of window 1
 save active tab of window 1
 print active tab of window 1
 reload active tab of window 1
 go back active tab of window 1
 go forward active tab of window 1
 copy selection of active tab of window 1
 paste selection active tab of window 1
end tell
</code>```

but alas you can't say "set X to source of active tab of window 1". Anyone have any suggestions for me? My current ideas are to load the code I need in the background in Safari (pretty ugly) or try to display source and grab it with UI script, but that's also ugly. Also I keep encountering scripting bugs that keep it from working.

Any help would be appreciated.

答:
I'm very excited to learn that Chrome has AppleScript support now.  It's unfortunate that it's minimal as yet, but I'm sure (I hope!) it'll get better.  Since there's no way to get the source directly, I'd choose the following hackish route:

```<code>tell application "Google Chrome"
    view source of active tab of window 1 -- Or whichever tab you want
    delay 3
    repeat while loading of active tab of window 1
        delay 3
    end repeat
    select all of active tab of window 1 -- Must *always* be the active tab
    copy selection of active tab of window 1
    delete tab (active tab index of window 1) of window 1
end tell
delay 1
return the clipboard
</code>```

Yes, it's hackish, but that's unavoidable, given the current state of the scripting dictionary.  The script should be straightforward: open a source tab, wait for it to load, select the contents, copy it, and close the tab.  You can play with the delay 3s to see what works best.  Note that the first active tab of window 1 is arbitrary, the rest explicitly refer to the source tab.  <s>Also, apparently there's no way to close a tab from within Chrome's scripting dictionary (oy vey), so I had to use JavaScript instead.</s>  Also, the last delay 1 shouldn't be necessary, but if it wasn't there, my tests would sometimes return the wrong thing, even though the clipboard contents were correct when I pasted them in.  I think it's because there was enough text that it took a noticeable amount of time to update the clipboard.

Edit 1: I replaced execute the active tab of window 1 javascript "window.close()" with the delete tab line, as was suggested to me.  Unfortunately, delete tab active tab of window 1 doesn't work, so you need this slightly more convoluted construction.

Body:
It's child's play to do this in Safari, which has good Applescript support. Google Chrome's AS support has just arrived so I'm giving them the benefit of the doubt. I am basically trying to grab the current HTML via the clipboard so I can get information out. We have some nifty commands like this:

tell application "Google Chrome"
 view source of active tab of window 1
 save active tab of window 1
 print active tab of window 1
 reload active tab of window 1
 go back active tab of window 1
 go forward active tab of window 1
 copy selection of active tab of window 1
 paste selection active tab of window 1
end tell

but alas you can't say "set X to source of active tab of window 1". Anyone have any suggestions for me? My current ideas are to load the code I need in the background in Safari (pretty ugly) or try to display source and grab it with UI script, but that's also ugly. Also I keep encountering scripting bugs that keep it from working.

Any help would be appreciated.

Body:
I'm very excited to learn that Chrome has AppleScript support now.  It's unfortunate that it's minimal as yet, but I'm sure (I hope!) it'll get better.  Since there's no way to get the source directly, I'd choose the following hackish route:

tell application "Google Chrome"
    view source of active tab of window 1 -- Or whichever tab you want
    delay 3
    repeat while loading of active tab of window 1
        delay 3
    end repeat
    select all of active tab of window 1 -- Must *always* be the active tab
    copy selection of active tab of window 1
    delete tab (active tab index of window 1) of window 1
end tell
delay 1
return the clipboard

Yes, it's hackish, but that's unavoidable, given the current state of the scripting dictionary.  The script should be straightforward: open a source tab, wait for it to load, select the contents, copy it, and close the tab.  You can play with the delay 3s to see what works best.  Note that the first active tab of window 1 is arbitrary, the rest explicitly refer to the source tab.  <s>Also, apparently there's no way to close a tab from within Chrome's scripting dictionary (oy vey), so I had to use JavaScript instead.</s>  Also, the last delay 1 shouldn't be necessary, but if it wasn't there, my tests would sometimes return the wrong thing, even though the clipboard contents were correct when I pasted them in.  I think it's because there was enough text that it took a noticeable amount of time to update the clipboard.

Edit 1: I replaced execute the active tab of window 1 javascript "window.close()" with the delete tab line, as was suggested to me.  Unfortunately, delete tab active tab of window 1 doesn't work, so you need this slightly more convoluted construction.


问:
QTimer won't start when passing a variable
I have a QTimer object that kicks off a function every second.  The timer runs correctly if I do the following

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    // Set a Qtimer to update the OSD display every 1 second
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(print()));
    timer->start(1000);
}

void MainWindow::print()
{
    printf("hello world\n");
}
</code>```

But I want to pass a variable to print().  But when I do this, I never see my print statement.

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    // Set a Qtimer to update the OSD display every 1 second
    QTimer *timer = new QTimer(this);
    int val = 42;
    // Now pass val to print()
    connect(timer, SIGNAL(timeout()), this, SLOT(print(val)));
    timer->start(1000);
}

void MainWindow::print(int val)
{
    // I never see my print statement
    printf("hello world, val=%d\n", val);
}
</code>```

header.h

```<code>class MainWindow : public QMainWindow
{
    Q_OBJECT
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();

    public slots:
        void print(int val);
</code>```

Why does this not work?  What can I do to pass a variable into print() using QTimer?

答:
```<code>connect(timer, SIGNAL(timeout()), this, SLOT(print(val)));
</code>```

Qt signal/slot connections don't work that way.  The text within the SIGNAL() and SLOT() macros has to be the signature of the signal/slot method, verbatim; you can't put variables or other non-method-signature text there.

If you look at your program's stdout while it runs, you'll see an error message printed by connect() telling you that it can't find any slot-method named print(val).

If you want to provide a separate value for your slot, you could either make val a member-variable of your class, and have print() look at the member variable instead of an argument, or you could use an intermediary slot, like this:

```<code>public slots:
   void print(int val);
   void print42() {print(val);}
</code>```

... and then connect your signal to SLOT(print42()) instead.

Body:
I have a QTimer object that kicks off a function every second.  The timer runs correctly if I do the following

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    // Set a Qtimer to update the OSD display every 1 second
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(print()));
    timer->start(1000);
}

void MainWindow::print()
{
    printf("hello world\n");
}

But I want to pass a variable to print().  But when I do this, I never see my print statement.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    // Set a Qtimer to update the OSD display every 1 second
    QTimer *timer = new QTimer(this);
    int val = 42;
    // Now pass val to print()
    connect(timer, SIGNAL(timeout()), this, SLOT(print(val)));
    timer->start(1000);
}

void MainWindow::print(int val)
{
    // I never see my print statement
    printf("hello world, val=%d\n", val);
}

header.h

class MainWindow : public QMainWindow
{
    Q_OBJECT
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();

    public slots:
        void print(int val);

Why does this not work?  What can I do to pass a variable into print() using QTimer?

Body:
connect(timer, SIGNAL(timeout()), this, SLOT(print(val)));

Qt signal/slot connections don't work that way.  The text within the SIGNAL() and SLOT() macros has to be the signature of the signal/slot method, verbatim; you can't put variables or other non-method-signature text there.

If you look at your program's stdout while it runs, you'll see an error message printed by connect() telling you that it can't find any slot-method named print(val).

If you want to provide a separate value for your slot, you could either make val a member-variable of your class, and have print() look at the member variable instead of an argument, or you could use an intermediary slot, like this:

public slots:
   void print(int val);
   void print42() {print(val);}

... and then connect your signal to SLOT(print42()) instead.


问:
MVC3 EditorTemplate for a nullable boolean using RadioButtons
I have a property on one of my objects that is a nullable boolean, I want my logic to have true represent Yes, false to be No and null to be N/A. Now because I am going to have multiple properties like this on many different objects it makes the most sense to make an editor and display templates for these properties. I am going to use jQuery UI to apply a visual element of buttonset after this is all working but for now, that's beyond the scope of my problem. My editor template looks like this.

```<code>@model bool?
<div data-ui="buttonset">
@Html.RadioButtonFor(x => x, true, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes"}) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))Yes">Yes</label>
@Html.RadioButtonFor(x => x, false, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No" }) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))No">No</label>
@Html.RadioButtonFor(x => x, "null", new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA" }) <label for="@(ViewData.TemplateInfo.GetFullHtmlFieldId(""))NA">N/A</label>
</div>
</code>```

My problem is that under no circumstances can I get this editor template to show the current value of the model correctly. Because I am not rendering a property of a model at this scope but the model itself, the built in logic in MVC3 will not set the checked property correctly because of a check that is made to verify the name is not empty or null (See MVC3 source, InputExtensions.cs:line#259). I can't set the checked attribute dynamically by comparing to the Model because the browser checks the radiobutton on the presence of the checked attribute not it's value, so even though my radio buttons would look like the following the last one is still the one selected.

```<code><div class="span-4" data-ui="buttonset">
<input checked="checked" id="MyObject_BooleanValueYes" name="MyObject.BooleanValue" type="radio" value="True" /><label for="MyObject_BooleanValueYes">Yes</label>
<input checked="" id="MyObject_BooleanValueNo" name="MyObject.BooleanValue" type="radio" value="False" /><label for="MyObject_BooleanValueNo">No</label>
<input checked="" id="MyObject_BooleanValueNA" name="MyObject.BooleanValue" type="radio" value="null" /><label for="MyObject_BooleanValueNA">N/A</label>
</div><span class="field-validation-valid" data-valmsg-for="MyObject.BooleanValue" data-valmsg-replace="true"></span> </div>
</code>```

I can't conditionally add the HtmlAttribute using something like if?truevalue:falsevalue becuase the true/false parts would be of different anonymous types and I get an error.

I'm struggling on how this should be done and am hoping one of you have a suggestion on how to tackle this problem?

答:
You can use a @helper to simplify the accepted answer:</p>

```<code>@model bool?

<div data-ui="buttonset">
    @Radio(true,  "Yes", "Yes")
    @Radio(false, "No",  "No")
    @Radio(null,  "N/A", "NA")
</div>

@helper Radio(bool? buttonValue, string buttonLabel, string buttonId)
{
    Dictionary<string, object> attrs = new Dictionary<string, object>();

    // Unique button id
    string id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + buttonId;

    attrs.Add("id", id);

    // Check the active button
    if (Model == buttonValue)
    {
        attrs.Add("checked", "checked");
    }

    @Html.RadioButtonFor(m => m, buttonValue, attrs) <label for="@id">@buttonLabel</label>
}
</code>```

Body:
I have a property on one of my objects that is a nullable boolean, I want my logic to have true represent Yes, false to be No and null to be N/A. Now because I am going to have multiple properties like this on many different objects it makes the most sense to make an editor and display templates for these properties. I am going to use jQuery UI to apply a visual element of buttonset after this is all working but for now, that's beyond the scope of my problem. My editor template looks like this.

@model bool?

@Html.RadioButtonFor(x => x, true, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes"}) Yes
@Html.RadioButtonFor(x => x, false, new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No" }) No
@Html.RadioButtonFor(x => x, "null", new { id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA" }) N/A

My problem is that under no circumstances can I get this editor template to show the current value of the model correctly. Because I am not rendering a property of a model at this scope but the model itself, the built in logic in MVC3 will not set the checked property correctly because of a check that is made to verify the name is not empty or null (See MVC3 source, InputExtensions.cs:line#259). I can't set the checked attribute dynamically by comparing to the Model because the browser checks the radiobutton on the presence of the checked attribute not it's value, so even though my radio buttons would look like the following the last one is still the one selected.

<input checked="checked" id="MyObject_BooleanValueYes" name="MyObject.BooleanValue" type="radio" value="True" />Yes
<input checked="" id="MyObject_BooleanValueNo" name="MyObject.BooleanValue" type="radio" value="False" />No
<input checked="" id="MyObject_BooleanValueNA" name="MyObject.BooleanValue" type="radio" value="null" />N/A

I can't conditionally add the HtmlAttribute using something like if?truevalue:falsevalue becuase the true/false parts would be of different anonymous types and I get an error.

I'm struggling on how this should be done and am hoping one of you have a suggestion on how to tackle this problem?

Body:
You can use a @helper to simplify the accepted answer:

@model bool?

<div data-ui="buttonset">
    @Radio(true,  "Yes", "Yes")
    @Radio(false, "No",  "No")
    @Radio(null,  "N/A", "NA")
</div>

@helper Radio(bool? buttonValue, string buttonLabel, string buttonId)
{
    Dictionary<string, object> attrs = new Dictionary<string, object>();

    // Unique button id
    string id = ViewData.TemplateInfo.GetFullHtmlFieldId("") + buttonId;

    attrs.Add("id", id);

    // Check the active button
    if (Model == buttonValue)
    {
        attrs.Add("checked", "checked");
    }

    @Html.RadioButtonFor(m => m, buttonValue, attrs) <label for="@id">@buttonLabel</label>
}


问:
Crawling websites to extract email
I have a web crawler, that does not work properly. If I visit a page, such like http://www.canon.de/support/consumer_products/contact_support/ then I want to extract the emails from this page. And furthermore, if there are references to other websites from canon ( and it is ) then my crawler shall visit all these pages to gather mails.

Unfortunately, my method "searchforWord" does not work, I never reach the if statement, I don't know why. Where is my mistake?

Here are my classes:

Spider.class

```<code> public class Spider {

 private static final int MAX_PAGES_TO_SEARCH = 10;
    private Set<String> pagesVisited = new HashSet<String>();
    private List<String> pagesToVisit = new LinkedList<String>();

    /**
     * Our main launching point for the Spider's functionality. Internally it creates spider legs
     * that make an HTTP request and parse the response (the web page).
     *
     * @param url
     *            - The starting point of the spider
     * @param searchWord
     *            - The word or string that you are searching for
     */
    public void search(String url)
    {
        while(this.pagesVisited.size() < MAX_PAGES_TO_SEARCH)
        {
            String currentUrl;
            SpiderLeg leg = new SpiderLeg();
            if(this.pagesToVisit.isEmpty())
            {
                currentUrl = url;
                this.pagesVisited.add(url);
            }
            else
            {
                currentUrl = this.nextUrl();
            }
            leg.crawl(currentUrl); // Lots of stuff happening here. Look at the crawl method in
                                   // SpiderLeg

            leg.searchForWord(currentUrl);

            this.pagesToVisit.addAll(leg.getLinks());
        }
        System.out.println("\n**Done** Visited " + this.pagesVisited.size() + " web page(s)");
    }

    /**
     * Returns the next URL to visit (in the order that they were found). We also do a check to make
     * sure this method doesn't return a URL that has already been visited.
     *
     * @return
     */
    private String nextUrl()
    {
        String nextUrl;
        do
        {
            nextUrl = this.pagesToVisit.remove(0);
        } while(this.pagesVisited.contains(nextUrl));
        this.pagesVisited.add(nextUrl);
        return nextUrl;
    }

  }
</code>```

SpiderLeg.class

```<code>public class SpiderLeg
{
// We'll use a fake USER_AGENT so the web server thinks the robot is a
 normal web browser.

      private static final String USER_AGENT =
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML,
      like Gecko) Chrome/13.0.782.112 Safari/535.1";
private List<String> links = new LinkedList<String>();
private Document htmlDocument;

/**
 * This performs all the work. It makes an HTTP request, checks the response, and then gathers
 * up all the links on the page. Perform a searchForWord after the successful crawl
 *
 * @param url
 *            - The URL to visit
 * @return whether or not the crawl was successful
 */
public boolean crawl(String url)
{
    try
    {
        Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);
        Document htmlDocument = connection.get();
        this.htmlDocument = htmlDocument;
        if(connection.response().statusCode() == 200) // 200 is the HTTP OK status code
                                                      // indicating that everything is great.
        {
           System.out.println("\n**Visiting** Received web page at " + url);
        }
        if(!connection.response().contentType().contains("text/html"))
        {
            System.out.println("**Failure** Retrieved something other than HTML");
            return false;
        }
        Elements linksOnPage = htmlDocument.select("a[href]");
        //System.out.println("Found (" + linksOnPage.size() + ") links");
        for(Element link : linksOnPage)
        {
            this.links.add(link.absUrl("href"));
        }
        return true;
    }
    catch(IOException ioe)
    {
        // We were not successful in our HTTP request
        return false;
    }
}

public void searchForWord(String searchWord)
{

    Pattern pattern =
              Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Za-z]{2,4})");

              Matcher matchs = pattern.matcher(searchWord);

              if (matchs.find()) {

                      System.out.println(searchWord.substring( matchs.start(), matchs.end()));

              }

              else
                  System.out.println("hdhdadsad");

}

public List<String> getLinks()
{
    return this.links;
}

}
</code>```

SpiderTest.class

```<code>public class SpiderTest
{

    public static void main(String[] args)
    {
        Spider spider = new Spider();
        spider.search("http://www.canon.de/support/consumer_products/contact_support/");
    }
}
</code>```

答:
Your regex is valid.

see here http://www.regexpal.com/?fam=97822

Use following code instead of  if to find all matches:

```<code>while (matchs.find()) {
    System.out.println(matchs.group());
}
</code>```

Title: Crawling websites to extract email

Body:
I have a web crawler, that does not work properly. If I visit a page, such like http://www.canon.de/support/consumer_products/contact_support/ then I want to extract the emails from this page. And furthermore, if there are references to other websites from canon ( and it is ) then my crawler shall visit all these pages to gather mails.

Unfortunately, my method "searchforWord" does not work, I never reach the if statement, I don't know why. Where is my mistake?

Here are my classes:

Spider.class

 public class Spider {

 private static final int MAX_PAGES_TO_SEARCH = 10;
    private Set<String> pagesVisited = new HashSet<String>();
    private List<String> pagesToVisit = new LinkedList<String>();

    /**
     * Our main launching point for the Spider's functionality. Internally it creates spider legs
     * that make an HTTP request and parse the response (the web page).
     *
     * @param url
     *            - The starting point of the spider
     * @param searchWord
     *            - The word or string that you are searching for
     */
    public void search(String url)
    {
        while(this.pagesVisited.size() < MAX_PAGES_TO_SEARCH)
        {
            String currentUrl;
            SpiderLeg leg = new SpiderLeg();
            if(this.pagesToVisit.isEmpty())
            {
                currentUrl = url;
                this.pagesVisited.add(url);
            }
            else
            {
                currentUrl = this.nextUrl();
            }
            leg.crawl(currentUrl); // Lots of stuff happening here. Look at the crawl method in
                                   // SpiderLeg

            leg.searchForWord(currentUrl);

            this.pagesToVisit.addAll(leg.getLinks());
        }
        System.out.println("\n**Done** Visited " + this.pagesVisited.size() + " web page(s)");
    }

    /**
     * Returns the next URL to visit (in the order that they were found). We also do a check to make
     * sure this method doesn't return a URL that has already been visited.
     *
     * @return
     */
    private String nextUrl()
    {
        String nextUrl;
        do
        {
            nextUrl = this.pagesToVisit.remove(0);
        } while(this.pagesVisited.contains(nextUrl));
        this.pagesVisited.add(nextUrl);
        return nextUrl;
    }

  }

SpiderLeg.class

public class SpiderLeg
{
// We'll use a fake USER_AGENT so the web server thinks the robot is a
 normal web browser.

      private static final String USER_AGENT =
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML,
      like Gecko) Chrome/13.0.782.112 Safari/535.1";
private List<String> links = new LinkedList<String>();
private Document htmlDocument;

/**
 * This performs all the work. It makes an HTTP request, checks the response, and then gathers
 * up all the links on the page. Perform a searchForWord after the successful crawl
 *
 * @param url
 *            - The URL to visit
 * @return whether or not the crawl was successful
 */
public boolean crawl(String url)
{
    try
    {
        Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);
        Document htmlDocument = connection.get();
        this.htmlDocument = htmlDocument;
        if(connection.response().statusCode() == 200) // 200 is the HTTP OK status code
                                                      // indicating that everything is great.
        {
           System.out.println("\n**Visiting** Received web page at " + url);
        }
        if(!connection.response().contentType().contains("text/html"))
        {
            System.out.println("**Failure** Retrieved something other than HTML");
            return false;
        }
        Elements linksOnPage = htmlDocument.select("a[href]");
        //System.out.println("Found (" + linksOnPage.size() + ") links");
        for(Element link : linksOnPage)
        {
            this.links.add(link.absUrl("href"));
        }
        return true;
    }
    catch(IOException ioe)
    {
        // We were not successful in our HTTP request
        return false;
    }
}

public void searchForWord(String searchWord)
{

    Pattern pattern =
              Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Za-z]{2,4})");

              Matcher matchs = pattern.matcher(searchWord);

              if (matchs.find()) {

                      System.out.println(searchWord.substring( matchs.start(), matchs.end()));

              }

              else
                  System.out.println("hdhdadsad");

}

public List<String> getLinks()
{
    return this.links;
}

}

SpiderTest.class

public class SpiderTest
{

    public static void main(String[] args)
    {
        Spider spider = new Spider();
        spider.search("http://www.canon.de/support/consumer_products/contact_support/");
    }
}

Body:
Your regex is valid.

see here http://www.regexpal.com/?fam=97822

Use following code instead of  if to find all matches:

while (matchs.find()) {
    System.out.println(matchs.group());
}