问:
Using same column multiple times in WHERE clause
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

```<code>SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'
</code>```

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

答:
you are using AND operator between two pn.id=1 and pn.id=2. then how you getting the answer is between that:

```<code>(SELECT id FROM property_value WHERE value like '101') and
(SELECT id FROM property_value WHERE value like '102')
</code>```

So like above comments ,  Use or operator.

Update 1:

```<code>SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE pn.id in (1,2) AND pv.id IN (SELECT id FROM property_value WHERE value like '101' or value like '102');
</code>```

Body:
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

Body:
you are using AND operator between two pn.id=1 and pn.id=2. then how you getting the answer is between that:

(SELECT id FROM property_value WHERE value like '101') and
(SELECT id FROM property_value WHERE value like '102')

So like above comments ,  Use or operator.

Update 1:

SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE pn.id in (1,2) AND pv.id IN (SELECT id FROM property_value WHERE value like '101' or value like '102');


来源: stackexchange

问:
In javascript, when creating properties, which is the right way or better syntax?
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax</p>

```<code>var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?
</code>```

答:
When using the dot syntax, the propery name is an identifer:

```<code>var myObj = {};
myObj.myProp1 = "value1";
myObj.myProp2 = "value2";
</code>```

As the property name has to follow the rules of identifier naming, it can for example not start with a digit.

When using the bracket syntax, the property name is a string:

```<code>var myObj = {};
myObj["myProp1"] = "value1";
myObj["myProp2"] = "value2";
</code>```

What's used in the brackets can be a variable, or any kind of expression that results in a string:

```<code>var myObj = {};
var prop1 = "myProp1";
myObj[prop1] = "value1";
myObj["myProp" + 2] = "value2";
</code>```

If you use a number as property name, it will automatically be converted to a string, so these have the same result:

```<code>myObj[2010] = "value";
myObj["2010"] = "value";
</code>```

You can also use an object literal to set the values:

```<code>var myObj = { myProp1: "value1", myProp2: "value2" };
</code>```

(Note that {} is also an object literal, only without properties.)

Using the prototype of an object is only useful if you have named object types (or otherwise assign a prototype to the object). When you create objects using an object literal each object has it's own prototype, so putting anything in the prototype has the same effect as putting it in the object.

ContentLicense: CC BY-SA 2.5

Body:
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax

var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?

Body:
When using the dot syntax, the propery name is an identifer:

var myObj = {};
myObj.myProp1 = "value1";
myObj.myProp2 = "value2";

As the property name has to follow the rules of identifier naming, it can for example not start with a digit.

When using the bracket syntax, the property name is a string:

var myObj = {};
myObj["myProp1"] = "value1";
myObj["myProp2"] = "value2";

What's used in the brackets can be a variable, or any kind of expression that results in a string:

var myObj = {};
var prop1 = "myProp1";
myObj[prop1] = "value1";
myObj["myProp" + 2] = "value2";

If you use a number as property name, it will automatically be converted to a string, so these have the same result:

myObj[2010] = "value";
myObj["2010"] = "value";

You can also use an object literal to set the values:

var myObj = { myProp1: "value1", myProp2: "value2" };

(Note that {} is also an object literal, only without properties.)

Using the prototype of an object is only useful if you have named object types (or otherwise assign a prototype to the object). When you create objects using an object literal each object has it's own prototype, so putting anything in the prototype has the same effect as putting it in the object.


问:
Boolean expression using Spring Profiles
We have the following annotation for a Component in a project:

```<code>@Profile("!department")
</code>```

This means run this component when department is not an active profile.
However, can you do something like:

@Profile("!department" || "datamigration" ) OR

```<code> @Profile(["!department","datamigration"] )
</code>```

Basically I want a way to be able to say, use this Component if:

profile is NOT department

OR

profile is datamigration

答:
This should be enough  </p>

```<code>@Profile({"!department","datamigration"})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We have the following annotation for a Component in a project:

@Profile("!department")

This means run this component when department is not an active profile.
However, can you do something like:

@Profile("!department" || "datamigration" ) OR

 @Profile(["!department","datamigration"] )

Basically I want a way to be able to say, use this Component if:

profile is NOT department

OR

profile is datamigration

Body:
This should be enough

@Profile({"!department","datamigration"})


问:
Hystrix Javanica : Call always returning result from fallback method.(java web app without spring)
I am trying to integrate Hystrix javanica into my existing java EJB web application and facing 2 issues with running it.

When I try to invoke following service it always returns response from fallback method and I see that the Throwable object in fallback method has "com.netflix.hystrix.exception.HystrixTimeoutException" exception.

Each time this service is triggered, HystrixCommad and fallback methods are called multiple times around 50 times.

Can anyone suggest me with any inputs? Am I missing any configuration?

I am including following libraries in my project.
project libraries

I have setup my aspect file as follows:

```<code><aspectj>
 <weaver options="-verbose -showWeaveInfo"></weaver>
 <aspects>
    <aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
 </aspects>
</aspectj>
</code>```

Here is my config.properties file in META-INF/config.properties

```<code>hystrix.command.default.execution.timeout.enabled=false
</code>```

Here is my rest service file

```<code>@Path("/hystrix")
public class HystrixService {

 @GET
 @Path("clusterName")
 @Produces({ MediaType.APPLICATION_JSON })
 public Response getClusterName(@QueryParam("id") int id) {
    ClusterCmdBean clusterCmdBean = new ClusterCmdBean();
    String result = clusterCmdBean.getClusterNameForId(id);
    return Response.ok(result).build();
 }
}
</code>```

Here is my bean class

```<code>public class ClusterCmdBean {

 @HystrixCommand(groupKey = "ClusterCmdBeanGroup", commandKey = "getClusterNameForId", fallbackMethod = "defaultClusterName")
 public String getClusterNameForId(int id) {
    if (id > 0) {
        return "cluster"+id;
    } else {
        throw new RuntimeException("command failed");
    }
 }

 public String defaultClusterName(int id, Throwable e) {
    return "No cluster - returned from fallback:" + e.getMessage();
 }
}
</code>```

Thanks for the help.

答:
If you want to ensure you are setting the property, you can do that explicitly in the circuit annotation itself:

```<code>@HystrixCommand(commandProperties = {
    @HystrixProperty(name = "execution.timeout.enabled", value = "false")
})
</code>```

I would only recommend this for debugging purposes though.

Something that jumps out to me is that Javanica uses AspectJ AOP, which I have never seen work with new MyBean() before. I've always have to use @Autowired with Spring or similar to allow proxying. This could well just be something that is new to me though.
If you set a breakpoint inside the getClusterNameForId can you see in the stack trace that its being called via reflection (which it should be AFAIK)?

Note you can remove commandKey as this will default to the method name. Personally I would also remove groupKey and let it default to the class name.

Body:
I am trying to integrate Hystrix javanica into my existing java EJB web application and facing 2 issues with running it.

When I try to invoke following service it always returns response from fallback method and I see that the Throwable object in fallback method has "com.netflix.hystrix.exception.HystrixTimeoutException" exception.

Each time this service is triggered, HystrixCommad and fallback methods are called multiple times around 50 times.

Can anyone suggest me with any inputs? Am I missing any configuration?

I am including following libraries in my project.
project libraries

I have setup my aspect file as follows:

<aspectj>
 <weaver options="-verbose -showWeaveInfo"></weaver>
 <aspects>
    <aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
 </aspects>
</aspectj>

Here is my config.properties file in META-INF/config.properties

hystrix.command.default.execution.timeout.enabled=false

Here is my rest service file

@Path("/hystrix")
public class HystrixService {

 @GET
 @Path("clusterName")
 @Produces({ MediaType.APPLICATION_JSON })
 public Response getClusterName(@QueryParam("id") int id) {
    ClusterCmdBean clusterCmdBean = new ClusterCmdBean();
    String result = clusterCmdBean.getClusterNameForId(id);
    return Response.ok(result).build();
 }
}

Here is my bean class

public class ClusterCmdBean {

 @HystrixCommand(groupKey = "ClusterCmdBeanGroup", commandKey = "getClusterNameForId", fallbackMethod = "defaultClusterName")
 public String getClusterNameForId(int id) {
    if (id > 0) {
        return "cluster"+id;
    } else {
        throw new RuntimeException("command failed");
    }
 }

 public String defaultClusterName(int id, Throwable e) {
    return "No cluster - returned from fallback:" + e.getMessage();
 }
}

Thanks for the help.

Body:
If you want to ensure you are setting the property, you can do that explicitly in the circuit annotation itself:

@HystrixCommand(commandProperties = {
    @HystrixProperty(name = "execution.timeout.enabled", value = "false")
})

I would only recommend this for debugging purposes though.

Something that jumps out to me is that Javanica uses AspectJ AOP, which I have never seen work with new MyBean() before. I've always have to use @Autowired with Spring or similar to allow proxying. This could well just be something that is new to me though.
If you set a breakpoint inside the getClusterNameForId can you see in the stack trace that its being called via reflection (which it should be AFAIK)?

Note you can remove commandKey as this will default to the method name. Personally I would also remove groupKey and let it default to the class name.


问:
bash : cd : too many arguments
if i need to go to my directory named as"exception handling" then i write (cd exception handling) but it gives error too many arguments</p>

答:
Use quotes:

```<code>cd "new folder"
</code>```

or escape the space:

```<code>cd new\ folder
</code>```

(That being said, cd does not open a file but changes the working directory.)

ContentLicense: CC BY-SA 4.0

Title: bash : cd : too many arguments

Body:
Use quotes:

cd "new folder"

or escape the space:

cd new\ folder

(That being said, cd does not open a file but changes the working directory.)


问:
PowerShell Get-Content with basic manipulations so slow
I am merging a lot of large CSV files, e.g. while skipping the leading junk and appending the filename to each line:

```<code>Get-ChildItem . | Where Name -match "Q[0-4]20[0-1][0-9].csv" |
Foreach-Object {
    $file = $_.BaseName
    Get-Content $_.FullName | select-object -skip 3 | % {
        "$_,${file}" | Out-File -Append temp.csv -Encoding ASCII
    }
}
</code>```

In PowerShell this is incredibly slow even on an i7/16GB machine (~5 megabyte/minute).  Can I make it more efficient or should I just switch to e.g. Python?

答:
To avoid -Append to ruin the performance of your script you could use a buffer array variable:

```<code># Initialize buffer
$csvBuffer = @()

Get-ChildItem *.csv | Foreach-Object {
    $file = $_.BaseName
    $content = Get-Content $_.FullName | Select-Object -Skip 3 | %{
        "$_,${file}"
    }

    # Populate buffer
    $csvBuffer += $content

    # Write buffer to disk if it contains 5000 lines or more
    $csvBufferCount = $csvBuffer | Measure-Object | Select-Object -ExpandProperty Count
    if( $csvBufferCount -ge 5000 )
    {
        $csvBuffer | Out-File -Path temp.csv -Encoding ASCII -Append
        $csvBuffer = @()
    }
}

# Important : empty the buffer remainder
if( $csvBufferCount -gt 0 )
{
    $csvBuffer | Out-File -Path temp.csv -Encoding ASCII -Append
    $csvBuffer = @()
}
</code>```

Body:
I am merging a lot of large CSV files, e.g. while skipping the leading junk and appending the filename to each line:

Get-ChildItem . | Where Name -match "Q[0-4]20[0-1][0-9].csv" |
Foreach-Object {
    $file = $_.BaseName
    Get-Content $_.FullName | select-object -skip 3 | % {
        "$_,${file}" | Out-File -Append temp.csv -Encoding ASCII
    }
}

In PowerShell this is incredibly slow even on an i7/16GB machine (~5 megabyte/minute).  Can I make it more efficient or should I just switch to e.g. Python?

Body:
To avoid -Append to ruin the performance of your script you could use a buffer array variable:

# Initialize buffer
$csvBuffer = @()

Get-ChildItem *.csv | Foreach-Object {
    $file = $_.BaseName
    $content = Get-Content $_.FullName | Select-Object -Skip 3 | %{
        "$_,${file}"
    }

    # Populate buffer
    $csvBuffer += $content

    # Write buffer to disk if it contains 5000 lines or more
    $csvBufferCount = $csvBuffer | Measure-Object | Select-Object -ExpandProperty Count
    if( $csvBufferCount -ge 5000 )
    {
        $csvBuffer | Out-File -Path temp.csv -Encoding ASCII -Append
        $csvBuffer = @()
    }
}

# Important : empty the buffer remainder
if( $csvBufferCount -gt 0 )
{
    $csvBuffer | Out-File -Path temp.csv -Encoding ASCII -Append
    $csvBuffer = @()
}


问:
byte array (string) to string javascript
I have a model which has a bytearray as a property,

```<code>public byte[] bytearraytest{ get; set; }
</code>```

when I get this model via javascript GET request it is a string.

```<code>tgwBAQ==
</code>```

How can i decode it now ?

答:
The string in javascript is a Base64 string.
You have to do a Base64 Decode in the javascript to access de bytes.
Try this: https://www.w3schools.com/jsref/met_win_atob.asp</p>

Body:
I have a model which has a bytearray as a property,

public byte[] bytearraytest{ get; set; }

when I get this model via javascript GET request it is a string.

tgwBAQ==

How can i decode it now ?


问:
Distributed Erlang: multicall exceeds requested timeout
We use distributed erlang cluster and now I tests it in case of net splits.

To get information from all nodes of the cluster I use gen_server:multicall/4 with defined timeout. What I need is to get information from available nodes as soon as possible. So timeout is not too big (about 3000 ms).
Here call example:

```<code>Timeout = 3000
Nodes = AllConfiguredNodes
gen_server:multi_call(Nodes, broker, get_score, Timeout)
</code>```

I expect that this call returns result in Timeout ms. But in case of net split it does not. It waits approx. 8 seconds.

What I found that multi_call request is halted for additional 5 seconds in call erlang:monitor(process, {Name, Node}) before sending request.

I really do not care that some node do not reply or busy or not available, I can use any other but with this halting I forced to wait until Erlang VM
try to establish new connection to dead/not available node.

The question is: do you know solution that can prevent this halting? Or may be another RPC that suitable for my situation.

答:
My solution of the problem.

I've made my own implementation of multicall that uses gen_server:call
Basic idea is to call all nodes with gen_server:call() in separate process. And collect result of these calls. Collection is made by receiving messages from mailbox of calling process.

To control timeout I calculate deadline when timeout expired and then use it as reference point to calculate timeout for after in receive.

Implementation

Main function is:

```<code>multicall(Nodes, Name, Req, Timeout) ->
    Refs = lists:map(fun(Node) -> call_node(Node, Name, Req, Timeout) end, Nodes),
    Results = read_all(Timeout, Refs),
    PosResults = [ { Node, Result } || { ok, { ok, { Node, Result } } } <- Results ],
    { PosResults, calc_bad_nodes(Nodes, PosResults) }.
</code>```

Idea here is to call all nodes and wait for all results within one Timeout.

Calling one node is performed from spawned process. It catches exits that used by gen_server:call in case of error.

```<code>call_node(Node, Name, Req, Timeout) ->
    Ref = make_ref(),
    Self = self(),
    spawn_link(fun() ->
                       try
                           Result = gen_server:call({Name,Node},Req,Timeout),
                           Self ! { Ref, { ok, { Node, Result } } }
                       catch
                           exit:Exit ->
                               Self ! { Ref, { error, { 'EXIT', Exit } } }
                       end
               end),
    Ref.
</code>```

Bad nodes are calculated as those that are not respond within Timout

```<code>calc_bad_nodes(Nodes, PosResults) ->
    { GoodNodes, _ } = lists:unzip(PosResults),
    [ BadNode || BadNode <- Nodes, not lists:member(BadNode, GoodNodes) ].
</code>```

Results are collected by reading mailbox with Timeout

```<code>read_all(ReadList, Timeout) ->
    Now = erlang:monotonic_time(millisecond),
    Deadline = Now + Timeout,
    read_all_impl(ReadList, Deadline, []).
</code>```

Implementation reads until Deadline does not occur

```<code>read_all_impl([], _, Results) ->
    lists:reverse(Results);
read_all_impl([ W | Rest ], expired, Results) ->
    R = read(0, W),
    read_all_impl(Rest, expired, [R | Results ]);
read_all_impl([ W | Rest ] = L, Deadline, Results) ->
    Now = erlang:monotonic_time(millisecond),
    case Deadline - Now of
        Timeout when Timeout > 0 ->
            R = read(Timeout, W),
            case R of
                { ok, _ } ->
                    read_all_impl(Rest, Deadline, [ R | Results ]);
                { error, { read_timeout, _ } } ->
                    read_all_impl(Rest, expired, [ R | Results ])
            end;
        Timeout when Timeout =< 0 ->
            read_all_impl(L, expired, Results)
    end.
</code>```

One single read is just receive from mailbox with Timeout.

```<code>read(Timeout, Ref) ->
    receive
        { Ref, Result } ->
            { ok, Result }
    after Timeout ->
            { error, { read_timeout, Timeout } }
    end.
</code>```

Further improvements:

rpc module spawns separate process to avoid garbage of late answers. So It will be useful to do the same in this multicall function

infinity timeout may be handled in obvious way

Body:
We use distributed erlang cluster and now I tests it in case of net splits.

To get information from all nodes of the cluster I use gen_server:multicall/4 with defined timeout. What I need is to get information from available nodes as soon as possible. So timeout is not too big (about 3000 ms).
Here call example:

Timeout = 3000
Nodes = AllConfiguredNodes
gen_server:multi_call(Nodes, broker, get_score, Timeout)

I expect that this call returns result in Timeout ms. But in case of net split it does not. It waits approx. 8 seconds.

What I found that multi_call request is halted for additional 5 seconds in call erlang:monitor(process, {Name, Node}) before sending request.

I really do not care that some node do not reply or busy or not available, I can use any other but with this halting I forced to wait until Erlang VM
try to establish new connection to dead/not available node.

The question is: do you know solution that can prevent this halting? Or may be another RPC that suitable for my situation.

Body:
My solution of the problem.

I've made my own implementation of multicall that uses gen_server:call
Basic idea is to call all nodes with gen_server:call() in separate process. And collect result of these calls. Collection is made by receiving messages from mailbox of calling process.

To control timeout I calculate deadline when timeout expired and then use it as reference point to calculate timeout for after in receive.

Implementation

Main function is:

multicall(Nodes, Name, Req, Timeout) ->
    Refs = lists:map(fun(Node) -> call_node(Node, Name, Req, Timeout) end, Nodes),
    Results = read_all(Timeout, Refs),
    PosResults = [ { Node, Result } || { ok, { ok, { Node, Result } } } <- Results ],
    { PosResults, calc_bad_nodes(Nodes, PosResults) }.

Idea here is to call all nodes and wait for all results within one Timeout.

Calling one node is performed from spawned process. It catches exits that used by gen_server:call in case of error.

call_node(Node, Name, Req, Timeout) ->
    Ref = make_ref(),
    Self = self(),
    spawn_link(fun() ->
                       try
                           Result = gen_server:call({Name,Node},Req,Timeout),
                           Self ! { Ref, { ok, { Node, Result } } }
                       catch
                           exit:Exit ->
                               Self ! { Ref, { error, { 'EXIT', Exit } } }
                       end
               end),
    Ref.

Bad nodes are calculated as those that are not respond within Timout

calc_bad_nodes(Nodes, PosResults) ->
    { GoodNodes, _ } = lists:unzip(PosResults),
    [ BadNode || BadNode <- Nodes, not lists:member(BadNode, GoodNodes) ].

Results are collected by reading mailbox with Timeout

read_all(ReadList, Timeout) ->
    Now = erlang:monotonic_time(millisecond),
    Deadline = Now + Timeout,
    read_all_impl(ReadList, Deadline, []).

Implementation reads until Deadline does not occur

read_all_impl([], _, Results) ->
    lists:reverse(Results);
read_all_impl([ W | Rest ], expired, Results) ->
    R = read(0, W),
    read_all_impl(Rest, expired, [R | Results ]);
read_all_impl([ W | Rest ] = L, Deadline, Results) ->
    Now = erlang:monotonic_time(millisecond),
    case Deadline - Now of
        Timeout when Timeout > 0 ->
            R = read(Timeout, W),
            case R of
                { ok, _ } ->
                    read_all_impl(Rest, Deadline, [ R | Results ]);
                { error, { read_timeout, _ } } ->
                    read_all_impl(Rest, expired, [ R | Results ])
            end;
        Timeout when Timeout =< 0 ->
            read_all_impl(L, expired, Results)
    end.

One single read is just receive from mailbox with Timeout.

read(Timeout, Ref) ->
    receive
        { Ref, Result } ->
            { ok, Result }
    after Timeout ->
            { error, { read_timeout, Timeout } }
    end.

Further improvements:

rpc module spawns separate process to avoid garbage of late answers. So It will be useful to do the same in this multicall function

infinity timeout may be handled in obvious way


问:
Information Management Policy in SharePoint
An obscure puzzle, but it's driving me absolutely nuts:

I'm creating a custom Information Management Policy in MOSS. I've implemented IPolicyFeature, and my policy feature happily registers itself by configuring a new SPItemEventReceiver. All new items in my library fire the events as they should, and it all works fine.

IPolicyFeature also has a method ProcessListItem, which is supposed to retroactively apply the policy to items that were already in the library (at least, it's supposed to do that for as long as it keeps returning true). Except it doesn't. It only applies the policy to the first item in the library, and I have absolutely no idea why.

It doesn't seem to be throwing an exception, and it really does return true from processing that first item, and I can't think what else to look at. Anyone?

Edit: Cory's answer, below, set me on the right track. Something else was indeed failing -- I didn't find out what, since my windbg-fu isn't what it should be, but I suspect it was something like "modifying a collection while it's being iterated over". My code was modifying the SPListItem that's passed into ProcessListItem, and then calling SystemUpdate on it; as soon as I changed the code so that it created its own variable (pointing at the exact same SPListItem) and used that, the problem went away...

答: Some nice ideas there, thanks. The Visual Studio debugger wasn't showing an exception (and I've wrapped everything in try/catch blocks just in case), but I hadn't thought of trying Windbg...</p>

OwnerDisplayName: Matt Bishop

LastEditorDisplayName: Matt Bishop


问:
Converting PHP Api call example code to a C# RestSharp Api call w/ OAuth 1.0
I am calling a 3rd party API which provided me with a PHP code example on how to call their API.  I do not know PHP but it looks pretty straight forward and readable for me to try and build a similar .NET solution. The PHP example below is doing a Post but in my C# example I will be doing a Get. I have mocked up the PHP example with some dummy values.

```<code>$params = array();
$params['assertion_id'] = "b57936e4-6cea-46f4-a897-c7b3a6f01147"; // Example Assertion ID.
$params['product_id'] = "product001";
$params['product_name'] = "Useless Product";
$params['price'] = "1.99";

// Generate Signature Base String.
$params['api_key'] = "526587410g44p9kk8f7h2bb2zf3365va"; // Example Api Key.
$params['timestamp'] = "1510760624"; // Example Timestamp.
$params['nonce'] = "uilp37xh"; // Example Nonce.
ksort($params);

$url = "https://someurl.com/api/product";
$signature_base_string = 'POST&'.urlencode($url).'&'.http_build_query($params);

// Encrypt signature base string for signature.
$secret_key = "DlKST1adTpoWELS8TjjBc1pFATdlGA8qHUNEaq9MOSAUT648AlAvzK4EEC7="; // Example Secret Key.
$signature = base64_encode(hash_hmac('sha1', $signature_base_string, base64_decode($secret_key), true));
$params['signature'] = $signature;

// Send Request.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, count($params));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
</code>```

Here is the C# code example that I have constructed thus far utilizing RestSharp. The nonce, timestamp, and signature adhere to the OAuth 1.0 specification but I am not sure that I have handled that part correctly? I cannot provide the real values to actually test the Api call but know the code does work in the sense that it does get a response back from the 3rd party Api. However, the response states that the parameters are missing...

```<code>public class ProductApiRequest
{
    private string _api;
    private string _apiKey;
    private string _apiSecretKey;

    public ProductApiRequest()
    {
        _api = "https://someurl.com/api/";
        _apiKey = "526587410g44p9kk8f7h2bb2zf3365va";
        _apiSecretKey = "DlKST1adTpoWELS8TjjBc1pFATdlGA8qHUNEaq9MOSAUT648AlAvzK4EEC7=";
    }

    public class Product
    {
        public Guid assertion_id { get; set; }
        public String api_key { get; set; }
        public string product_id { get; set; }
        public string product_name { get; set; }
        public string price { get; set; }
        public string timestamp { get; set; }
        public string nonce { get; set; }
        public string signature { get; set; }
    }

    public string getProduct()
    {
        try
        {
            Product oProduct = new Product();

            oProduct.assertion_id = Guid.NewGuid();
            oProduct.api_key = _apiKey;
            oProduct.product_id = "product001";
            oProduct.product_name = "Useless Product";
            oProduct.price = "1.99";
            oProduct.timestamp = GenerateTimeStamp();
            oProduct.nonce = GenerateNonce();
            oProduct.signature = GenerateSignature(oProduct.nonce, oProduct.timestamp, _apiSecretKey);

            var path = "product";
            dynamic request = new RestSharp.RestRequest(path, RestSharp.Method.GET);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.JsonSerializer = new RestSharp.Serializers.JsonSerializer();
            request.AddJsonBody(oProduct);

            var client = new RestSharp.RestClient(_api);
            var response = client.Execute(request);

            return "Return something.";
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }

    public string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        string timeStamp = ts.TotalSeconds.ToString();
        timeStamp = timeStamp.Substring(0, timeStamp.IndexOf("."));
        return timeStamp;
    }

    public string GenerateNonce()
    {
        var _random = new Random();
        var sb = new StringBuilder();
        for (int i = 0; i < 8; i++)
        {
            int g = _random.Next(3);
            switch (g)
            {
                case 0:
                    // lowercase alpha
                    sb.Append((char)(_random.Next(26) + 97), 1);
                    break;
                default:
                    // numeric digits
                    sb.Append((char)(_random.Next(10) + 48), 1);
                    break;
            }
        }
        return sb.ToString();
    }

    public string GenerateSignature(string nonce, string timestamp, string apisecretkey)
    {
        var encoder = new UTF8Encoding();
        var hasher = new System.Security.Cryptography.HMACSHA1();
        var vals = string.Concat(nonce, timestamp, apisecretkey);
        byte[] hashedDataBytes = hasher.ComputeHash(encoder.GetBytes(vals));
        return Convert.ToBase64String(hashedDataBytes);
    }
}
</code>```

Any help converting the PHP solution to a C# solution would be appreciated!

答:
I did not know PHP but have managed to figured out the solution! \m/ Metal \m/</p>

```<code>public class ProductApiRequest
{
    private string _api;
    private string _apiKey;
    private string _apiSecretKey;
    private string _resource;

    public ProductApiRequest()
    {
        _api = "https://someurl.com/api/";
        _apiKey = "526587410g44p9kk8f7h2bb2zf3365va";
        _apiSecretKey = "DlKST1adTpoWELS8TjjBc1pFATdlGA8qHUNEaq9MOSAUT648AlAvzK4EEC7=";
        _resource = "products";
    }

    public class Product
    {
        public Guid assertion_id { get; set; }
        public String api_key { get; set; }
        public string product_id { get; set; }
        public string product_name { get; set; }
        public string price { get; set; }
        public string timestamp { get; set; }
        public string nonce { get; set; }
        public string signature { get; set; }
    }

    public string getProduct()
    {
        Product oProduct = new Product();

        oProduct.assertion_id = Guid.NewGuid();
        oProduct.api_key = _apiKey;
        oProduct.product_id = "product001";
        oProduct.product_name = "Useless Product";
        oProduct.price = "1.99";
        oProduct.timestamp = GenerateTimeStamp();
        oProduct.nonce = GenerateNonce();

        // Create Signature Base String.
        string apiEncoded = Uri.EscapeDataString(_api + _resource);
        string strSignatureBase = "GET&" + apiEncoded + "&api_key=" + oProduct.api_key + "&product_id=" + oProduct.product_id + "&product_name=" + oProduct.product_name + "&price=" + oProduct.price + "&nonce=" + oProduct.nonce + "&timestamp=" + oProduct.timestamp;

        // Create Signature for OAuth 1.0
        oProduct.signature = GenerateSignature(strSignatureBase, _apiSecretKey);

        var client = new RestClient(_api + _resource + "?assertion_id=" + oProduct.assertion_id + "&api_key=" + oProduct.api_key + "&product_id=" + oProduct.product_id + "&product_name=" + oProduct.product_name + "&price=" + oProduct.price + "&timestamp=" + oProduct.timestamp + "&nonce=" + oProduct.nonce + "&signature=" + HttpUtility.UrlEncode(oProduct.signature));
        var request = new RestRequest(Method.GET);
        IRestResponse response = client.Execute(request);

        return "Return whatever you want.";
    }

    public string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        string timeStamp = ts.TotalSeconds.ToString();
        timeStamp = timeStamp.Substring(0, timeStamp.IndexOf("."));
        return timeStamp;
    }

    public string GenerateNonce()
    {
        var _random = new Random();
        var sb = new StringBuilder();
        for (int i = 0; i < 8; i++)
        {
            int g = _random.Next(3);
            switch (g)
            {
                case 0:
                    // lowercase alpha
                    sb.Append((char)(_random.Next(26) + 97), 1);
                    break;
                default:
                    // numeric digits
                    sb.Append((char)(_random.Next(10) + 48), 1);
                    break;
            }
        }
        return sb.ToString();
    }

    public string GenerateSignature(string strSignatureBase, string strSecretKey)
    {
        byte[] signatureBaseBytes = Encoding.UTF8.GetBytes(strSignatureBase);
        byte[] secretKeyDecodedBytes = Convert.FromBase64String(strSecretKey); // Decode Secret Key.

        var encoder = new UTF8Encoding();
        var hasher = new HMACSHA1(secretKeyDecodedBytes);

        byte[] hashedDataBytes = hasher.ComputeHash(signatureBaseBytes);

        return Convert.ToBase64String(hashedDataBytes);
    }
}
</code>```

Body:
I am calling a 3rd party API which provided me with a PHP code example on how to call their API.  I do not know PHP but it looks pretty straight forward and readable for me to try and build a similar .NET solution. The PHP example below is doing a Post but in my C# example I will be doing a Get. I have mocked up the PHP example with some dummy values.

$params = array();
$params['assertion_id'] = "b57936e4-6cea-46f4-a897-c7b3a6f01147"; // Example Assertion ID.
$params['product_id'] = "product001";
$params['product_name'] = "Useless Product";
$params['price'] = "1.99";

// Generate Signature Base String.
$params['api_key'] = "526587410g44p9kk8f7h2bb2zf3365va"; // Example Api Key.
$params['timestamp'] = "1510760624"; // Example Timestamp.
$params['nonce'] = "uilp37xh"; // Example Nonce.
ksort($params);

$url = "https://someurl.com/api/product";
$signature_base_string = 'POST&'.urlencode($url).'&'.http_build_query($params);

// Encrypt signature base string for signature.
$secret_key = "DlKST1adTpoWELS8TjjBc1pFATdlGA8qHUNEaq9MOSAUT648AlAvzK4EEC7="; // Example Secret Key.
$signature = base64_encode(hash_hmac('sha1', $signature_base_string, base64_decode($secret_key), true));
$params['signature'] = $signature;

// Send Request.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, count($params));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);

Here is the C# code example that I have constructed thus far utilizing RestSharp. The nonce, timestamp, and signature adhere to the OAuth 1.0 specification but I am not sure that I have handled that part correctly? I cannot provide the real values to actually test the Api call but know the code does work in the sense that it does get a response back from the 3rd party Api. However, the response states that the parameters are missing...

public class ProductApiRequest
{
    private string _api;
    private string _apiKey;
    private string _apiSecretKey;

    public ProductApiRequest()
    {
        _api = "https://someurl.com/api/";
        _apiKey = "526587410g44p9kk8f7h2bb2zf3365va";
        _apiSecretKey = "DlKST1adTpoWELS8TjjBc1pFATdlGA8qHUNEaq9MOSAUT648AlAvzK4EEC7=";
    }

    public class Product
    {
        public Guid assertion_id { get; set; }
        public String api_key { get; set; }
        public string product_id { get; set; }
        public string product_name { get; set; }
        public string price { get; set; }
        public string timestamp { get; set; }
        public string nonce { get; set; }
        public string signature { get; set; }
    }

    public string getProduct()
    {
        try
        {
            Product oProduct = new Product();

            oProduct.assertion_id = Guid.NewGuid();
            oProduct.api_key = _apiKey;
            oProduct.product_id = "product001";
            oProduct.product_name = "Useless Product";
            oProduct.price = "1.99";
            oProduct.timestamp = GenerateTimeStamp();
            oProduct.nonce = GenerateNonce();
            oProduct.signature = GenerateSignature(oProduct.nonce, oProduct.timestamp, _apiSecretKey);

            var path = "product";
            dynamic request = new RestSharp.RestRequest(path, RestSharp.Method.GET);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.JsonSerializer = new RestSharp.Serializers.JsonSerializer();
            request.AddJsonBody(oProduct);

            var client = new RestSharp.RestClient(_api);
            var response = client.Execute(request);

            return "Return something.";
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }

    public string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        string timeStamp = ts.TotalSeconds.ToString();
        timeStamp = timeStamp.Substring(0, timeStamp.IndexOf("."));
        return timeStamp;
    }

    public string GenerateNonce()
    {
        var _random = new Random();
        var sb = new StringBuilder();
        for (int i = 0; i < 8; i++)
        {
            int g = _random.Next(3);
            switch (g)
            {
                case 0:
                    // lowercase alpha
                    sb.Append((char)(_random.Next(26) + 97), 1);
                    break;
                default:
                    // numeric digits
                    sb.Append((char)(_random.Next(10) + 48), 1);
                    break;
            }
        }
        return sb.ToString();
    }

    public string GenerateSignature(string nonce, string timestamp, string apisecretkey)
    {
        var encoder = new UTF8Encoding();
        var hasher = new System.Security.Cryptography.HMACSHA1();
        var vals = string.Concat(nonce, timestamp, apisecretkey);
        byte[] hashedDataBytes = hasher.ComputeHash(encoder.GetBytes(vals));
        return Convert.ToBase64String(hashedDataBytes);
    }
}

Any help converting the PHP solution to a C# solution would be appreciated!

Body:
I did not know PHP but have managed to figured out the solution! \m/ Metal \m/

public class ProductApiRequest
{
    private string _api;
    private string _apiKey;
    private string _apiSecretKey;
    private string _resource;

    public ProductApiRequest()
    {
        _api = "https://someurl.com/api/";
        _apiKey = "526587410g44p9kk8f7h2bb2zf3365va";
        _apiSecretKey = "DlKST1adTpoWELS8TjjBc1pFATdlGA8qHUNEaq9MOSAUT648AlAvzK4EEC7=";
        _resource = "products";
    }

    public class Product
    {
        public Guid assertion_id { get; set; }
        public String api_key { get; set; }
        public string product_id { get; set; }
        public string product_name { get; set; }
        public string price { get; set; }
        public string timestamp { get; set; }
        public string nonce { get; set; }
        public string signature { get; set; }
    }

    public string getProduct()
    {
        Product oProduct = new Product();

        oProduct.assertion_id = Guid.NewGuid();
        oProduct.api_key = _apiKey;
        oProduct.product_id = "product001";
        oProduct.product_name = "Useless Product";
        oProduct.price = "1.99";
        oProduct.timestamp = GenerateTimeStamp();
        oProduct.nonce = GenerateNonce();

        // Create Signature Base String.
        string apiEncoded = Uri.EscapeDataString(_api + _resource);
        string strSignatureBase = "GET&" + apiEncoded + "&api_key=" + oProduct.api_key + "&product_id=" + oProduct.product_id + "&product_name=" + oProduct.product_name + "&price=" + oProduct.price + "&nonce=" + oProduct.nonce + "&timestamp=" + oProduct.timestamp;

        // Create Signature for OAuth 1.0
        oProduct.signature = GenerateSignature(strSignatureBase, _apiSecretKey);

        var client = new RestClient(_api + _resource + "?assertion_id=" + oProduct.assertion_id + "&api_key=" + oProduct.api_key + "&product_id=" + oProduct.product_id + "&product_name=" + oProduct.product_name + "&price=" + oProduct.price + "&timestamp=" + oProduct.timestamp + "&nonce=" + oProduct.nonce + "&signature=" + HttpUtility.UrlEncode(oProduct.signature));
        var request = new RestRequest(Method.GET);
        IRestResponse response = client.Execute(request);

        return "Return whatever you want.";
    }

    public string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        string timeStamp = ts.TotalSeconds.ToString();
        timeStamp = timeStamp.Substring(0, timeStamp.IndexOf("."));
        return timeStamp;
    }

    public string GenerateNonce()
    {
        var _random = new Random();
        var sb = new StringBuilder();
        for (int i = 0; i < 8; i++)
        {
            int g = _random.Next(3);
            switch (g)
            {
                case 0:
                    // lowercase alpha
                    sb.Append((char)(_random.Next(26) + 97), 1);
                    break;
                default:
                    // numeric digits
                    sb.Append((char)(_random.Next(10) + 48), 1);
                    break;
            }
        }
        return sb.ToString();
    }

    public string GenerateSignature(string strSignatureBase, string strSecretKey)
    {
        byte[] signatureBaseBytes = Encoding.UTF8.GetBytes(strSignatureBase);
        byte[] secretKeyDecodedBytes = Convert.FromBase64String(strSecretKey); // Decode Secret Key.

        var encoder = new UTF8Encoding();
        var hasher = new HMACSHA1(secretKeyDecodedBytes);

        byte[] hashedDataBytes = hasher.ComputeHash(signatureBaseBytes);

        return Convert.ToBase64String(hashedDataBytes);
    }
}


问:
How to get current time in Swift?
I'm trying to get the current time, and I've done this so far:

```<code>    let date = NSDate()
    let calender = NSCalendar.currentCalendar()
    let components = calender.component([.Hour, .Minute], fromDate: date)
</code>```

And I then try to get the hour of the components

```<code>    let hour = components.hour
</code>```

This give me "Value of type "Int" has no member 'hour'". Any suggestions?

答:
swift 4</p>

```<code>let hh2 = (Calendar.current.component(.hour, from: Date()))
let mm2 = (Calendar.current.component(.minute, from: Date()))
let ss2 = (Calendar.current.component(.second, from: Date()))

print(hh2,":", mm2,":", ss2)

 output: ---> 9 : 10 : 55
</code>```

Title: How to get current time in Swift?

Body:
I'm trying to get the current time, and I've done this so far:

    let date = NSDate()
    let calender = NSCalendar.currentCalendar()
    let components = calender.component([.Hour, .Minute], fromDate: date)

And I then try to get the hour of the components

    let hour = components.hour

This give me "Value of type "Int" has no member 'hour'". Any suggestions?

Body:
swift 4

let hh2 = (Calendar.current.component(.hour, from: Date()))
let mm2 = (Calendar.current.component(.minute, from: Date()))
let ss2 = (Calendar.current.component(.second, from: Date()))

print(hh2,":", mm2,":", ss2)

 output: ---> 9 : 10 : 55


问:
jQuery validate giving error (.validate is not a function)
Hy all I am using jQuery validate plugin it was working fine suddenly it stopped working when I checked the console for any errors it was giving me this error

Uncaught TypeError: $(...).validate is not a function

I have read many forums but all the solutions are not working for me please someone help me out here is my code.

This is the head portion

```<code><head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/assets/css/bootstrap.min.css" media="all" />
    <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/assets/css/style.css" media="all" />
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>

    <?php wp_head(); ?>
</head>
</code>```

For the main body portion

```<code><script type="text/javascript">
$(document).ready(function () {
    $("#submit").click(function (e) {
        e.preventDefault();

        $('#addpro').validate();

        var form = $("#addpro");
        var itemm = $("#id_itemchoice").val();
        var itemmsize = $("#id_size").val();
        var itemmprice = $("#id_price").val();
        var wholesaleprice = $("#id_wholesale_price").val();
        var itemmdes = $("#id_description").val();
        var quantity = $("#id_quantity_received").val();

        if (itemm === "" || itemmsize === "" || itemmprice === "" || wholesaleprice === "") {
            $(".val-error, .error-message").show();
        } else {
            jQuery.ajax({
                type: 'POST',
                data: {action: 'insert_consultant_post', itemchoice: itemm, size: itemmsize, price: itemmprice, description: itemmdes, quantity: quantity},
                url: "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
                success: function (data) {
                    console.log(data);

                }
            });
        }
    });
});
</code>```

Please have a look at it and tell me what I am doing wrong. Thanks in advance

答:
Are you sure that you are using wp_enqueue_script() from WordPress?
Check the docs - https://developer.wordpress.org/reference/functions/wp_enqueue_script/

```<code>wp_enqueue_script()
</code>```

I think you can simplify your ajax post way more.
Check this fiddle - https://jsfiddle.net/ftr08w9L/

```<code>$.post()
</code>```

Ofcourse you would want to adjust the fiddle for your code. I've also added some comments to help you out.

Body:
Hy all I am using jQuery validate plugin it was working fine suddenly it stopped working when I checked the console for any errors it was giving me this error

Uncaught TypeError: $(...).validate is not a function

I have read many forums but all the solutions are not working for me please someone help me out here is my code.

This is the head portion

    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/assets/css/bootstrap.min.css" media="all" />
    <link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/assets/css/style.css" media="all" />
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />

    <?php wp_head(); ?>

For the main body portion

Body:
Are you sure that you are using wp_enqueue_script() from WordPress?
Check the docs - https://developer.wordpress.org/reference/functions/wp_enqueue_script/

wp_enqueue_script()

I think you can simplify your ajax post way more.
Check this fiddle - https://jsfiddle.net/ftr08w9L/

$.post()

Ofcourse you would want to adjust the fiddle for your code. I've also added some comments to help you out.


问:
Java String.compareTo - continue to compare even the characters are of different value at first
I know there is a method of String which allows me to compare two Strings, which is called compareTo. I was trying to write a modificated version of this method. My issue is that my method stops when a difference between 2 characters was found. For example:

```<code>public static int stringCompare(String s1, String s2) {
    int i  = 0, n1, n2;
    while(true)  {
        if (s1.length() <= i && s2.length() <= i) {
            return 0;
        } else if (s1.length() <= i) {
            return -s2.charAt(i);
        } else if (s2.length() <= i) {
            return s1.charAt(i);
        } else {
            n1 = s1.charAt(i);
            n2 = s2.charAt(i);
            if (n1 != n2) {
                i++;
                return n1 - n2;
            } else {
                i++;
            }
        }
    }
}
</code>```

My main looks like this:

```<code>    public static void main(String[] args) {
    String str1 = "AB";
    String str2 = "AA";
    System.out.print(stringCompare(str1, str2));
}
</code>```

The result of the comparison is 1, because the character 'B' is equal to 66 in the charset and 'A' is equal to 65 -> 66 - 65 = 1. That means the String str1 is greater then str2.

If I change the Strings and add one character more to both of them, the remaining characters after the character index 1, in my case 'A' and 'B', are not going to be compared.

Here is the updated main, which will give me the same result as the previous.

```<code>    public static void main(String[] args) {
    String str1 = "ABA";
    String str2 = "AAB";
    System.out.print(stringCompare(str1, str2));
}
</code>```

Even the value of both Strings is equal 0 ((65 + 66 + 65) - (65 + 65 + 66)) the result is 1 because the characters at index 2 of the Strings ('A' and 'B') will not be compared.

The instance method of Strings gives me the same result. Even when I use the method str.compareTo(str), the value of the comparison is 1.

Could anyone explain me how can I modify my function, so the other characters will be included in the comparison?

Thank you.

答:
iterate through the characters in the strings.
where they don't match, store the difference.
return the total difference at the end. </p>

Body:
I know there is a method of String which allows me to compare two Strings, which is called compareTo. I was trying to write a modificated version of this method. My issue is that my method stops when a difference between 2 characters was found. For example:

public static int stringCompare(String s1, String s2) {
    int i  = 0, n1, n2;
    while(true)  {
        if (s1.length() <= i && s2.length() <= i) {
            return 0;
        } else if (s1.length() <= i) {
            return -s2.charAt(i);
        } else if (s2.length() <= i) {
            return s1.charAt(i);
        } else {
            n1 = s1.charAt(i);
            n2 = s2.charAt(i);
            if (n1 != n2) {
                i++;
                return n1 - n2;
            } else {
                i++;
            }
        }
    }
}

My main looks like this:

    public static void main(String[] args) {
    String str1 = "AB";
    String str2 = "AA";
    System.out.print(stringCompare(str1, str2));
}

The result of the comparison is 1, because the character 'B' is equal to 66 in the charset and 'A' is equal to 65 -> 66 - 65 = 1. That means the String str1 is greater then str2.

If I change the Strings and add one character more to both of them, the remaining characters after the character index 1, in my case 'A' and 'B', are not going to be compared.

Here is the updated main, which will give me the same result as the previous.

    public static void main(String[] args) {
    String str1 = "ABA";
    String str2 = "AAB";
    System.out.print(stringCompare(str1, str2));
}

Even the value of both Strings is equal 0 ((65 + 66 + 65) - (65 + 65 + 66)) the result is 1 because the characters at index 2 of the Strings ('A' and 'B') will not be compared.

The instance method of Strings gives me the same result. Even when I use the method str.compareTo(str), the value of the comparison is 1.

Could anyone explain me how can I modify my function, so the other characters will be included in the comparison?

Thank you.


问:
Convert command line cURL to C cURL
I've never done any curl before so am in need of some help. I've tried to work this out from examples but cannot get my head around it!

I have a curl command that I can successfully run from a windows command line that index pdf file in Solr.

I would need to incorporate this curl command in a C clinet.

How can I translate this curl command so that it works in a C cURL client?

curl "http://localhost:8983/solr/update/extract?literal.id=doc2&uprefix=attr_&fmap.content=attr_content&commit=true"" -F "myfile=@doc.pdf"

答:
```<code>STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
TCHAR tempCmdLine[MAX_PATH];
_tcscpy_s(tempCmdLine, MAX_PATH, _T("curl.exe http://localhost:8983/solr/update/extract?literal.id=doc2&uprefix=attr_&fmap.content=attr_content&commit=true -F myfile=@doc.pdf"));
CreateProcess(NULL, tempCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
</code>```

You may want to check the return value of CreateProcess.

Title: Convert command line cURL to C cURL

Body:
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
TCHAR tempCmdLine[MAX_PATH];
_tcscpy_s(tempCmdLine, MAX_PATH, _T("curl.exe http://localhost:8983/solr/update/extract?literal.id=doc2&uprefix=attr_&fmap.content=attr_content&commit=true -F myfile=@doc.pdf"));
CreateProcess(NULL, tempCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

You may want to check the return value of CreateProcess.


问:
select combobox item by value C#
I have a combobox , bound to Datatable
and have the following properties:

```<code>cboCars.DisplayMember = "carLiscen";
cboCars.ValueMember = "carNo";
</code>```

How can I select the DisplayMember when I know the ValueMember ?

答:
You can search for the correct item and set it to that, very simple:

```<code>cbTEST.SelectedIndex = cbTEST.FindStringExact("your search string here");
</code>```

or select an item based on an ListViewItem:

```<code>cbTEST.SelectedIndex = cbTEST.FindStringExact(lvTEST.SelectedItems[0].SubItems[0].Text);
</code>```

thats it. very simple!

Title: select combobox item by value C#

Body:
I have a combobox , bound to Datatable
and have the following properties:

cboCars.DisplayMember = "carLiscen";
cboCars.ValueMember = "carNo";

How can I select the DisplayMember when I know the ValueMember ?

Body:
You can search for the correct item and set it to that, very simple:

cbTEST.SelectedIndex = cbTEST.FindStringExact("your search string here");

or select an item based on an ListViewItem:

cbTEST.SelectedIndex = cbTEST.FindStringExact(lvTEST.SelectedItems[0].SubItems[0].Text);

thats it. very simple!


答:
The issue is you're returning once you've found a difference

```<code>if(n1 != n2)
{
    i++;
    return n1 - n2;
}
</code>```

Instead, to keep on computing, you'll want a sum variable

```<code>int sum = 0; //at the start of the method
[...]
if(n1 != n2)
{
    i++;
    sum += n1 - n2;
}
[...]
return sum; //at the end of the method
</code>```

This can be done a bit cleaner

```<code>int stringCompare(String a, String b)
{
    int sum = 0;
    for(int i = 0; i < a.length() && i < b.length(); i++)
        sum += a.charAt(i) - b.charAt(i);
    return sum;
}
</code>```

If all characters are taken into account, you can either loop over the excess after

```<code>int stringCompare(String a, String b)
{
    int sum = 0;
    for(int i = 0; i < a.length() && i < b.length(); i++)
        sum += a.charAt(i) - b.charAt(i);
    for(int i = b.length(); i < a.length(); i++)
        sum += a.charAt(i);
    for(int i = a.length(); i < b.length(); i++)
        sum -= b.charAt(i);
    return sum;
}
</code>```

Or sum and subtract

```<code>int stringCompare(String a, String b)
{
    int sum = 0;
    for(int i = 0; i < a.length(); i++)
        sum += a.charAt(i);
    for(int i = 0; i < b.length(); i++)
        sum -= b.charAt(i);
    return sum;
}
</code>```

Title: Java String.compareTo - continue to compare even the characters are of different value at first

Body:
The issue is you're returning once you've found a difference

if(n1 != n2)
{
    i++;
    return n1 - n2;
}

Instead, to keep on computing, you'll want a sum variable

int sum = 0; //at the start of the method
[...]
if(n1 != n2)
{
    i++;
    sum += n1 - n2;
}
[...]
return sum; //at the end of the method

This can be done a bit cleaner

int stringCompare(String a, String b)
{
    int sum = 0;
    for(int i = 0; i < a.length() && i < b.length(); i++)
        sum += a.charAt(i) - b.charAt(i);
    return sum;
}

If all characters are taken into account, you can either loop over the excess after

int stringCompare(String a, String b)
{
    int sum = 0;
    for(int i = 0; i < a.length() && i < b.length(); i++)
        sum += a.charAt(i) - b.charAt(i);
    for(int i = b.length(); i < a.length(); i++)
        sum += a.charAt(i);
    for(int i = a.length(); i < b.length(); i++)
        sum -= b.charAt(i);
    return sum;
}

Or sum and subtract

int stringCompare(String a, String b)
{
    int sum = 0;
    for(int i = 0; i < a.length(); i++)
        sum += a.charAt(i);
    for(int i = 0; i < b.length(); i++)
        sum -= b.charAt(i);
    return sum;
}


问:
Change background color when button is active or selected
I have default  ._sideFolder  with background color of black

I want to change the bgcolor into blue when the button is selected

```<code>.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}
</code>```

The blue color only appears when clicked.

I am really confused with my pseudo CSS. Should I use JavaScript in here?

My JSFiddle

I want to display like in the picture on the left.

FYI: In my project I use ._sideFolder with background-color: red;

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._sideFolder {
  background-color: black;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

            Main Folder

            Second Folder

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <button class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <input hidden="hidden" name="offId" />
              <button class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

```

答:
May be a bit late. But this is how you can do it.

This approach says to remove the style from all of the divs and then add it to the clicked one

```<code>$('._tabFolder').click(function(){
 $("._tabFolder").css("cssText", "height: 40px; border-bottom: 1px groove; user-select: none; border-left: solid 0px;");

   $(this).css("cssText", "height: 40px; border-bottom: 1px groove; user-select: none; border-left: solid 5px;");
})
</code>```

Check here the Fiddle

Hope this helps

Body:
I have default  ._sideFolder  with background color of black

I want to change the bgcolor into blue when the button is selected

.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

The blue color only appears when clicked.

I am really confused with my pseudo CSS. Should I use JavaScript in here?

My JSFiddle

I want to display like in the picture on the left.

FYI: In my project I use ._sideFolder with background-color: red;

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});

._sideFolder {
  background-color: black;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

            Main Folder

            Second Folder

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <button class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <input hidden="hidden" name="offId" />
              <button class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

Body:
May be a bit late. But this is how you can do it.

This approach says to remove the style from all of the divs and then add it to the clicked one

$('._tabFolder').click(function(){
 $("._tabFolder").css("cssText", "height: 40px; border-bottom: 1px groove; user-select: none; border-left: solid 0px;");

   $(this).css("cssText", "height: 40px; border-bottom: 1px groove; user-select: none; border-left: solid 5px;");
})

Check here the Fiddle

Hope this helps


问:
Typo3 v8 how to insert current year into copyright from Bootstrap Package?
I'm looking for a way to set the Text of page.theme.copyright.text dynamic to

"© Company Name {year}"

What I have tried:

1.) Marker:

"© Company Name ###DATE###"

With Typoscript:

```<code>page.10 {
   marks.DATE= TEXT
   marks.DATE.data = date : Y
}
</code>```

2.) lib.copyright

TS:

```<code>lib.copyright = TEXT
lib.copyright.data = date:U
lib.copyright.strftime = %Y
lib.copyright.wrap= © |
temp.mainTemplate.subparts.copyright_date < lib.copyright
</code>```

3.) with TS Constant

TS Constant:

```<code>page.theme.copyright.text = © Company Name |
</code>```

TS:

```<code>page.10.variables.themeCopyrightText {
    value >
    data = date:U
    strftime = %Y
    noTrimWrap = |{$page.theme.copyright.text}|
}
</code>```

Nothing worked.

What I have:

Typo3 v8.7.8

Theme: Bootstrap Package 8.0.3

no clue how to solve this :)

答:
There already is a replacement going on (source).

Use the marker ###CURRENTYEAR###.

Body:
I'm looking for a way to set the Text of page.theme.copyright.text dynamic to

"© Company Name {year}"

What I have tried:

1.) Marker:

"© Company Name ###DATE###"

With Typoscript:

page.10 {
   marks.DATE= TEXT
   marks.DATE.data = date : Y
}

2.) lib.copyright

TS:

lib.copyright = TEXT
lib.copyright.data = date:U
lib.copyright.strftime = %Y
lib.copyright.wrap= © |
temp.mainTemplate.subparts.copyright_date < lib.copyright

3.) with TS Constant

TS Constant:

page.theme.copyright.text = © Company Name |

TS:

page.10.variables.themeCopyrightText {
    value >
    data = date:U
    strftime = %Y
    noTrimWrap = |{$page.theme.copyright.text}|
}

Nothing worked.

What I have:

Typo3 v8.7.8

Theme: Bootstrap Package 8.0.3

no clue how to solve this :)


问:
ReactNative Flatlist onEndReached not working
Im trying to call a function on onEndReached of a FlatList but it's not working.

I'm calling the this.state.pageNo at the end and it's not updating. I want to use this logic later in infinite scroll but not able to get it working now.

```<code> import React, { Component } from "react";
 import {
  View,
  Text,
  StyleSheet,
  Button,
  TouchableOpacity,
  FlatList,
  Alert
  } from "react-native";

 class InfiniteScrollRedux extends Component {
   constructor(props) {
      super(props);
      this.state = {
        loading: false,
        pageNo: 1,
        data: [
            { id: 1, name: "Name01" },
            { id: 2, name: "Name02" },
            { id: 3, name: "Name03" },
            { id: 4, name: "Name04" },
            { id: 5, name: "Name05" },
            { id: 6, name: "Name06" }
        ]
    };
}

myFunction = () => {
    this.setState({ pageNo: this.state.pageNo++ });
};

render() {
    return (
        <View>
            <FlatList
                data={this.state.data}
                renderItem={({ item }) => (
                    <View style={mystyle.mainCard}>
                        <Text style={mystyle.titleText}> {item.id} </Text>
                        <View style={{ marginTop: 200 }} />
                        <Text style={mystyle.nameText}> {item.name} </Text>
                    </View>
                )}
                keyExtractor={item => item.id}
                onEndReached={this.myFunction}
                onEndThreshold={0}
            />
            <Text style={{ margin: 20, padding: 20, fontSize: 20 }}>
                {this.state.pageNo}
            </Text>
        </View>
      );
   }
}

const mystyle = StyleSheet.create({
 mainCard: {
    backgroundColor: "#2F4F4F",
    marginBottom: 1,
    padding: 5
},
titleText: {
    fontSize: 20,
    color: "#F0FFFF"
},
nameText: {
    fontSize: 14,
    color: "#F0FFFF"
 }
 });

 export default InfiniteScrollRedux;
</code>```

答: There is an issue for that here: https://github.com/facebook/react-native/issues/14312. Looks like a lot of people are experiencing the same. There is a suggestion to change the onEndReachedThreshold to value bigger that 0, for example: 0.3.

Body:
Im trying to call a function on onEndReached of a FlatList but it's not working.

I'm calling the this.state.pageNo at the end and it's not updating. I want to use this logic later in infinite scroll but not able to get it working now.

 import React, { Component } from "react";
 import {
  View,
  Text,
  StyleSheet,
  Button,
  TouchableOpacity,
  FlatList,
  Alert
  } from "react-native";

 class InfiniteScrollRedux extends Component {
   constructor(props) {
      super(props);
      this.state = {
        loading: false,
        pageNo: 1,
        data: [
            { id: 1, name: "Name01" },
            { id: 2, name: "Name02" },
            { id: 3, name: "Name03" },
            { id: 4, name: "Name04" },
            { id: 5, name: "Name05" },
            { id: 6, name: "Name06" }
        ]
    };
}

myFunction = () => {
    this.setState({ pageNo: this.state.pageNo++ });
};

render() {
    return (
        <View>
            <FlatList
                data={this.state.data}
                renderItem={({ item }) => (
                    <View style={mystyle.mainCard}>
                        <Text style={mystyle.titleText}> {item.id} </Text>
                        <View style={{ marginTop: 200 }} />
                        <Text style={mystyle.nameText}> {item.name} </Text>
                    </View>
                )}
                keyExtractor={item => item.id}
                onEndReached={this.myFunction}
                onEndThreshold={0}
            />
            <Text style={{ margin: 20, padding: 20, fontSize: 20 }}>
                {this.state.pageNo}
            </Text>
        </View>
      );
   }
}

const mystyle = StyleSheet.create({
 mainCard: {
    backgroundColor: "#2F4F4F",
    marginBottom: 1,
    padding: 5
},
titleText: {
    fontSize: 20,
    color: "#F0FFFF"
},
nameText: {
    fontSize: 14,
    color: "#F0FFFF"
 }
 });

 export default InfiniteScrollRedux;


问:
Trying to find a set of letters within a string with a loop
I am trying to make a loop that checks all the cells in column A and if it finds that any of them contains the phrase "ISAW" within a string (like 1314_ISAW_STUFF) then it changes the value of the corresponding cell in column G to "COMPLIANT".

I have the following code, the loop works and the Cells.Find option should work but it doesn't activate any cells with matching criteria.

```<code>Sub mytestsub()

Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")

Dim i As Integer
sh1.Activate

On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
    sh1.Cells.Find("ISAW").Activate
    If InStr(ActiveCell, "ISAW") > 0 Then
        ActiveCell.Offset(, 7).Value = "COMPLIANT"
    End If
Next i

MyError:
On Error GoTo -1

End Sub
</code>```

Any help would be appreciated!

I altered the script Tom generously provided as seen below, but it doesn't seem to be working now.

```<code> Sub bugfix()
'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String
    Worksheets("Summary").Unprotect
With Worksheets("Summary")
        .Activate

        On Error GoTo MyError
        Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Cells.FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
Exit Sub
MyError:
    On Error GoTo -1
End Sub
</code>```

答:
Use Find and FindNext to do this. This will find all cells in Sheet1 that contain "ISAW" and update the values in column G. Also, with error handling make sure to Exit Sub before your error handling process otherwise it'll run whether there is an error or not.

Updated after comments

The reason it's not doing anything is because your code actually has an error BUT it is being masked by your On Error GoTo MyError. I've updated with a fixed code

```<code>Sub bugfix()
    'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String

    With Worksheets("Summary")
        .Unprotect
        .Activate
        On Error GoTo MyError
        Set fndCell = .Columns(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Columns(3).FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
    Exit Sub
MyError:
    On Error GoTo -1
End Sub
</code>```

Body:
I am trying to make a loop that checks all the cells in column A and if it finds that any of them contains the phrase "ISAW" within a string (like 1314_ISAW_STUFF) then it changes the value of the corresponding cell in column G to "COMPLIANT".

I have the following code, the loop works and the Cells.Find option should work but it doesn't activate any cells with matching criteria.

Sub mytestsub()

Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")

Dim i As Integer
sh1.Activate

On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
    sh1.Cells.Find("ISAW").Activate
    If InStr(ActiveCell, "ISAW") > 0 Then
        ActiveCell.Offset(, 7).Value = "COMPLIANT"
    End If
Next i

MyError:
On Error GoTo -1

End Sub

Any help would be appreciated!

I altered the script Tom generously provided as seen below, but it doesn't seem to be working now.

 Sub bugfix()
'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String
    Worksheets("Summary").Unprotect
With Worksheets("Summary")
        .Activate

        On Error GoTo MyError
        Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Cells.FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
Exit Sub
MyError:
    On Error GoTo -1
End Sub

Body:
Use Find and FindNext to do this. This will find all cells in Sheet1 that contain "ISAW" and update the values in column G. Also, with error handling make sure to Exit Sub before your error handling process otherwise it'll run whether there is an error or not.

Updated after comments

The reason it's not doing anything is because your code actually has an error BUT it is being masked by your On Error GoTo MyError. I've updated with a fixed code

Sub bugfix()
    'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String

    With Worksheets("Summary")
        .Unprotect
        .Activate
        On Error GoTo MyError
        Set fndCell = .Columns(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Columns(3).FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
    Exit Sub
MyError:
    On Error GoTo -1
End Sub


问:
using stored procedure parameter as join condition within procedure
What I want here is, using the parameter @PackageId as join condition parameter from Packages table while joining Packages table with the Devices(somewhere around FROM Packages Join Devices on Packages.PackageId=Devices.PackageId)

```<code>create PROC [dbo].[Usp_MissingPackageList]
(@DeviceName AS varchar(50),
@PackageId as int )
AS
BEGIN
    SELECT Packages.PackageId
        ,Packages.DisplayName
        ,Packages.PublishedBy
        ,convert(VARCHAR(10),Packages.PublishedOn, 101) PublishedOn
    FROM Packages Join Devices on Packages.PackageId=Devices.PackageId
    join [dbo].[PersonalizationStatuses] on Devices.SerialKey=PersonalizationStatuses.DeviceSerialNo
    where (Packages.PackageId>@PackageID) and (Packages.FlightType=PersonalizationStatuses.FleetType or Packages.FlightType='Common')
    ORDER BY PackageId ASC
END
</code>```

My requirement is to get all tha packages from the Package table having PackageId>@PackageId

答:
Use along with Join</p>

```<code>  create PROC [dbo].[Usp_MissingPackageList]
    (@DeviceName AS varchar(50),
    @PackageId as int )
    AS
    BEGIN
        SELECT Packages.PackageId
            ,Packages.DisplayName
            ,Packages.PublishedBy
            ,convert(VARCHAR(10),Packages.PublishedOn, 101) PublishedOn
        FROM Packages Join Devices on Packages.PackageId=Devices.PackageId AND (Packages.PackageId>@PackageID)
        join [dbo].[PersonalizationStatuses] on Devices.SerialKey=PersonalizationStatuses.DeviceSerialNo
        where  (Packages.FlightType=PersonalizationStatuses.FleetType or Packages.FlightType='Common')
        ORDER BY PackageId ASC
    END
</code>```

Body:
What I want here is, using the parameter @PackageId as join condition parameter from Packages table while joining Packages table with the Devices(somewhere around FROM Packages Join Devices on Packages.PackageId=Devices.PackageId)

create PROC [dbo].[Usp_MissingPackageList]
(@DeviceName AS varchar(50),
@PackageId as int )
AS
BEGIN
    SELECT Packages.PackageId
        ,Packages.DisplayName
        ,Packages.PublishedBy
        ,convert(VARCHAR(10),Packages.PublishedOn, 101) PublishedOn
    FROM Packages Join Devices on Packages.PackageId=Devices.PackageId
    join [dbo].[PersonalizationStatuses] on Devices.SerialKey=PersonalizationStatuses.DeviceSerialNo
    where (Packages.PackageId>@PackageID) and (Packages.FlightType=PersonalizationStatuses.FleetType or Packages.FlightType='Common')
    ORDER BY PackageId ASC
END

My requirement is to get all tha packages from the Package table having PackageId>@PackageId

Body:
Use along with Join

  create PROC [dbo].[Usp_MissingPackageList]
    (@DeviceName AS varchar(50),
    @PackageId as int )
    AS
    BEGIN
        SELECT Packages.PackageId
            ,Packages.DisplayName
            ,Packages.PublishedBy
            ,convert(VARCHAR(10),Packages.PublishedOn, 101) PublishedOn
        FROM Packages Join Devices on Packages.PackageId=Devices.PackageId AND (Packages.PackageId>@PackageID)
        join [dbo].[PersonalizationStatuses] on Devices.SerialKey=PersonalizationStatuses.DeviceSerialNo
        where  (Packages.FlightType=PersonalizationStatuses.FleetType or Packages.FlightType='Common')
        ORDER BY PackageId ASC
    END


问:
GraphQL and data transform
I have limited capabilities on my client, and need to send unstructured data to GraphQL.

I'll have a query like this:

```<code>mutation createDroid {
  payload: "R2-D2,Astromech,NEWHOPE\,EMPIRE\,JEDI"
}
</code>```

And want to turn it into schema like this:

```<code>type Droid {
  name: String!
  function: String!
  appearsIn: [Episode]!
}
</code>```

Would this be the right way to define the Mutator

```<code>type Mutation {
  createDroid(string payload): Droid
}
</code>```

All I would have to do is make sure the resolver returns an Object with name function and appearsIn properties to invoke the schema validation?

Something makes me think I would need to build a new query and call
graphql(schema, query, resolvers) again.

答:
Yes, you only need to make sure the resolver returns a correct Object ;)

On a side note, correct query and mutation definition syntax:

```<code>mutation CreationOfTheDroid {
  createDroid(payload: "R2-D2,Astromech,NEWHOPE\,EMPIRE\,JEDI") {
    // ...
  }
}

type Mutation {
  createDroid(payload: String!): Droid!
}
</code>```

Title: GraphQL and data transform

Body:
I have limited capabilities on my client, and need to send unstructured data to GraphQL.

I'll have a query like this:

mutation createDroid {
  payload: "R2-D2,Astromech,NEWHOPE\,EMPIRE\,JEDI"
}

And want to turn it into schema like this:

type Droid {
  name: String!
  function: String!
  appearsIn: [Episode]!
}

Would this be the right way to define the Mutator

type Mutation {
  createDroid(string payload): Droid
}

All I would have to do is make sure the resolver returns an Object with name function and appearsIn properties to invoke the schema validation?

Something makes me think I would need to build a new query and call
graphql(schema, query, resolvers) again.

Body:
Yes, you only need to make sure the resolver returns a correct Object ;)

On a side note, correct query and mutation definition syntax:

mutation CreationOfTheDroid {
  createDroid(payload: "R2-D2,Astromech,NEWHOPE\,EMPIRE\,JEDI") {
    // ...
  }
}

type Mutation {
  createDroid(payload: String!): Droid!
}


问:
Spark program to bulkdelete hbase rows throws AbstractMethodError
Following is my code block in spark application to delete set of rowkeys (rePartitionedRowKeys) from hbase table,

```<code>hbaseContext.bulkDelete[Array[Byte]](rePartitionedRowKeys,
        TableName.valueOf(hbaseTableName),
        putRecord => new Delete(putRecord), batchSize)
</code>```

Related dependencies in pom.xml are,

```<code><dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-spark</artifactId>
    <version>1.2.0-cdh5.7.0</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.10</artifactId>
    <version>1.6.0-cdh5.7.0</version>
    <scope>provided</scope>
</dependency>
</code>```

When I run the application, I am getting AbstractMethodError for one of the log method,

```<code>org.apache.spark.SparkException: Job aborted due to stage failure: Task 3 in stage 4.0 failed 4 times, most recent failure: Lost task 3.3 in stage 4.0 (TID 17, c175vjt.int.westgroup.com, executor 2): java.lang.AbstractMethodError: org.apache.hadoop.hbase.spark.HBaseContext.initializeLogIfNecessary(Z)V
    at org.apache.spark.Logging$class.log(Logging.scala:50)
    at org.apache.hadoop.hbase.spark.HBaseContext.log(HBaseContext.scala:60)
    at org.apache.spark.Logging$class.logDebug(Logging.scala:62)
    at org.apache.hadoop.hbase.spark.HBaseContext.logDebug(HBaseContext.scala:60)
    at org.apache.hadoop.hbase.spark.HBaseContext.applyCreds(HBaseContext.scala:235)
    at org.apache.hadoop.hbase.spark.HBaseContext.org$apache$hadoop$hbase$spark$HBaseContext$$hbaseForeachPartition(HBaseContext.scala:482)
    at org.apache.hadoop.hbase.spark.HBaseContext$$anonfun$org$apache$hadoop$hbase$spark$HBaseContext$$bulkMutation$1.apply(HBaseContext.scala:322)
    at org.apache.hadoop.hbase.spark.HBaseContext$$anonfun$org$apache$hadoop$hbase$spark$HBaseContext$$bulkMutation$1.apply(HBaseContext.scala:322)
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1$$anonfun$apply$33.apply(RDD.scala:920)
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1$$anonfun$apply$33.apply(RDD.scala:920)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1866)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1866)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:242)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1457) ~[spark-assembly-1.6.0-cdh5.10.2-hadoop2.6.0-cdh5.10.2.jar:na]
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1445) ~[spark-assembly-1.6.0-cdh5.10.2-hadoop2.6.0-cdh5.10.2.jar:na]
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1444) ~[spark-assembly-1.6.0-cdh5.10.2-hadoop2.6.0-cdh5.10.2.jar:na]
</code>```

Am I missing any dependency jars or is it due to jar conflict ?
Thanks in advance

答:
I was using CDH5.5.7 jars with Spark 1.5.1 but spark-hbase related jars were pointing to cdh5.7.0.

Then I upgraded the CDH version to 5.10.2 and made all other jars compatible to cdh5.10.2 which resolved AbstractMethodError.

Body:
Following is my code block in spark application to delete set of rowkeys (rePartitionedRowKeys) from hbase table,

hbaseContext.bulkDelete[Array[Byte]](rePartitionedRowKeys,
        TableName.valueOf(hbaseTableName),
        putRecord => new Delete(putRecord), batchSize)

Related dependencies in pom.xml are,

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-spark</artifactId>
    <version>1.2.0-cdh5.7.0</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming_2.10</artifactId>
    <version>1.6.0-cdh5.7.0</version>
    <scope>provided</scope>
</dependency>

When I run the application, I am getting AbstractMethodError for one of the log method,

org.apache.spark.SparkException: Job aborted due to stage failure: Task 3 in stage 4.0 failed 4 times, most recent failure: Lost task 3.3 in stage 4.0 (TID 17, c175vjt.int.westgroup.com, executor 2): java.lang.AbstractMethodError: org.apache.hadoop.hbase.spark.HBaseContext.initializeLogIfNecessary(Z)V
    at org.apache.spark.Logging$class.log(Logging.scala:50)
    at org.apache.hadoop.hbase.spark.HBaseContext.log(HBaseContext.scala:60)
    at org.apache.spark.Logging$class.logDebug(Logging.scala:62)
    at org.apache.hadoop.hbase.spark.HBaseContext.logDebug(HBaseContext.scala:60)
    at org.apache.hadoop.hbase.spark.HBaseContext.applyCreds(HBaseContext.scala:235)
    at org.apache.hadoop.hbase.spark.HBaseContext.org$apache$hadoop$hbase$spark$HBaseContext$$hbaseForeachPartition(HBaseContext.scala:482)
    at org.apache.hadoop.hbase.spark.HBaseContext$$anonfun$org$apache$hadoop$hbase$spark$HBaseContext$$bulkMutation$1.apply(HBaseContext.scala:322)
    at org.apache.hadoop.hbase.spark.HBaseContext$$anonfun$org$apache$hadoop$hbase$spark$HBaseContext$$bulkMutation$1.apply(HBaseContext.scala:322)
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1$$anonfun$apply$33.apply(RDD.scala:920)
    at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1$$anonfun$apply$33.apply(RDD.scala:920)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1866)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1866)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:242)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1457) ~[spark-assembly-1.6.0-cdh5.10.2-hadoop2.6.0-cdh5.10.2.jar:na]
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1445) ~[spark-assembly-1.6.0-cdh5.10.2-hadoop2.6.0-cdh5.10.2.jar:na]
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1444) ~[spark-assembly-1.6.0-cdh5.10.2-hadoop2.6.0-cdh5.10.2.jar:na]

Am I missing any dependency jars or is it due to jar conflict ?
Thanks in advance


问:
Deleting Empty Paragraphs in Word Using VBA: Not All Empty Paragraphs Deleted
I wrote a macro to delete all the empty paragraphs in my document, but it exhibits weird behavior: If there are a number of empty paragraphs at the very end of the document, about half of them are deleted. Repeatedly running the macro gradually eliminates the empty paragraphs until only one empty paragraph remains. Even if there is a boundary condition so that I need a line of code to delete the last paragraph, but I still don't understand why only half of the empty paragraphs at the end are deleted. Can anyone explain why this is happening and how to correct this behavior? As an aside, I searched online and saw numerous posts about detecting paragraph markers (^p, ^13, and others, but only searching vbCr worked, which is another minor puzzle.)</p>

```<code>Sub Delete_Empty__Paras_2() 'This macro looks for empty paragraphs and deletes them.
Dim original_num_of_paras_in_doc As Integer
Dim num_of_deleted_paras As Integer

original_num_of_paras_in_doc = ActiveDocument.Paragraphs.Count 'Count the number of paragraphs in the document to start
num_of_deleted_paras = 0 'In the beginning, no paragraphs have been deleted

Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
For current_para_number = 1 To original_num_of_paras_in_doc 'Process each paragraph in the document, one by one.
    If current_para_number + num_of_deleted_paras > original_num_of_paras_in_doc Then 'Stop processing paragraphs when the loop has processed every paragraph.
        Exit For
    Else 'If the system just deleted the 3rd paragraph of the document because
        ' it's empty, the next paragraph processed is the 3rd one again,
        'so when we iterate the counter, we have to subtract the number of deleted paragraphs to account for this.
        Set paraRange = ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range
        paratext = paraRange.Text
        If paratext = vbCr Then 'Is the paragraph empty? (By the way, checking for vbCr is the only method that worked for checking for empty paras.)
            paratext = "" 'Delete the paragraph.
            ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range.Text = paratext
            num_of_deleted_paras = num_of_deleted_paras + 1 'Iterate the count of deleted paras.
        End If
    End If
Next current_para_number
End Sub
</code>```

答:
You can replace the paragraph marks:</p>

```<code>ActiveDocument.Range.Find.Execute FindText:="^p^p", ReplaceWith:="^p", Replace:=wdReplaceAll

ActiveDocument.Range.Find.Execute "^p^p", , , , , , , , , "^p", wdReplaceAll ' might be needed more than once
</code>```

Body:
I wrote a macro to delete all the empty paragraphs in my document, but it exhibits weird behavior: If there are a number of empty paragraphs at the very end of the document, about half of them are deleted. Repeatedly running the macro gradually eliminates the empty paragraphs until only one empty paragraph remains. Even if there is a boundary condition so that I need a line of code to delete the last paragraph, but I still don't understand why only half of the empty paragraphs at the end are deleted. Can anyone explain why this is happening and how to correct this behavior? As an aside, I searched online and saw numerous posts about detecting paragraph markers (^p, ^13, and others, but only searching vbCr worked, which is another minor puzzle.)

Sub Delete_Empty__Paras_2() 'This macro looks for empty paragraphs and deletes them.
Dim original_num_of_paras_in_doc As Integer
Dim num_of_deleted_paras As Integer

original_num_of_paras_in_doc = ActiveDocument.Paragraphs.Count 'Count the number of paragraphs in the document to start
num_of_deleted_paras = 0 'In the beginning, no paragraphs have been deleted

Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
For current_para_number = 1 To original_num_of_paras_in_doc 'Process each paragraph in the document, one by one.
    If current_para_number + num_of_deleted_paras > original_num_of_paras_in_doc Then 'Stop processing paragraphs when the loop has processed every paragraph.
        Exit For
    Else 'If the system just deleted the 3rd paragraph of the document because
        ' it's empty, the next paragraph processed is the 3rd one again,
        'so when we iterate the counter, we have to subtract the number of deleted paragraphs to account for this.
        Set paraRange = ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range
        paratext = paraRange.Text
        If paratext = vbCr Then 'Is the paragraph empty? (By the way, checking for vbCr is the only method that worked for checking for empty paras.)
            paratext = "" 'Delete the paragraph.
            ActiveDocument.Paragraphs(current_para_number - num_of_deleted_paras).Range.Text = paratext
            num_of_deleted_paras = num_of_deleted_paras + 1 'Iterate the count of deleted paras.
        End If
    End If
Next current_para_number
End Sub

Body:
You can replace the paragraph marks:

ActiveDocument.Range.Find.Execute FindText:="^p^p", ReplaceWith:="^p", Replace:=wdReplaceAll

ActiveDocument.Range.Find.Execute "^p^p", , , , , , , , , "^p", wdReplaceAll ' might be needed more than once