问:
how to create a relocatable rpm package , no compile
I am trying to create a "relocatable RPM" of bunch of script and .png files. No build/compile. I wrote

```<code>
    Name:       utp
    Version:    1.0
    Release:    1%{?dist}
    Summary:    some summary

    Group:      Applications/Engineering
    License:    Proprietary
    URL:        http://www.example.com
    Source0:    %{name}-%{version}.tgz
    BuildArch:  noarch
    Prefix:     /opt

    %description
    A very nice description

    %prep
    echo "=== prep ... done"

    %setup -n utp
    echo "=== setup ... done"

    # %files -f %{_tmppath}/files.list
    %files

</code>```

and I get

```<code>
    medi@medi:~/work> rpm -qi -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    Name        : utp
    Version     : 1.0
    Release     : 1.el8
    Architecture: noarch
    Install Date: (not installed)
    Group       : Applications/Engineering
    Size        : 0
    License     : Proprietary
    Signature   : (none)
    Source RPM  : utp-1.0-1.el8.src.rpm
    Build Date  : Mon 17 Feb 2020 03:44:00 PM PST
    Build Host  : medi.example.com
    Relocations : /opt
    URL         : http://www.example.com
    Summary     : some summary
    Description :
    A very nice description
</code>```

and

```<code>    medi@medi:~/work> rpm -ql -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    (contains no files)
    medi@medi:~/work>
</code>```

Most likely the problem is with '%files'. I tried to specify a list (commented out now), but I ran into the following

```<code>    Processing files: utp-1.0-1.el8.noarch
    error: Directory not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg/UserGuide.txt

</code>```

where my file.list looks like

```<code>
    /opt/utp/
    /opt/utp/utg
    /opt/utp/utg/UserGuide.txt
    /opt/utp/utg/install.txt

</code>```

Since I want to make this a relocatable one (see Prefix: /opt), I prepended '/opt'.

I think overall, I am confused. Yes I did read the doc, but I am missing it.

答:
The reason for pkg not having content is because %file directive was empty and with -f one has to be careful about where files are. After many reads, I figured that %files look for files in %{buildroot} by default so this combination solved it

```<code>%install
cp -r ./* %{buildroot}

%files
/%{name}
</code>```

So, now I have content, but then I ran into some shebang_mangling, where I had to disable that.

Body:
I am trying to create a "relocatable RPM" of bunch of script and .png files. No build/compile. I wrote

    Name:       utp
    Version:    1.0
    Release:    1%{?dist}
    Summary:    some summary

    Group:      Applications/Engineering
    License:    Proprietary
    URL:        http://www.example.com
    Source0:    %{name}-%{version}.tgz
    BuildArch:  noarch
    Prefix:     /opt

    %description
    A very nice description

    %prep
    echo "=== prep ... done"

    %setup -n utp
    echo "=== setup ... done"

    # %files -f %{_tmppath}/files.list
    %files

and I get

    medi@medi:~/work> rpm -qi -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    Name        : utp
    Version     : 1.0
    Release     : 1.el8
    Architecture: noarch
    Install Date: (not installed)
    Group       : Applications/Engineering
    Size        : 0
    License     : Proprietary
    Signature   : (none)
    Source RPM  : utp-1.0-1.el8.src.rpm
    Build Date  : Mon 17 Feb 2020 03:44:00 PM PST
    Build Host  : medi.example.com
    Relocations : /opt
    URL         : http://www.example.com
    Summary     : some summary
    Description :
    A very nice description

and

    medi@medi:~/work> rpm -ql -p rpmbuild/RPMS/noarch/utp-1.0-1.el8.noarch.rpm
    (contains no files)
    medi@medi:~/work>

Most likely the problem is with '%files'. I tried to specify a list (commented out now), but I ran into the following

    Processing files: utp-1.0-1.el8.noarch
    error: Directory not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg
    error: File not found: /home/medi/work/rpmbuild/BUILDROOT/utp-1.0-1.el8.x86_64/opt/utp/utg/UserGuide.txt

where my file.list looks like

    /opt/utp/
    /opt/utp/utg
    /opt/utp/utg/UserGuide.txt
    /opt/utp/utg/install.txt

Since I want to make this a relocatable one (see Prefix: /opt), I prepended '/opt'.

I think overall, I am confused. Yes I did read the doc, but I am missing it.

Body:
The reason for pkg not having content is because %file directive was empty and with -f one has to be careful about where files are. After many reads, I figured that %files look for files in %{buildroot} by default so this combination solved it

%install
cp -r ./* %{buildroot}

%files
/%{name}

So, now I have content, but then I ran into some shebang_mangling, where I had to disable that.


来源: stackexchange

问:
unittest - how to assert if the two possibly NaN values are equal
In my test case, I assume that if two values are NaN then they are equal. What is the way to express it using unittest assertions? The two common functions presented below are not handling this case.

```<code>v1 = np.nan
v2 = np.nan
self.assertEquals(v1, v2)
self.assertTrue(v1 == v2)
</code>```

A solution that is working for me right now is using a boolean expression inside assertTrue:

```<code>self.assertTrue(v1 == v2 or (np.isnan(v1) and np.isnan(v2))
</code>```

答:
A standard way of checking for nans is

```<code>assert (v1 != v1) and (v2 != v2)
</code>```

i.e. something that is not equal to itself, e.g:

```<code>>>> n = float('nan')
>>> n != n
True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my test case, I assume that if two values are NaN then they are equal. What is the way to express it using unittest assertions? The two common functions presented below are not handling this case.

v1 = np.nan
v2 = np.nan
self.assertEquals(v1, v2)
self.assertTrue(v1 == v2)

A solution that is working for me right now is using a boolean expression inside assertTrue:

self.assertTrue(v1 == v2 or (np.isnan(v1) and np.isnan(v2))

Body:
A standard way of checking for nans is

assert (v1 != v1) and (v2 != v2)

i.e. something that is not equal to itself, e.g:

>>> n = float('nan')
>>> n != n
True


问:
Laravel dispatching Queues at set time
I am currently dispatching queued jobs to send API Events instantly, in busy times these queued jobs need to be held until overnight when the API is less busy, how can I hold these queued jobs or schedule them to only run from 01:00am the following day.

the Queued Job call currently looks like:

```<code>EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli');
</code>```

there are other jobs on the same queue, all of which will need to be held in busy times

答:
You can use delayed dispatching (see https://laravel.com/docs/6.x/queues#delayed-dispatching):

// Run it 10 minutes later:
EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli')->delay(
    now()->addMinutes(10)
);
```

<p>Or pass another carbon instance like:</p>

<pre class="lang-php prettyprint-override"><code>// Run it at the end of the current week (i believe this is sunday 23:59, havent checked).
->delay(Carbon::now()->endOfWeek());
// Or run it at february second 2020 at 00:00.
->delay(Carbon::createFromFormat('Y-m-d', '2020-02-02'));
</code>```

You get the picture.

Title: Laravel dispatching Queues at set time

Body:
I am currently dispatching queued jobs to send API Events instantly, in busy times these queued jobs need to be held until overnight when the API is less busy, how can I hold these queued jobs or schedule them to only run from 01:00am the following day.

the Queued Job call currently looks like:

EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli');

there are other jobs on the same queue, all of which will need to be held in busy times

Body:
You can use delayed dispatching (see https://laravel.com/docs/6.x/queues#delayed-dispatching):

// Run it 10 minutes later:
EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli')->delay(
    now()->addMinutes(10)
);

Or pass another carbon instance like:

// Run it at the end of the current week (i believe this is sunday 23:59, havent checked).
->delay(Carbon::now()->endOfWeek());
// Or run it at february second 2020 at 00:00.
->delay(Carbon::createFromFormat('Y-m-d', '2020-02-02'));

You get the picture.


问:
How can I access my personal data through the Evernote API?
I would like to make some Pyton or NodeJS script to help me with repetitive tasks or searchs in my personal Evernote.

I don't want to make any application for general use. Only some scripts for me.

Is there a quick way to make this before creating an account in sandbox.evernote.com? I want to access my already available data in Evernote.

答:
Yes, this exact thing exists. Go here:
https://dev.evernote.com/doc/articles/dev_tokens.php

And get a "developer token" for your production account. It will allow access to your account only and you can do what you like with your data via the API.


问:
Replace uploaded image using Cloudinary and Flutter
I upload my images like this:

```<code>CloudinaryResponse response = await this.url.uploadImage(filePath,
        filename: "background",
        folder: "alquileres/$userId/$portfolioId/$investmentId");
</code>```

The image names are "background_longID". I'd like to overwrite all the images.

I've found an old issue in Github but doesn't provide too much info (https://github.com/cloudinary/cloudinary_ios/issues/87)

答:
Cloudinary doesn't support integration with flutter. there are some third parties that you can use for example here: https://gist.github.com/Wizpna/eab058e15cc1533bdb73bf764078f642

If you would like to upload images to Cloudinary, our best practice is to add an upload widget. You can read more about it here:
https://cloudinary.com/documentation/upload_widget

Body:
I upload my images like this:

CloudinaryResponse response = await this.url.uploadImage(filePath,
        filename: "background",
        folder: "alquileres/$userId/$portfolioId/$investmentId");

The image names are "background_longID". I'd like to overwrite all the images.

I've found an old issue in Github but doesn't provide too much info (https://github.com/cloudinary/cloudinary_ios/issues/87)


问:
Regex to match quote with minimum number of words
I have the following text:

Attorney General William Barr said the volume of information
  compromised was “staggering” and the largest breach in U.S.
  history.“This theft not only caused significant financial damage to
  Equifax but invaded the privacy of many, millions of Americans and
  imposed substantial costs and burdens on them as they had to take
  measures to protect themselves from identity theft,” said Mr. Barr.

I want to match text within a quote however the quote must be a min of 5 words long otherwise it should be ignored.

Currently, I am using the following regex:

```<code>(?<=[\\“|\\"])[A-Za-z0-9\.\-][A-Za-z\s,:\\’]+(?=[\”|\"])
</code>```

However, this would include the quote “staggering”  which is only 1 word so it should be ignored.

I realize I could accomplish this by repeating this part of Regex 5 times:

```<code>[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+
</code>```

However, I am wondering if there is a shorter and more concise way to achieve this? Perhaps by forcing the \s in [] to appear at least 5 times?

Thanks

答:
You need to "unroll" the character class by taking out the whitespace matching pattern out of it, and use a [<chars>]+(?:\s+[<chars>]+){4,} like pattern. Note you should not use lookarounds here because " can be both a leading and a trailing marker, and that may result in unwanted matches. Use a capturing group instead  and access its value via matcher.group(1).

You may use

```<code>String regex = "[“\"]([A-Za-z0-9.-][A-Za-z,:’]*(?:\\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,})[”\"]";
</code>```

See the regex demo.

Then, just grab the Group 1 value:

```<code>String line = "Attorney General William Barr said the volume of information compromised was “staggering” and the largest breach in U.S. history.“This theft not only caused significant financial damage to Equifax but invaded the privacy of many, millions of Americans and imposed substantial costs and burdens on them as they had to take measures to protect themselves from identity theft,” said Mr. Barr.";
String regex = "[“\"]([A-Za-z0-9.-][A-Za-z,:’]*(?:\\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,})[”\"]";
Matcher m = Pattern.compile(regex).matcher(line);
List<String> res = new ArrayList<>();
while(m.find()) {
    res.add(m.group(1));
}
System.out.println(res);
</code>```

See the online Java demo.

Pattern details

[“"] - “ or "

([A-Za-z0-9.-][A-Za-z,:’]*(?:\\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,}) - Group 1:

[A-Za-z0-9.-][A-Za-z,:’]* - an ASCII alphanumeric or . or - and then 0+ of ASCII letters, ,, :, ’ chars

(?:\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,} - four or more occurrences of

\s+ - 1+ whitespaces

[A-Za-z0-9.-][A-Za-z,:’]* - an ASCII alphanumeric or . or - and then 0+ of ASCII letters, ,, :, ’ chars

[”"] - " or ”

Body:
I have the following text:

Attorney General William Barr said the volume of information
  compromised was “staggering” and the largest breach in U.S.
  history.“This theft not only caused significant financial damage to
  Equifax but invaded the privacy of many, millions of Americans and
  imposed substantial costs and burdens on them as they had to take
  measures to protect themselves from identity theft,” said Mr. Barr.

I want to match text within a quote however the quote must be a min of 5 words long otherwise it should be ignored.

Currently, I am using the following regex:

(?<=[\\“|\\"])[A-Za-z0-9\.\-][A-Za-z\s,:\\’]+(?=[\”|\"])

However, this would include the quote “staggering”  which is only 1 word so it should be ignored.

I realize I could accomplish this by repeating this part of Regex 5 times:

[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+[A-Za-z\s,:\\’]+

However, I am wondering if there is a shorter and more concise way to achieve this? Perhaps by forcing the \s in [] to appear at least 5 times?

Thanks

Body:
You need to "unroll" the character class by taking out the whitespace matching pattern out of it, and use a [<chars>]+(?:\s+[<chars>]+){4,} like pattern. Note you should not use lookarounds here because " can be both a leading and a trailing marker, and that may result in unwanted matches. Use a capturing group instead  and access its value via matcher.group(1).

You may use

String regex = "[“\"]([A-Za-z0-9.-][A-Za-z,:’]*(?:\\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,})[”\"]";

See the regex demo.

Then, just grab the Group 1 value:

String line = "Attorney General William Barr said the volume of information compromised was “staggering” and the largest breach in U.S. history.“This theft not only caused significant financial damage to Equifax but invaded the privacy of many, millions of Americans and imposed substantial costs and burdens on them as they had to take measures to protect themselves from identity theft,” said Mr. Barr.";
String regex = "[“\"]([A-Za-z0-9.-][A-Za-z,:’]*(?:\\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,})[”\"]";
Matcher m = Pattern.compile(regex).matcher(line);
List<String> res = new ArrayList<>();
while(m.find()) {
    res.add(m.group(1));
}
System.out.println(res);

See the online Java demo.

Pattern details

[“"] - “ or "

([A-Za-z0-9.-][A-Za-z,:’]*(?:\\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,}) - Group 1:

[A-Za-z0-9.-][A-Za-z,:’]* - an ASCII alphanumeric or . or - and then 0+ of ASCII letters, ,, :, ’ chars

(?:\s+[A-Za-z0-9.-][A-Za-z,:’]*){4,} - four or more occurrences of

\s+ - 1+ whitespaces

[A-Za-z0-9.-][A-Za-z,:’]* - an ASCII alphanumeric or . or - and then 0+ of ASCII letters, ,, :, ’ chars

[”"] - " or ”


问:
javax/xml/bind/JAXBException building with gradle
I'm trying to update to gradle 5.4 and thus JDK 11 but I'm having errors when building:

```<code> Task :app:compileDesarrolloDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDesarrolloDebugJavaWithJavac'.
> javax/xml/bind/JAXBException
</code>```

I've been searching for some solution and I found that I had to add some dependencies on my app/build.gradle because Java 9+ does not install jre anymore:

```<code>compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
compile group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.3.0'
compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
compile group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '2.3.1'
</code>```

But I'm still getting the same error:

```<code>javax/xml/bind/JAXBException
> javax.xml.bind.JAXBException

org.gradle.api.tasks.TaskExecutionException
:
Execution failed for task ':app:compileDesarrolloDebugJavaWithJavac'.
Open stacktrace
Caused by:
java.lang.NoClassDefFoundError
:
javax/xml/bind/JAXBException
Open stacktrace
Caused by:
java.lang.ClassNotFoundException
:
javax.xml.bind.JAXBException
Close stacktrace
at org.gradle.api.internal.tasks.compile.AnnotationProcessingCompileTask.instantiateProcessor(AnnotationProcessingCompileTask.java:149)
at org.gradle.api.internal.tasks.compile.AnnotationProcessingCompileTask.setupProcessors(AnnotationProcessingCompileTask.java:108)
at org.gradle.api.internal.tasks.compile.AnnotationProcessingCompileTask.call(AnnotationProcessingCompileTask.java:91)
at org.gradle.api.internal.tasks.compile.ResourceCleaningCompilationTask.call(ResourceCleaningCompilationTask.java:57)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:36)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:100)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:52)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:38)
at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:51)
at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:37)
...
</code>```

Full app/build.gradle: https://gist.github.com/vivoconunxino/a68d2011bc1b184a83786a6268533087

Full error: https://gist.github.com/vivoconunxino/1a27586133b34adbbe8314395e6704a1

答:
Note: I'm just trying to make a comment, but do not have enough reputation to make one.

I just ran into this issue today, when attempting to build an Android App with Gradle 6.1.1 (also tried on 5.4.1), and using JDK 11, on macOS 10.15.3 (Catalina).

I fixed this issue by downgrading my JDK, to JDK8, since according to this (How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException in Java 9), apparently JAXB was removed in JDK 11.

I feel like this is an issue related to a Gradle plugin (possibly com.android.application, or a kotlin plugin), since I built JNI via Gradle with JDK11.

Body:
I'm trying to update to gradle 5.4 and thus JDK 11 but I'm having errors when building:

 Task :app:compileDesarrolloDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDesarrolloDebugJavaWithJavac'.
> javax/xml/bind/JAXBException

I've been searching for some solution and I found that I had to add some dependencies on my app/build.gradle because Java 9+ does not install jre anymore:

compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
compile group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.3.0'
compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
compile group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '2.3.1'

But I'm still getting the same error:

javax/xml/bind/JAXBException
> javax.xml.bind.JAXBException

org.gradle.api.tasks.TaskExecutionException
:
Execution failed for task ':app:compileDesarrolloDebugJavaWithJavac'.
Open stacktrace
Caused by:
java.lang.NoClassDefFoundError
:
javax/xml/bind/JAXBException
Open stacktrace
Caused by:
java.lang.ClassNotFoundException
:
javax.xml.bind.JAXBException
Close stacktrace
at org.gradle.api.internal.tasks.compile.AnnotationProcessingCompileTask.instantiateProcessor(AnnotationProcessingCompileTask.java:149)
at org.gradle.api.internal.tasks.compile.AnnotationProcessingCompileTask.setupProcessors(AnnotationProcessingCompileTask.java:108)
at org.gradle.api.internal.tasks.compile.AnnotationProcessingCompileTask.call(AnnotationProcessingCompileTask.java:91)
at org.gradle.api.internal.tasks.compile.ResourceCleaningCompilationTask.call(ResourceCleaningCompilationTask.java:57)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:36)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:100)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:52)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:38)
at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:51)
at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:37)
...

Full app/build.gradle: https://gist.github.com/vivoconunxino/a68d2011bc1b184a83786a6268533087

Full error: https://gist.github.com/vivoconunxino/1a27586133b34adbbe8314395e6704a1


问:
"Object was open" error for large result sets?
I am getting an error 'Object was open' when executing a stored procedure with large amounts of data. This procedure runs from a VB 6.00 application on SQL 2005. When running the script in SQL there is no problem

```<code>rs.Open cmd, Options:=adCmdStoredProc
</code>```

IMPORTANT: This error ONLY happens with large amount of data. The threshold level is about 250000 rows of data. If more than that amount of data is retreived the error occurs. If less then there is no problem.

Any suggestion would be greatfull

Thanks

答:
Try using other cursor types.  On the connection object, try switching from adUseClient to adUseServer or vice versa.

```<code>rs.Open cmd, , adOpenStatic, adLockReadOnly, Options:=adCmdStoredProc
</code>```

Body:
I am getting an error 'Object was open' when executing a stored procedure with large amounts of data. This procedure runs from a VB 6.00 application on SQL 2005. When running the script in SQL there is no problem

rs.Open cmd, Options:=adCmdStoredProc

IMPORTANT: This error ONLY happens with large amount of data. The threshold level is about 250000 rows of data. If more than that amount of data is retreived the error occurs. If less then there is no problem.

Any suggestion would be greatfull

Thanks

Body:
Try using other cursor types.  On the connection object, try switching from adUseClient to adUseServer or vice versa.

rs.Open cmd, , adOpenStatic, adLockReadOnly, Options:=adCmdStoredProc


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

答:
I recommend R package runner for this kind of operations.
streak_run calculates consecutive occurrence of the same value, and sum_run calculates sum in window which length is defined by k argument.

Here is solution:

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

n_of_sequence <- runner::streak_run(x > 0)
sum <- runner::sum_run(x, k = n_of_sequence)

data.frame(x, n_of_sequence, sum)

#         x n_of_sequence    sum
# 1  -0.010             1 -0.010
# 2   0.003             1  0.003
# 3  -0.002             1 -0.002
# 4   0.018             1  0.018
# 5   0.002             2  0.020
# 6   0.006             3  0.026
# 7  -0.012             1 -0.012
# 8   0.014             1  0.014
# 9  -0.017             1 -0.017
# 10 -0.007             2 -0.024
# 11  0.002             1  0.002
# 12  0.002             2  0.004
# 13 -0.004             1 -0.004
# 14  0.015             1  0.015
# 15  0.002             2  0.017
# 16 -0.001             1 -0.001
# 17 -0.008             2 -0.009
# 18  0.010             1  0.010
# 19 -0.018             1 -0.018
# 20  0.046             1  0.046
```

<hr>

<p>Below benchmark to compare actual solutions</p>

<pre class="lang-r prettyprint-override"><code>set.seed(0)
x <- round(rnorm(10000, sd = 0.02), 3)

library(runner)
runner_streak <- function(x) {
  n_of_sequence <- streak_run(x > 0)
  sum <- sum_run(x, k = n_of_sequence)
}

library(data.table)
dt <- data.table(x)
dt_streak <- function(dt) {
  dt[, c("n_of_sequence", "sum") := list(seq_len(.N), cumsum(x)),rleid(sign(x))]
}

rle_streak <- function(x) {
  run_lengths <- rle(sign(x))$lengths
  run_lengths

  n_of_sequence <- run_lengths %>% map(seq) %>% unlist

  start <- cumsum(c(1,run_lengths))
  start <- start[-length(start)]
  sum <- map2(start,run_lengths,~cumsum(x[.x:(.x+.y-1)])) %>% unlist()
}

library(tidyverse)
df <- tibble(x = x)
tv_streak <- function(x) {
  res <- df %>%
    mutate(seqno = cumsum(c(1, diff(sign(x)) != 0))) %>%
    group_by(seqno) %>%
    mutate(n_of_sequence = row_number(),
           sum = cumsum(x)) %>%
    ungroup() %>%
    select(-seqno)
}

count_and_sum <- function(x) {
  runs   <- rle((x > 0) * 1)$lengths
  groups <- split(x, rep(1:length(runs), runs))
  output <- function(group)
    data.frame(x = group, n = seq_along(group), sum = cumsum(group))
  result <- as.data.frame(do.call(rbind, lapply(groups, output)))
  `rownames<-`(result, 1:nrow(result))
}
</code>```

```<code>microbenchmark::microbenchmark(
  runner_streak(x),
  dt_streak(dt),
  rle_streak(x),
  tv_streak(df),
  count_and_sum(x),
  times = 100L
)

# Unit: milliseconds
#             expr         min          lq        mean      median          uq        max neval
# runner_streak(x)    4.240192    4.833563    6.321697    5.300817    6.543926   14.80221   100
#    dt_streak(dt)    7.648100    8.587887   10.862806    9.650483   11.295488   34.66027   100
#    rle_streak(x)   42.321506   55.397586   64.195692   63.404403   67.813738  167.71444   100
#    tv_streak(df)   31.398885   36.333751   45.141452   40.800077   45.756279  163.19535   100
# count_and_sum(x) 1691.438977 1919.518282 2306.036783 2149.543281 2499.951020 6158.43384   100
</code>```

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
I recommend R package runner for this kind of operations.
streak_run calculates consecutive occurrence of the same value, and sum_run calculates sum in window which length is defined by k argument.

Here is solution:

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

n_of_sequence <- runner::streak_run(x > 0)
sum <- runner::sum_run(x, k = n_of_sequence)

data.frame(x, n_of_sequence, sum)

#         x n_of_sequence    sum
# 1  -0.010             1 -0.010
# 2   0.003             1  0.003
# 3  -0.002             1 -0.002
# 4   0.018             1  0.018
# 5   0.002             2  0.020
# 6   0.006             3  0.026
# 7  -0.012             1 -0.012
# 8   0.014             1  0.014
# 9  -0.017             1 -0.017
# 10 -0.007             2 -0.024
# 11  0.002             1  0.002
# 12  0.002             2  0.004
# 13 -0.004             1 -0.004
# 14  0.015             1  0.015
# 15  0.002             2  0.017
# 16 -0.001             1 -0.001
# 17 -0.008             2 -0.009
# 18  0.010             1  0.010
# 19 -0.018             1 -0.018
# 20  0.046             1  0.046

Below benchmark to compare actual solutions

set.seed(0)
x <- round(rnorm(10000, sd = 0.02), 3)

library(runner)
runner_streak <- function(x) {
  n_of_sequence <- streak_run(x > 0)
  sum <- sum_run(x, k = n_of_sequence)
}

library(data.table)
dt <- data.table(x)
dt_streak <- function(dt) {
  dt[, c("n_of_sequence", "sum") := list(seq_len(.N), cumsum(x)),rleid(sign(x))]
}

rle_streak <- function(x) {
  run_lengths <- rle(sign(x))$lengths
  run_lengths

  n_of_sequence <- run_lengths %>% map(seq) %>% unlist

  start <- cumsum(c(1,run_lengths))
  start <- start[-length(start)]
  sum <- map2(start,run_lengths,~cumsum(x[.x:(.x+.y-1)])) %>% unlist()
}

library(tidyverse)
df <- tibble(x = x)
tv_streak <- function(x) {
  res <- df %>%
    mutate(seqno = cumsum(c(1, diff(sign(x)) != 0))) %>%
    group_by(seqno) %>%
    mutate(n_of_sequence = row_number(),
           sum = cumsum(x)) %>%
    ungroup() %>%
    select(-seqno)
}

count_and_sum <- function(x) {
  runs   <- rle((x > 0) * 1)$lengths
  groups <- split(x, rep(1:length(runs), runs))
  output <- function(group)
    data.frame(x = group, n = seq_along(group), sum = cumsum(group))
  result <- as.data.frame(do.call(rbind, lapply(groups, output)))
  `rownames<-`(result, 1:nrow(result))
}

microbenchmark::microbenchmark(
  runner_streak(x),
  dt_streak(dt),
  rle_streak(x),
  tv_streak(df),
  count_and_sum(x),
  times = 100L
)

# Unit: milliseconds
#             expr         min          lq        mean      median          uq        max neval
# runner_streak(x)    4.240192    4.833563    6.321697    5.300817    6.543926   14.80221   100
#    dt_streak(dt)    7.648100    8.587887   10.862806    9.650483   11.295488   34.66027   100
#    rle_streak(x)   42.321506   55.397586   64.195692   63.404403   67.813738  167.71444   100
#    tv_streak(df)   31.398885   36.333751   45.141452   40.800077   45.756279  163.19535   100
# count_and_sum(x) 1691.438977 1919.518282 2306.036783 2149.543281 2499.951020 6158.43384   100


问:
HTML5 video previous - next and auto play
I'm new to this site and I am new to HTML5 and Javascript aswell.
It's not that I am a beginner, I kinda understand HTML5 and Javascript when I see it, I just can't write it proper myself.

I have many videos, all mp4, all same size, all in the same folder on the server.
I already got them to play one after another without break. I don't have any controls.
Looks like this (a code I found and copied and changed as far as I understood it):

BODY

```<code><video id="homevideo" width="1022px" height="766px" autoplay onended="run()">
    <source src="video1.mp4" type='video/mp4'/>
</video>
</code>```

SCRIPT

```<code><script>
video_count =1;
videoPlayer = document.getElementById("homevideo");

function run(){
        video_count++;
        if (video_count == 16) video_count = 1;
        var nextVideo = "video"+video_count+".mp4";
        videoPlayer.src = nextVideo;
        videoPlayer.play();
   };
   </script>
</code>```

It all looks like this now:
Presentation

What I want:
I want a previous and a next function.
So, I have two buttons, a previous and a next button. When I click on the next button, the next video will start and play automatically (no loop). When I click on previous button, the previous video will play again (no loop). So I can simply switch between all my videos forward and backwards.
Like this for example:
IMAGE

What do I have to add to my code? What to change? I know hot do make buttons ect.
Would be nice if someone could give me a clear code for this. Nothing with play or pause or anything.

Thanks very much!

答:
```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id="homevideo" autoplay="" controls webkit-playsinline="" width="100%" height="100%" >
<source src="video1.mp4" type="video/mp4">
</video></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to this site and I am new to HTML5 and Javascript aswell.
It's not that I am a beginner, I kinda understand HTML5 and Javascript when I see it, I just can't write it proper myself.

I have many videos, all mp4, all same size, all in the same folder on the server.
I already got them to play one after another without break. I don't have any controls.
Looks like this (a code I found and copied and changed as far as I understood it):

BODY

<video id="homevideo" width="1022px" height="766px" autoplay onended="run()">
    <source src="video1.mp4" type='video/mp4'/>
</video>

SCRIPT

It all looks like this now:
Presentation

What I want:
I want a previous and a next function.
So, I have two buttons, a previous and a next button. When I click on the next button, the next video will start and play automatically (no loop). When I click on previous button, the previous video will play again (no loop). So I can simply switch between all my videos forward and backwards.
Like this for example:
IMAGE

What do I have to add to my code? What to change? I know hot do make buttons ect.
Would be nice if someone could give me a clear code for this. Nothing with play or pause or anything.

Thanks very much!

Body:
<script>
    var videocount =1;
 var player=document.getElementById('homevideo');
    player.addEventListener('ended',dispositor);
    function dispositor(x){
    if(!x)
    { x = window.event; }
 videocount++;
 if (videocount > 2){ // last number of video playing in loop.
 videocount = 1;}
 player.src="video"+videocount+".mp4"; //complete url
}
</script>

<video id="homevideo" autoplay="" controls webkit-playsinline="" width="100%" height="100%" >
<source src="video1.mp4" type="video/mp4">
</video>


问:
Is there a lablled dataset for rate-of-speech? With labels like fast,medium,slow or based on words-per-minute?
I am doing a project on ML for finding the rate-of-speech from an audio file.
I couldn't find a labeled dataset for it.
Any suggestions?</p>

答:
You can time-align dataset like TEDLIUM with word timestamps and calculate the rate of speech from it.

If you need variety of rates, it is probably better to dump youtube audios and use recognized word timestamps since most datasets are pretty uniform in terms of rate.


问:
Resizing wpf window programmatically in c#
I have a wpf window with two usercontrols inside of which the second is only shown when needed. I only set the MinWidth of the window in XAML, the MinHeight is provided through databinding an ist set depending on if the second usercontrol is shown. Now: How can I set the size of the window to different values than the MinWidth/Height during runtime. I tried setting the values before the Show(), after the Show(), in various events (Initialized, Loaded, etc.). I tried with and without UpdateLayout(), I tried setting the Height/Width through databinding. Nothing works! But when I debug the approaches I see that the Height/Width properties of the window are set to the expected values, but ActualHeight/Width stay. I thought it would be a bagatelle but it turned out it is not (to me). Thy for any help.</p>

答:
I just simply set the window Height property.

Originally _myWindow.Height = 400;

And once the content required resizing I set it as follows:

double newWindowHeight = a + b; Where a + b make the window larger, and so:

_myWindow.Height = newWindowHeight;


问:
How to implement chat using jQuery, PHP, and MySQL?
I have made a chat script using php, mysql and jquery. It uses json to get data from the server. It makes fixed interval requests to the server with the lastly fetched message id to get new messages from the server. But when multiple users will be chatting then thousands and crores of requests will be made to the server within an hour and the hosting people will block it for sure.

Th gmail chat uses socket I think. Because it does not sends fixed interval requests for sure. Could any one of you please give me some sample code or some direction to solve this issue.

Please I need help desperately.

Many thanks in advance. My respect and regards for all.

答:
Why would the host block that? Your making a standard http request for a page, if your host doesn't allow that then it's time to switch.

As for using sockets, there is no native ability to connect to a socket via javascript, although I believe JSocket is a lib that allows you to bridge a socket through an embedded flash which is actually connected to your server. Haven't looked for a jquery plugin that does this, might be one.

Your server side code would also change drastically (persistent vs polling is very different) so you'd have your work cut out for you.

I recommend just doing what you are doing and upgrade your host if it can't handle it. Unless your going to have a huge number of users on at a time? A caching system so your not hitting the db on every single request can probably speed things up if it gets that busy.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ryeguy

OwnerDisplayName: savageguy


问:
Is there any technique to implement a cache in a fully immutable programming language?
I checked Haskell but even there they are using mutable data types internally.

Assuming everything is immutable, is there a way to have a cache?

Edit: Assume this is a general purpose cache which is supposed to keep the result of a computation (e.g. reading from a DB)

答:
I came across this post trying to do something similar to what the OP wanted to do, though I'm using Scala. In Scala, variables and objects can be mutable, so you can always use mutable types if you want.

But if not, in Haskell you could use the State monad, combined with Data.Map to model a stateful, mutable cache with immutable data. In Scala you could use the State monad in Cats with an immutable map.


问:
Timeout::Error using selenium-webdriver in ruby
I have been getting a Timeout error ever since I started developing my tests. At first I thought it was related to the efficiency of my xpaths but after seeing the test pass quickly numerous times I don't think it is related to the selectors. The error randomly occurs and often when it does it occurs multiple times within a feature. I need to fix or at least understand what this problem is.

An example of a step definition:

```<code>When /^I navigate to "(.*)"$/ do |webpage|
navigate_to(webpage)
end
</code>```

This is the error I get:

```<code> Timeout::Error (Timeout::Error)
      /usr/lib/ruby/1.9.1/net/protocol.rb:146:in `rescue in rbuf_fill'
      /usr/lib/ruby/1.9.1/net/protocol.rb:140:in `rbuf_fill'
      /usr/lib/ruby/1.9.1/net/protocol.rb:122:in `readuntil'
      /usr/lib/ruby/1.9.1/net/protocol.rb:132:in `readline'
      /usr/lib/ruby/1.9.1/net/http.rb:2562:in `read_status_line'
      /usr/lib/ruby/1.9.1/net/http.rb:2551:in `read_new'
      /usr/lib/ruby/1.9.1/net/http.rb:1319:in `block in transport_request'
      /usr/lib/ruby/1.9.1/net/http.rb:1316:in `catch'
      /usr/lib/ruby/1.9.1/net/http.rb:1316:in `transport_request'
      /usr/lib/ruby/1.9.1/net/http.rb:1293:in `request'
      /usr/lib/ruby/1.9.1/net/http.rb:1286:in `block in request'
      /usr/lib/ruby/1.9.1/net/http.rb:745:in `start'
      /usr/lib/ruby/1.9.1/net/http.rb:1284:in `request'
      ./features/support/env.rb:88:in `block in get_page_url'
</code>```

The env.rb :

```<code>require 'selenium-webdriver'
require 'rubygems'
require 'nokogiri'
require 'rspec'
require 'rspec/expectations'
require 'httpclient'
require 'fileutils.rb'
require 'pathname'

$driver = Selenium::WebDriver.for :ie
#accept_next_alert = true
$driver.manage.timeouts.implicit_wait = 300
$driver.manage.timeouts.script_timeout = 300
$driver.manage.timeouts.page_load = 300
#verification_errors = []

AfterStep do
 sleep 5
end

at_exit do
    $driver.close
end
</code>```

I have gone through numerous questions about this very same topic and none seem to have an answer that works, if an answer at all.

Similar issue. I have tried the solutions provided here but my error still persist
https://www.ruby-forum.com/topic/4414675

I have tried adding explicit waits as such:
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

I need to get this issue sorted out so please ask questions if I wasn't clear on anything.

Here is a list of installed gems:

```<code>archive-tar-minitar (0.5.2)
bigdecimal (1.1.0)
builder (3.2.0)
bundler (1.3.5)
childprocess (0.3.9)
columnize (0.3.6)
commonwatir (4.0.0)
cucumber (1.2.3)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.2.2)
diff-lcs (1.2.1)
ffi (1.5.0, 1.0.9)
gherkin (2.11.6)
hoe (3.6.2)
httpclient (2.3.2)
io-console (0.3)
json (1.7.7)
linecache19 (0.5.12)
mime-types (1.23)
mini_magick (3.6.0)
mini_portile (0.5.0)
minitest (2.12.1, 2.5.1)
multi_json (1.7.1)
nokogiri (1.5.9)
rack (1.5.2)
rack-test (0.6.2)
rake (10.0.3, 0.9.6)
rautomation (0.9.2)
rb-readline (0.5.0)
rdoc (3.12.1)
rspec (2.13.0)
rspec-core (2.13.1)
rspec-expectations (2.13.0)
rspec-mocks (2.13.0)
ruby-debug-base19 (0.11.25)
ruby-debug19 (0.11.6)
ruby_core_source (0.1.5)
rubygems-update (2.0.3)
rubyzip (0.9.9)
s4t-utils (1.0.4)
selenium-webdriver (2.33.0, 2.31.0)
subexec (0.2.3)
user-choices (1.1.6.1)
watir (4.0.2)
watir-classic (3.7.0)
watir-webdriver (0.6.2)
websocket (1.0.7)
win32-api (1.4.8)
win32-process (0.7.2)
win32screenshot (1.0.8)
windows-api (0.4.2)
windows-pr (1.2.2)
xml-simple (1.1.2)
xpath (2.0.0)
</code>```

答: Disabling --headless option was what worked in my case.

Body:
I have been getting a Timeout error ever since I started developing my tests. At first I thought it was related to the efficiency of my xpaths but after seeing the test pass quickly numerous times I don't think it is related to the selectors. The error randomly occurs and often when it does it occurs multiple times within a feature. I need to fix or at least understand what this problem is.

An example of a step definition:

When /^I navigate to "(.*)"$/ do |webpage|
navigate_to(webpage)
end

This is the error I get:

 Timeout::Error (Timeout::Error)
      /usr/lib/ruby/1.9.1/net/protocol.rb:146:in `rescue in rbuf_fill'
      /usr/lib/ruby/1.9.1/net/protocol.rb:140:in `rbuf_fill'
      /usr/lib/ruby/1.9.1/net/protocol.rb:122:in `readuntil'
      /usr/lib/ruby/1.9.1/net/protocol.rb:132:in `readline'
      /usr/lib/ruby/1.9.1/net/http.rb:2562:in `read_status_line'
      /usr/lib/ruby/1.9.1/net/http.rb:2551:in `read_new'
      /usr/lib/ruby/1.9.1/net/http.rb:1319:in `block in transport_request'
      /usr/lib/ruby/1.9.1/net/http.rb:1316:in `catch'
      /usr/lib/ruby/1.9.1/net/http.rb:1316:in `transport_request'
      /usr/lib/ruby/1.9.1/net/http.rb:1293:in `request'
      /usr/lib/ruby/1.9.1/net/http.rb:1286:in `block in request'
      /usr/lib/ruby/1.9.1/net/http.rb:745:in `start'
      /usr/lib/ruby/1.9.1/net/http.rb:1284:in `request'
      ./features/support/env.rb:88:in `block in get_page_url'

The env.rb :

require 'selenium-webdriver'
require 'rubygems'
require 'nokogiri'
require 'rspec'
require 'rspec/expectations'
require 'httpclient'
require 'fileutils.rb'
require 'pathname'

$driver = Selenium::WebDriver.for :ie
#accept_next_alert = true
$driver.manage.timeouts.implicit_wait = 300
$driver.manage.timeouts.script_timeout = 300
$driver.manage.timeouts.page_load = 300
#verification_errors = []

AfterStep do
 sleep 5
end

at_exit do
    $driver.close
end

I have gone through numerous questions about this very same topic and none seem to have an answer that works, if an answer at all.

Similar issue. I have tried the solutions provided here but my error still persist
https://www.ruby-forum.com/topic/4414675

I have tried adding explicit waits as such:
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

I need to get this issue sorted out so please ask questions if I wasn't clear on anything.

Here is a list of installed gems:

archive-tar-minitar (0.5.2)
bigdecimal (1.1.0)
builder (3.2.0)
bundler (1.3.5)
childprocess (0.3.9)
columnize (0.3.6)
commonwatir (4.0.0)
cucumber (1.2.3)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.2.2)
diff-lcs (1.2.1)
ffi (1.5.0, 1.0.9)
gherkin (2.11.6)
hoe (3.6.2)
httpclient (2.3.2)
io-console (0.3)
json (1.7.7)
linecache19 (0.5.12)
mime-types (1.23)
mini_magick (3.6.0)
mini_portile (0.5.0)
minitest (2.12.1, 2.5.1)
multi_json (1.7.1)
nokogiri (1.5.9)
rack (1.5.2)
rack-test (0.6.2)
rake (10.0.3, 0.9.6)
rautomation (0.9.2)
rb-readline (0.5.0)
rdoc (3.12.1)
rspec (2.13.0)
rspec-core (2.13.1)
rspec-expectations (2.13.0)
rspec-mocks (2.13.0)
ruby-debug-base19 (0.11.25)
ruby-debug19 (0.11.6)
ruby_core_source (0.1.5)
rubygems-update (2.0.3)
rubyzip (0.9.9)
s4t-utils (1.0.4)
selenium-webdriver (2.33.0, 2.31.0)
subexec (0.2.3)
user-choices (1.1.6.1)
watir (4.0.2)
watir-classic (3.7.0)
watir-webdriver (0.6.2)
websocket (1.0.7)
win32-api (1.4.8)
win32-process (0.7.2)
win32screenshot (1.0.8)
windows-api (0.4.2)
windows-pr (1.2.2)
xml-simple (1.1.2)
xpath (2.0.0)


问:
How can I create a timeline of multiple subjects without using dates in R?
I have a dataset of subjects that I want to compare based on Days After Treatment rather than the actual dates of their treatments and follow ups.

My thought process is that it would be way easier to visualize if all the subjects would start at the same point and end at the same point rather than be spread across multiple years due to subjects starting at different times.

Is there a way to do this in R? I've looked at vistime, which looks promising except that start/end are supposed to be dates.

Here's an example of what my data looks like:

```<code>df <- data.frame(Patient = c(1,1,1,2,2,2,3,3,3),
                 Response = c("PR", "CR", "CR", "SD", "SD", "PD", "PR", "PR", "CR"),
                 Start = rep(c("Day 30", "Day 90", "Day 180")),
                 End = rep(c("Day 90", "Day 180", "Day 270")))
</code>```

Example Data

答:
So from the example you posted your data isn't actually numeric or date, it's text.

```<code>df <- data.frame(Patient = c(1,1,1,2,2,2,3,3,3),
                 Response = c("PR", "CR", "CR", "SD", "SD", "PD", "PR", "PR", "CR"),
                 Start = rep(c("Day 30", "Day 90", "Day 180")),
                 End = rep(c("Day 90", "Day 180", "Day 270")))

  Patient Response   Start     End
1       1       PR  Day 30  Day 90
2       1       CR  Day 90 Day 180
3       1       CR Day 180 Day 270
4       2       SD  Day 30  Day 90
5       2       SD  Day 90 Day 180
6       2       PD Day 180 Day 270
7       3       PR  Day 30  Day 90
8       3       PR  Day 90 Day 180
9       3       CR Day 180 Day 270
</code>```

To work with text there are a bunch of options, including tidyverse below (there's also base, plus others).

```<code>library(dplyr)
library(stringr)
df %>%
  mutate(Start = as.numeric(str_extract(Start, "[:digit:]+")),
         End = as.numeric(str_extract(End, "[:digit:]+")),
         Difference = End - Start,
         )
</code>```

What I've done is extracted the numeric portion of your start and end dates and then subtracted them.  That's what you're looking for right?

```<code>  Patient Response Start End Difference
1       1       PR    30  90         60
2       1       CR    90 180         90
3       1       CR   180 270         90
4       2       SD    30  90         60
5       2       SD    90 180         90
6       2       PD   180 270         90
7       3       PR    30  90         60
8       3       PR    90 180         90
9       3       CR   180 270         90
</code>```

Body:
I have a dataset of subjects that I want to compare based on Days After Treatment rather than the actual dates of their treatments and follow ups.

My thought process is that it would be way easier to visualize if all the subjects would start at the same point and end at the same point rather than be spread across multiple years due to subjects starting at different times.

Is there a way to do this in R? I've looked at vistime, which looks promising except that start/end are supposed to be dates.

Here's an example of what my data looks like:

df <- data.frame(Patient = c(1,1,1,2,2,2,3,3,3),
                 Response = c("PR", "CR", "CR", "SD", "SD", "PD", "PR", "PR", "CR"),
                 Start = rep(c("Day 30", "Day 90", "Day 180")),
                 End = rep(c("Day 90", "Day 180", "Day 270")))

Example Data

Body:
So from the example you posted your data isn't actually numeric or date, it's text.

df <- data.frame(Patient = c(1,1,1,2,2,2,3,3,3),
                 Response = c("PR", "CR", "CR", "SD", "SD", "PD", "PR", "PR", "CR"),
                 Start = rep(c("Day 30", "Day 90", "Day 180")),
                 End = rep(c("Day 90", "Day 180", "Day 270")))

  Patient Response   Start     End
1       1       PR  Day 30  Day 90
2       1       CR  Day 90 Day 180
3       1       CR Day 180 Day 270
4       2       SD  Day 30  Day 90
5       2       SD  Day 90 Day 180
6       2       PD Day 180 Day 270
7       3       PR  Day 30  Day 90
8       3       PR  Day 90 Day 180
9       3       CR Day 180 Day 270

To work with text there are a bunch of options, including tidyverse below (there's also base, plus others).

library(dplyr)
library(stringr)
df %>%
  mutate(Start = as.numeric(str_extract(Start, "[:digit:]+")),
         End = as.numeric(str_extract(End, "[:digit:]+")),
         Difference = End - Start,
         )

What I've done is extracted the numeric portion of your start and end dates and then subtracted them.  That's what you're looking for right?

  Patient Response Start End Difference
1       1       PR    30  90         60
2       1       CR    90 180         90
3       1       CR   180 270         90
4       2       SD    30  90         60
5       2       SD    90 180         90
6       2       PD   180 270         90
7       3       PR    30  90         60
8       3       PR    90 180         90
9       3       CR   180 270         90


问:
is it possible to create a generic closure in Swift?
```<code>func myfunc<T>(i:T) -> T {
    return i
}
</code>```

is it possible to make this generic function a closure?

```<code>let myfunc = { <T>(i:T) -> T in
    return i
}
</code>```

this doesn't work...

答:
Probably you need something like this.

Type declaration:

```<code>typealias ResultClosure<T> = (ResultCode, String?, T?) -> Void
</code>```

Function declaration:

```<code>func loginUser(userName: String, password: String, resultHandler: ResultClosure<TokenModel>?)
</code>```

Usage:

```<code>    NetConnector.shared.loginUser(userName: userName ?? "", password: password ?? "") { (code, message, data) in
        self.display?.unlockScreen()
        if code == .success {
            if let activeToken = data {
                AppData.shared.userToken = activeToken
            }
            self.display?.showHome()
        } else {
            self.display?.showError(errorMessage: message)
        }
    }
</code>```

Body:
func myfunc<T>(i:T) -> T {
    return i
}

is it possible to make this generic function a closure?

let myfunc = { <T>(i:T) -> T in
    return i
}

this doesn't work...

Body:
Probably you need something like this.

Type declaration:

typealias ResultClosure<T> = (ResultCode, String?, T?) -> Void

Function declaration:

func loginUser(userName: String, password: String, resultHandler: ResultClosure<TokenModel>?)

Usage:

    NetConnector.shared.loginUser(userName: userName ?? "", password: password ?? "") { (code, message, data) in
        self.display?.unlockScreen()
        if code == .success {
            if let activeToken = data {
                AppData.shared.userToken = activeToken
            }
            self.display?.showHome()
        } else {
            self.display?.showError(errorMessage: message)
        }
    }


问:
h2o - AttributeError: type object 'ModelBase' has no attribute 'hit_ratio_table'
I'm following a tutorial from https://github.com/h2oai/h2o-tutorials/blob/master/tutorials/gbm-randomforest/GBM_RandomForest_Example.py

I have been following the tutorial until I reached the line with hit_ratio_table. when I executed "rf_v1.hit_ratio_table(valid=True)", I encounter the error below.

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-21-ff67e4484e12> in <module>
----> 1 rf_v1.hit_ratio_table(valid=True)

~\Anaconda3\lib\site-packages\h2o\utils\metaclass.py in __getattr__(self, name)
    191             if name in self._bci:
    192                 return self._bci[name]
--> 193             return getattr(new_clz, name)
    194
    195         new_clz = extend_and_replace(clz, __init__=__init__, __getattr__=__getattr__)

~\Anaconda3\lib\site-packages\h2o\utils\metaclass.py in __getattribute__(cls, name)
    233             if attr is not MetaFeature.NOT_FOUND:
    234                 return attr
--> 235         return type.__getattribute__(cls, name)
    236
    237     def __setattr__(cls, name, value):

AttributeError: type object 'ModelBase' has no attribute 'hit_ratio_table'
</code>```

I have tried to converts the target to a factor using df.asfactor() but still not working.

答:
Just try to use the below example, its working fine for me, the error can be due to h2o cluster version, I have included mine and also the results for the h2o.hit_ratio_table

```<code>import h2o
h2o.init(
  nthreads=-1,            ## -1: use all available threads
  max_mem_size = "8G")

from h2o.estimators import H2ORandomForestEstimator
cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")

# set the factor:
cars["cylinders"] = cars["cylinders"].asfactor()

# split the training and validation sets:
r = cars[0].runif()
train = cars[r > .2]
valid = cars[r <= .2]

# set the predictors columns, repsonse column, and distribution type:
predictors = ["displacement","power","weight","acceleration","year"]
response_col = "cylinders"
distribution = "multinomial"

# build and train the model:
drf = H2ORandomForestEstimator(nfolds = 3, distribution = distribution)
drf.train(x=predictors, y=response_col, training_frame=train, validation_frame=valid)

# build the hit ratio table:
drf_hit = drf.hit_ratio_table(valid=True)
drf_hit.show()
</code>```

Output:

```<code>H2O cluster uptime: 02 secs
H2O cluster timezone:   Etc/UTC
H2O data parsing timezone:  UTC
H2O cluster version:    3.26.0.10
H2O cluster version age:    3 months and 12 days !!!
H2O cluster name:   H2O_from_python_unknownUser_wggipn
H2O cluster total nodes:    1
H2O cluster free memory:    7.111 Gb
H2O cluster total cores:    4
H2O cluster allowed cores:  4
H2O cluster status: accepting new members, healthy
H2O connection url: http://127.0.0.1:54321
H2O connection proxy:   {'http': None, 'https': None}
H2O internal security:  False
H2O API Extensions: Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4
Python version: 3.6.6 final
</code>```

```<code>
k   hit_ratio
0   1   0.988235
1   2   0.988235
2   3   1.000000
3   4   1.000000
4   5   1.000000
</code>```

Body:
I'm following a tutorial from https://github.com/h2oai/h2o-tutorials/blob/master/tutorials/gbm-randomforest/GBM_RandomForest_Example.py

I have been following the tutorial until I reached the line with hit_ratio_table. when I executed "rf_v1.hit_ratio_table(valid=True)", I encounter the error below.

AttributeError                            Traceback (most recent call last)
<ipython-input-21-ff67e4484e12> in <module>
----> 1 rf_v1.hit_ratio_table(valid=True)

~\Anaconda3\lib\site-packages\h2o\utils\metaclass.py in __getattr__(self, name)
    191             if name in self._bci:
    192                 return self._bci[name]
--> 193             return getattr(new_clz, name)
    194
    195         new_clz = extend_and_replace(clz, __init__=__init__, __getattr__=__getattr__)

~\Anaconda3\lib\site-packages\h2o\utils\metaclass.py in __getattribute__(cls, name)
    233             if attr is not MetaFeature.NOT_FOUND:
    234                 return attr
--> 235         return type.__getattribute__(cls, name)
    236
    237     def __setattr__(cls, name, value):

AttributeError: type object 'ModelBase' has no attribute 'hit_ratio_table'

I have tried to converts the target to a factor using df.asfactor() but still not working.

Body:
Just try to use the below example, its working fine for me, the error can be due to h2o cluster version, I have included mine and also the results for the h2o.hit_ratio_table

import h2o
h2o.init(
  nthreads=-1,            ## -1: use all available threads
  max_mem_size = "8G")

from h2o.estimators import H2ORandomForestEstimator
cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")

# set the factor:
cars["cylinders"] = cars["cylinders"].asfactor()

# split the training and validation sets:
r = cars[0].runif()
train = cars[r > .2]
valid = cars[r <= .2]

# set the predictors columns, repsonse column, and distribution type:
predictors = ["displacement","power","weight","acceleration","year"]
response_col = "cylinders"
distribution = "multinomial"

# build and train the model:
drf = H2ORandomForestEstimator(nfolds = 3, distribution = distribution)
drf.train(x=predictors, y=response_col, training_frame=train, validation_frame=valid)

# build the hit ratio table:
drf_hit = drf.hit_ratio_table(valid=True)
drf_hit.show()

Output:

H2O cluster uptime: 02 secs
H2O cluster timezone:   Etc/UTC
H2O data parsing timezone:  UTC
H2O cluster version:    3.26.0.10
H2O cluster version age:    3 months and 12 days !!!
H2O cluster name:   H2O_from_python_unknownUser_wggipn
H2O cluster total nodes:    1
H2O cluster free memory:    7.111 Gb
H2O cluster total cores:    4
H2O cluster allowed cores:  4
H2O cluster status: accepting new members, healthy
H2O connection url: http://127.0.0.1:54321
H2O connection proxy:   {'http': None, 'https': None}
H2O internal security:  False
H2O API Extensions: Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4
Python version: 3.6.6 final

k   hit_ratio
0   1   0.988235
1   2   0.988235
2   3   1.000000
3   4   1.000000
4   5   1.000000


问:
Merging non-empty elements with same id into single item using XSLT
I want to merge items with same id into single item. The resultant item needs to have first non-empty element from the item group. If there is no non-empty element in the item group then the element itself ignored from the item group and should not present in the resultant item.

Sample XML Input:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<shiporder orderid="orderid106">
   <orderperson id="123">orderperson107</orderperson>
   <shipto>
      <name>name108</name>
      <address>address109</address>
      <city>city110</city>
      <country>country111</country>
   </shipto>

   <!--Item Group 100-->
   <item>
      <id>100</id>
      <title>
         <first>
            <a></a>
         </first>
         <last>item100_lastTitle1</last>
      </title>
      <note></note>
      <quantity></quantity>
   </item>
   <item>
      <id>100</id>
      <title>
         <first>
            <a>a_100_2</a>
         </first>
         <last>item100_lastTitle2</last>
      </title>
      <note>note100_2</note>
      <quantity></quantity>
   </item>
   <item>
      <id>100</id>
      <title>
         <first>
            <a att1="abc" att2='cde'>a_100_3</a>
         </first>
         <last id="1" attr="2">item100_lastTitle3</last>
      </title>
      <note>note100_3</note>
      <quantity>1</quantity>
   </item>

   <!--Item Group 101-->
   <item>
      <id>101</id>
      <title>
         <first>
            <a>a_101_1</a>
         </first>
         <last></last>
      </title>
      <note>note101_1</note>
      <quantity>10</quantity>
   </item>
   <item>
      <id>101</id>
      <title>
         <first>
            <a>a_101_2</a>
         </first>
         <last>item101_lastTitle2</last>
      </title>
      <note>note101_2</note>
      <quantity>5</quantity>
   </item>

   <!--Item Group 103-->
   <item>
      <id>103</id>
      <title>
         <first>
            <a>a_103_2</a>
         </first>
         <last>item103_lastTitle2</last>
      </title>
      <note>note103_1</note>
      <quantity></quantity>
   </item>
</shiporder>
</code>```

Sample XML Output:

```<code><?xml version = '1.0' encoding = 'UTF-8'?>
<shiporder orderid="orderid106">
  <item>
    <id>100</id>
    <title>
      <first>
        <a>a_100_2</a>
      </first>
      <last>item100_lastTitle1</last>
    </title>
    <note>note100_2</note>
    <quantity>6</quantity>
  </item>

  <item>
    <id>101</id>
    <title>
      <first>
        <a>a_101_1</a>
      </first>
      <last>item101_lastTitle2</last>
    </title>
    <note>note101_1</note>
    <quantity>10</quantity>
  </item>

  <item>
    <id>103</id>
    <title>
      <first>
        <a>a_103_2</a>
      </first>
      <last>item103_lastTitle2</last>
    </title>
    <note>note103_1</note>
  </item>
</shiporder>
</code>```

I tried with the following XSL code to get the above output:

```<code><?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/shiporder">
      <shiporder>
         <xsl:if test="@orderid">
            <xsl:attribute name="orderid">
               <xsl:value-of select="@orderid"/>
            </xsl:attribute>
         </xsl:if>

         <!-- Grouping each item based on its ID element value-->
         <xsl:for-each-group select="item" group-by="id">
            <item-group>
               <!-- For Each group search for first non empty child element-->
               <xsl:for-each select="current-group()[id/text()][1]">
                  <xsl:copy-of select="id"/>
               </xsl:for-each>
               <title>
                  <first>
                     <!-- for 'a' element -->
                     <xsl:variable name="temp1">
                        <xsl:for-each select="current-group()/title/first[a/text()][1]">
                           <elm>
                              <xsl:copy-of select="a"/>
                           </elm>
                        </xsl:for-each>
                     </xsl:variable>
                     <xsl:copy-of select="$temp1/elm[1]/a"/>
                  </first>

                  <!-- for 'last' element -->
                  <xsl:variable name="temp2">
                     <xsl:for-each select="current-group()/title[last/text()][1]">
                        <elm>
                           <xsl:copy-of select="last"/>
                        </elm>
                     </xsl:for-each>
                  </xsl:variable>
                  <xsl:copy-of select="$temp2/elm[1]/last"/>
               </title>

               <!-- for 'note' element -->
               <xsl:for-each select="current-group()[note/text()][1]">
                  <xsl:copy-of select="note"/>
               </xsl:for-each>

               <!-- for 'quantity' element -->
               <xsl:for-each select="current-group()[quantity/text()][1]">
                  <xsl:copy-of select="quantity"/>
               </xsl:for-each>

            </item-group>
         </xsl:for-each-group>
      </shiporder>
   </xsl:template>
</xsl:stylesheet>
</code>```

The code works fine But the worst part is, I couldn’t make it generalize. For each element under the item I need to write a xsl code specific to the xpath of particular element. I couldn’t even write code in terms of user-defined-templates.

I found already answered question in the title of "Recursively combine identical sibling elements in XSLT". But I'm not able to customize it according to my requirements.

I'm having hundreds of such child or decedent element under each item and the depth of each one is arbitrary. It is very ridiculous to write xsl code corresponds to each of those child or descendants. Can any of the experts guide me to write generic xsl code (irrespective of number of elements and also its depth) or optimize the existing code?

Thanks in advance,

Kathir

答:
This is actually an XSLT 1.0 solution (I don't have an XSLT2 processor to hand), but it uses a generic 'combine' named template that should do what you need.

```<code><?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:key name="item" use="id" match="item" />

  <xsl:template match="item[generate-id() = generate-id(key('item',id)[1])]">
    <xsl:call-template name="combine">
      <xsl:with-param name="list" select="../*[id = current()/id]" />
    </xsl:call-template>
  </xsl:template>

  <xsl:template match="item" />

  <xsl:template name="combine">
    <xsl:param name="list" />
    <xsl:element name="{name($list[1])}">
      <xsl:for-each select="*[not(preceding-sibling::*[name() = name(current())])]" >
        <xsl:call-template name="combine">
          <xsl:with-param name="list" select="$list/*[name() = name(current())]" />
        </xsl:call-template>
      </xsl:for-each>
      <xsl:value-of select="$list[text()][1]/text()" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

The combine template takes a list of nodes, and combines them into one recursively, taking the first available value for each node. This template does NOT combine attributes as well, but as you don't have any in the item XML you provided, this should be OK. The <xsl:for-each in the middle of the template uses an XSLT1 technique for picking out unique element names; it only selects those that don't have a previous sibling with the same name. There's probably a way of doing this using for-each-group in XSLT2, but I can't check that here.

Body:
I want to merge items with same id into single item. The resultant item needs to have first non-empty element from the item group. If there is no non-empty element in the item group then the element itself ignored from the item group and should not present in the resultant item.

Sample XML Input:

<?xml version="1.0" encoding="UTF-8" ?>
<shiporder orderid="orderid106">
   <orderperson id="123">orderperson107</orderperson>
   <shipto>
      <name>name108</name>
      <address>address109</address>
      <city>city110</city>
      <country>country111</country>
   </shipto>

   <item>
      <id>100</id>
      <title>
         <first>

         </first>
         <last>item100_lastTitle1</last>
      </title>
      <note></note>
      <quantity></quantity>
   </item>
   <item>
      <id>100</id>
      <title>
         <first>
            a_100_2
         </first>
         <last>item100_lastTitle2</last>
      </title>
      <note>note100_2</note>
      <quantity></quantity>
   </item>
   <item>
      <id>100</id>
      <title>
         <first>
            a_100_3
         </first>
         <last id="1" attr="2">item100_lastTitle3</last>
      </title>
      <note>note100_3</note>
      <quantity>1</quantity>
   </item>

   <item>
      <id>101</id>
      <title>
         <first>
            a_101_1
         </first>
         <last></last>
      </title>
      <note>note101_1</note>
      <quantity>10</quantity>
   </item>
   <item>
      <id>101</id>
      <title>
         <first>
            a_101_2
         </first>
         <last>item101_lastTitle2</last>
      </title>
      <note>note101_2</note>
      <quantity>5</quantity>
   </item>

   <item>
      <id>103</id>
      <title>
         <first>
            a_103_2
         </first>
         <last>item103_lastTitle2</last>
      </title>
      <note>note103_1</note>
      <quantity></quantity>
   </item>
</shiporder>

Sample XML Output:

<?xml version = '1.0' encoding = 'UTF-8'?>
<shiporder orderid="orderid106">
  <item>
    <id>100</id>
    <title>
      <first>
        a_100_2
      </first>
      <last>item100_lastTitle1</last>
    </title>
    <note>note100_2</note>
    <quantity>6</quantity>
  </item>

  <item>
    <id>101</id>
    <title>
      <first>
        a_101_1
      </first>
      <last>item101_lastTitle2</last>
    </title>
    <note>note101_1</note>
    <quantity>10</quantity>
  </item>

  <item>
    <id>103</id>
    <title>
      <first>
        a_103_2
      </first>
      <last>item103_lastTitle2</last>
    </title>
    <note>note103_1</note>
  </item>
</shiporder>

I tried with the following XSL code to get the above output:

<?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/shiporder">
      <shiporder>
         <xsl:if test="@orderid">
            <xsl:attribute name="orderid">
               <xsl:value-of select="@orderid"/>
            </xsl:attribute>
         </xsl:if>

         <xsl:for-each-group select="item" group-by="id">
            <item-group>

               <xsl:for-each select="current-group()[id/text()][1]">
                  <xsl:copy-of select="id"/>
               </xsl:for-each>
               <title>
                  <first>

                     <xsl:variable name="temp1">
                        <xsl:for-each select="current-group()/title/first[a/text()][1]">
                           <elm>
                              <xsl:copy-of select="a"/>
                           </elm>
                        </xsl:for-each>
                     </xsl:variable>
                     <xsl:copy-of select="$temp1/elm[1]/a"/>
                  </first>

                  <xsl:variable name="temp2">
                     <xsl:for-each select="current-group()/title[last/text()][1]">
                        <elm>
                           <xsl:copy-of select="last"/>
                        </elm>
                     </xsl:for-each>
                  </xsl:variable>
                  <xsl:copy-of select="$temp2/elm[1]/last"/>
               </title>

               <xsl:for-each select="current-group()[note/text()][1]">
                  <xsl:copy-of select="note"/>
               </xsl:for-each>

               <xsl:for-each select="current-group()[quantity/text()][1]">
                  <xsl:copy-of select="quantity"/>
               </xsl:for-each>

            </item-group>
         </xsl:for-each-group>
      </shiporder>
   </xsl:template>
</xsl:stylesheet>

The code works fine But the worst part is, I couldn’t make it generalize. For each element under the item I need to write a xsl code specific to the xpath of particular element. I couldn’t even write code in terms of user-defined-templates.

I found already answered question in the title of "Recursively combine identical sibling elements in XSLT". But I'm not able to customize it according to my requirements.

I'm having hundreds of such child or decedent element under each item and the depth of each one is arbitrary. It is very ridiculous to write xsl code corresponds to each of those child or descendants. Can any of the experts guide me to write generic xsl code (irrespective of number of elements and also its depth) or optimize the existing code?

Thanks in advance,

Kathir

Body:
This is actually an XSLT 1.0 solution (I don't have an XSLT2 processor to hand), but it uses a generic 'combine' named template that should do what you need.

<?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:key name="item" use="id" match="item" />

  <xsl:template match="item[generate-id() = generate-id(key('item',id)[1])]">
    <xsl:call-template name="combine">
      <xsl:with-param name="list" select="../*[id = current()/id]" />
    </xsl:call-template>
  </xsl:template>

  <xsl:template match="item" />

  <xsl:template name="combine">
    <xsl:param name="list" />
    <xsl:element name="{name($list[1])}">
      <xsl:for-each select="*[not(preceding-sibling::*[name() = name(current())])]" >
        <xsl:call-template name="combine">
          <xsl:with-param name="list" select="$list/*[name() = name(current())]" />
        </xsl:call-template>
      </xsl:for-each>
      <xsl:value-of select="$list[text()][1]/text()" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

The combine template takes a list of nodes, and combines them into one recursively, taking the first available value for each node. This template does NOT combine attributes as well, but as you don't have any in the item XML you provided, this should be OK. The <xsl:for-each in the middle of the template uses an XSLT1 technique for picking out unique element names; it only selects those that don't have a previous sibling with the same name. There's probably a way of doing this using for-each-group in XSLT2, but I can't check that here.


问:
What is wrapperEl in canvas in FabricJS?
https://github.com/salgum1114/react-design-editor/blob/8db73ef3d9846444e25657a5414b417633b1ef0e/src/components/Canvas.js

I have gone through the code on the above link. But I can't seem to understand Line 495 where its written this.canvas.wrapperEl as it is not defined anywhere.

答:
This is a reference to the wrapper div element that fabric.js wraps around the actual canvas it draws on. This property is intended for internal use, that's why there is no mention of it in the docs.

If you inspect the HTML on a page that uses a fabric.js canvas in it, you'll see something like this:

  <canvas id="c" width="1000" height="800" class="lower-canvas" style="..."></canvas>
  <canvas class="upper-canvas" width="500" height="400" style="..."></canvas>

```

The canvas-container div is your wrapperEl.

Body:
This is a reference to the wrapper div element that fabric.js wraps around the actual canvas it draws on. This property is intended for internal use, that's why there is no mention of it in the docs.

If you inspect the HTML on a page that uses a fabric.js canvas in it, you'll see something like this:

<div class="canvas-container" style="...">
  <canvas id="c" width="1000" height="800" class="lower-canvas" style="..."></canvas>
  <canvas class="upper-canvas" width="500" height="400" style="..."></canvas>
</div>

The canvas-container div is your wrapperEl.


问:
How to Send MS Word Application to Background Using VB Script?
I have written below piece of code using VBA that creates a blank MS Word document with given no. of pages. The VB function works just fine but the problem is that when it runs it pops up MS Word in foreground despite wordApplication.Visible = False. As this function needs to be called inside a loop for N no. of documents, the repetitive flashing of Word screen becomes very annoying to the user.

Is there a solution to this problem? Can the application be sent to background so that it could neither appear in front nor in taskbar and user could go about his work smoothly without distractions.

```<code>Function CreateEmptyDoc(lngPages, strNewFile)

Dim wordApplication
Dim wordDocuments
Dim wordDocument
Dim objPage

Set wordApplication = CreateObject("Word.Application")
wordApplication.Visible = False
Set wordDocuments = wordApplication.Documents
wordApplication.WordBasic.DisableAutoMacros

Set wordDocument = wordDocuments.Add
'Msgbox wordDocument.Name

wordDocument.Activate

For i = 1 To (lngPages - 1) Step +1
   Set objPage = wordDocument.GoTo(1, 1, i)
   objPage.InsertBreak 7
Next

If wordDocument.SaveAs2(strNewFile, 1) = True Then
   CreateEmptyDoc = True
End If

wordDocuments.Close(0)
wordApplication.Quit

Set wordDocument = Nothing
Set wordDocuments = Nothing
Set wordApplication = Nothing

End Function
</code>```

Any pointers would be really helpful.

答:
I suspect the problem is caused by your unnecessary activation of the document. Try:</p>

```<code>Function CreateEmptyDoc(lngPages, strNewFile)
Dim wdApp, wdDoc, objPage
Set wdApp = CreateObject("Word.Application")
With wdApp
  .Visible = False
  .WordBasic.DisableAutoMacros
  Set wdDoc = .Documents.Add , , , 0
  With wdDoc
    For i = 1 To (lngPages - 1) Step +1
     Set objPage = .GoTo(1, 1, i)
     objPage.InsertBreak 7
    Next
    If .SaveAs2(strNewFile, 1) = True Then CreateEmptyDoc = True
    .Close(0)
  End With
  .Quit
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Function
</code>```

Body:
I have written below piece of code using VBA that creates a blank MS Word document with given no. of pages. The VB function works just fine but the problem is that when it runs it pops up MS Word in foreground despite wordApplication.Visible = False. As this function needs to be called inside a loop for N no. of documents, the repetitive flashing of Word screen becomes very annoying to the user.

Is there a solution to this problem? Can the application be sent to background so that it could neither appear in front nor in taskbar and user could go about his work smoothly without distractions.

Function CreateEmptyDoc(lngPages, strNewFile)

Dim wordApplication
Dim wordDocuments
Dim wordDocument
Dim objPage

Set wordApplication = CreateObject("Word.Application")
wordApplication.Visible = False
Set wordDocuments = wordApplication.Documents
wordApplication.WordBasic.DisableAutoMacros

Set wordDocument = wordDocuments.Add
'Msgbox wordDocument.Name

wordDocument.Activate

For i = 1 To (lngPages - 1) Step +1
   Set objPage = wordDocument.GoTo(1, 1, i)
   objPage.InsertBreak 7
Next

If wordDocument.SaveAs2(strNewFile, 1) = True Then
   CreateEmptyDoc = True
End If

wordDocuments.Close(0)
wordApplication.Quit

Set wordDocument = Nothing
Set wordDocuments = Nothing
Set wordApplication = Nothing

End Function

Any pointers would be really helpful.

Body:
I suspect the problem is caused by your unnecessary activation of the document. Try:

Function CreateEmptyDoc(lngPages, strNewFile)
Dim wdApp, wdDoc, objPage
Set wdApp = CreateObject("Word.Application")
With wdApp
  .Visible = False
  .WordBasic.DisableAutoMacros
  Set wdDoc = .Documents.Add , , , 0
  With wdDoc
    For i = 1 To (lngPages - 1) Step +1
     Set objPage = .GoTo(1, 1, i)
     objPage.InsertBreak 7
    Next
    If .SaveAs2(strNewFile, 1) = True Then CreateEmptyDoc = True
    .Close(0)
  End With
  .Quit
End With
Set wdDoc = Nothing: Set wdApp = Nothing
End Function


问:
OCR Exception:Iron OCR InstallationPath Permission Error 1772
I'm trying to use Iron OCR's library for OCR, I came across this error while trying to do the basics.

AutoOcr OCR = new AutoOcr() { ReadBarCodes = false };
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var Results = OCR.Read(@"Screenshot.png");
Console.WriteLine(Results.Text);
```

OCR Exception:Iron OCR InstallationPath Permission Error 1772.   Could not deploy and run IronOCR resources to path '' for user 'MYPCNAME\MYUSER'.  This can be fixed globally by setting IronOcrInstallation.InstallationPath to a directory on disk with file read and write permissions.  Please refer to documentation at http://ironsoftware.com/csharp/ocr/docs/html/P_IronOcr_IronOcrInstallation_InstallationPath.htm

This is the full error I get every time I try to run this code. If anyone could give me a hand, I'd appreciate it. Thanks!

答: That permission message is pretty misleading and wrong for most of the cases, I solved it by installing the c++ runtime (32+64) and it works like a charm!</p>

Body:
I'm trying to use Iron OCR's library for OCR, I came across this error while trying to do the basics.

AutoOcr OCR = new AutoOcr() { ReadBarCodes = false };
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var Results = OCR.Read(@"Screenshot.png");
Console.WriteLine(Results.Text);

OCR Exception:Iron OCR InstallationPath Permission Error 1772.   Could not deploy and run IronOCR resources to path '' for user 'MYPCNAME\MYUSER'.  This can be fixed globally by setting IronOcrInstallation.InstallationPath to a directory on disk with file read and write permissions.  Please refer to documentation at http://ironsoftware.com/csharp/ocr/docs/html/P_IronOcr_IronOcrInstallation_InstallationPath.htm

This is the full error I get every time I try to run this code. If anyone could give me a hand, I'd appreciate it. Thanks!


问:
Extract all values when I have key : value and store all value in an array
If I have an array,I want to extract each values in each line (values after (:) )

```<code>Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}
</code>```

Imagine I have several key : value then I want to extract Just value like bellow:

```<code>Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

</code>```

I have the result like this :

```<code>var result = ["value","value2",value3","value5","value6","value7"];
</code>```

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

答:
You can try looping through the array and concat the values like so

results = results.concat( Object.values( yourArray[loopIndex] ) )

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value2",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start