问:
Need Tips for RFID ZPL for Zebra ZD500R Printer
Working on printing and encoding RFID labels with the Zebra ZD500R Printer.

Here is my ZPL:  The field data is F1001001, which i can encode and print on the label.  However the EPC returned is F10010010000000000000000.  How can i do one of 2 things.  Either get the ZPL to 4 Bytes with no 0's or encode random hexadecimals at the front and my field data at the end?

My other question is how do make my field data increment and have both the RFID encoded tag and label match?

`^XA

^BCN,100,N,N

^FO30,50^FDF1001001^FS

^FO30,160^ADN,18,15^FDF1001001^FS

^FO30,220^ADN,10,20^^FD12/1/2024^FS

^FO30,260^ADN,10,20^^FDUYT 098^FS

^RFW,H^FDF1001001^FS

^RFR,H^FN11^FS

^FH^HV11,,EPC:[,]_0D_0A,L

^XZ`

答:
I know I'm a bit late to the party but it might be useful if someone else stumbles over this post...

Try:

```<code>^RS8
^RFW,H,,,A^FD12345678^FS
</code>```

When read with a RFID reader this will return the EPC code 12345678 without the trailing zeros (or encode random hexadecimals).  For reference this was written to a tag using a Zebra ZQ511.

https://www.zebra.com/content/dam/zebra_new_ia/en-us/manuals/printers/common/programming/rfid3-pg-en.pdf

Body:
I know I'm a bit late to the party but it might be useful if someone else stumbles over this post...

Try:

^RS8
^RFW,H,,,A^FD12345678^FS

When read with a RFID reader this will return the EPC code 12345678 without the trailing zeros (or encode random hexadecimals).  For reference this was written to a tag using a Zebra ZQ511.

https://www.zebra.com/content/dam/zebra_new_ia/en-us/manuals/printers/common/programming/rfid3-pg-en.pdf


来源: stackexchange

问:
Passing an element to function, creating id variable, using this variable to smooth scroll to element
I am trying to work out why the following is happening.

I am trying to:

Click an element.

On click, pass a DOM element to a function.

Use this DOM element within the function to create a target ID.

Smooth Scroll to this target ID>

Here is my code:

VARIABLE:

```<code>var productListQueryResult  = $('#product-list-query-result');
</code>```

TRIGGER:

```<code>scrollToDiv(productListQueryResult);
</code>```

FUNCTION:

```<code>// TO TOP OF ELEMENT
function scrollToDiv(e) {
    var el = e.attr('id');
    $('html, body').animate({
        scrollTop: $("#" + el).offset().top
    }, 300);
    console.log(el);
}
// END TO TOP OF ELEMENT
</code>```

RESULT:

```<code>jquery.js?ver=1.12.4-wp:2 Uncaught Error: Syntax error, unrecognized expression: '#product-list-query-result'
</code>```

Although this element is in existence. If I run:

```<code>var e = jQuery("#product-list-query-result");
console.log(e);
</code>```

I get two lines returned:

```<code>a.fn.init [div#product-list-query-result, context: document, selector: "#product-list-query-result"]
undefined
</code>```

I'm unsure as to why I get a second line returned too 'undefined', can anyone explain that too?

Hopefully I have provided enough information, if not please feel free to start a discussion.

Edit

I have also tried:

TRIGGER:

```<code>scrollToDiv(productListQueryResult.attr('id'));
</code>```

FUNCTION:

```<code>// TO TOP OF ELEMENT
function scrollToDiv(e) {
    var el = "'#" + e + "'";
    $('html, body').animate({
        scrollTop: $(el).offset().top
    }, 300);
    console.log(el);
}
// END TO TOP OF ELEMENT
</code>```

RESULT:

```<code>Uncaught Error: Syntax error, unrecognized expression: '#product-list-query-result'
</code>```

EDIT (SOLUTION):

If passing a variable into the selector you do not require the ""'s.

FUNCTION:

```<code>// TO TOP OF ELEMENT
function scrollToDiv(e) {
    var el = "#" + e;
    $('html, body').animate({
        scrollTop: $(el).offset().top
    }, 300);
    console.log(el);
}
// END TO TOP OF ELEMENT
</code>```

I am still confused why the first attempt wouldn't have worked, and why the simple test returned an undefined line?

答:
Your code is a bit complicated for what you want to achieve. You are storing a jQuery element into productListQueryResult but then you are retrieving its id in order to get it again by id.

A simpler solution would be:

```<code>// We already have the element.
var productListQueryResult  = $('#product-list-query-result');

scrollToDiv(productListQueryResult);

// TO TOP OF ELEMENT
function scrollToDiv(el) {
    // We don't need to get the element again, as we already have it.
    $('html, body').animate({
        scrollTop: el.offset().top
    }, 300);
    console.log(el);
}
</code>```

As to why your code did not work, your first try worked for me, as you can see in fiddle.

In your second try you were computing the id incorrectly:

```<code>var el = "'#" + e + "'";
</code>```

In this way, el ended up with value "'#product-list-query-result'" (note the single quotes) and that is not a valid selector for jQuery, hence the unrecognized expression error.

As to why the undefined line in your console.log, it doesn't mean that your HTML element was not present. With:

```<code>var e = jQuery("#product-list-query-result");
console.log(e);
</code>```

You got in console:

```<code>a.fn.init [div#product-list-query-result, context: document, selector: "#product-list-query-result"]
undefined
</code>```

The first line is the result of your console.log(e).

The why of the second line is better explained here. In few words, is the return of console.log command that also gets printed.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to work out why the following is happening.

I am trying to:

Click an element.

On click, pass a DOM element to a function.

Use this DOM element within the function to create a target ID.

Smooth Scroll to this target ID>

Here is my code:

VARIABLE:

var productListQueryResult  = $('#product-list-query-result');

TRIGGER:

scrollToDiv(productListQueryResult);

FUNCTION:

// TO TOP OF ELEMENT
function scrollToDiv(e) {
    var el = e.attr('id');
    $('html, body').animate({
        scrollTop: $("#" + el).offset().top
    }, 300);
    console.log(el);
}
// END TO TOP OF ELEMENT

RESULT:

jquery.js?ver=1.12.4-wp:2 Uncaught Error: Syntax error, unrecognized expression: '#product-list-query-result'

Although this element is in existence. If I run:

var e = jQuery("#product-list-query-result");
console.log(e);

I get two lines returned:

a.fn.init [div#product-list-query-result, context: document, selector: "#product-list-query-result"]
undefined

I'm unsure as to why I get a second line returned too 'undefined', can anyone explain that too?

Hopefully I have provided enough information, if not please feel free to start a discussion.

Edit

I have also tried:

TRIGGER:

scrollToDiv(productListQueryResult.attr('id'));

FUNCTION:

// TO TOP OF ELEMENT
function scrollToDiv(e) {
    var el = "'#" + e + "'";
    $('html, body').animate({
        scrollTop: $(el).offset().top
    }, 300);
    console.log(el);
}
// END TO TOP OF ELEMENT

RESULT:

Uncaught Error: Syntax error, unrecognized expression: '#product-list-query-result'

EDIT (SOLUTION):

If passing a variable into the selector you do not require the ""'s.

FUNCTION:

// TO TOP OF ELEMENT
function scrollToDiv(e) {
    var el = "#" + e;
    $('html, body').animate({
        scrollTop: $(el).offset().top
    }, 300);
    console.log(el);
}
// END TO TOP OF ELEMENT

I am still confused why the first attempt wouldn't have worked, and why the simple test returned an undefined line?

Body:
Your code is a bit complicated for what you want to achieve. You are storing a jQuery element into productListQueryResult but then you are retrieving its id in order to get it again by id.

A simpler solution would be:

// We already have the element.
var productListQueryResult  = $('#product-list-query-result');

scrollToDiv(productListQueryResult);

// TO TOP OF ELEMENT
function scrollToDiv(el) {
    // We don't need to get the element again, as we already have it.
    $('html, body').animate({
        scrollTop: el.offset().top
    }, 300);
    console.log(el);
}

As to why your code did not work, your first try worked for me, as you can see in fiddle.

In your second try you were computing the id incorrectly:

var el = "'#" + e + "'";

In this way, el ended up with value "'#product-list-query-result'" (note the single quotes) and that is not a valid selector for jQuery, hence the unrecognized expression error.

As to why the undefined line in your console.log, it doesn't mean that your HTML element was not present. With:

var e = jQuery("#product-list-query-result");
console.log(e);

You got in console:

a.fn.init [div#product-list-query-result, context: document, selector: "#product-list-query-result"]
undefined

The first line is the result of your console.log(e).

The why of the second line is better explained here. In few words, is the return of console.log command that also gets printed.


问:
How to plot a graph from a dataframe with a condition?
I have some data of some options where I want to plot the data yet with the conditions of either a call or a put. The following data looks like this:

```<code>            underlying_last  exchange  ...   IVBid   IVAsk
underlying                             ...
BP                    39.00         *  ...  0.0000  4.0743
BP                    39.00         *  ...  0.0000  3.0846
BP                    39.00         *  ...  0.0000  3.9024
BP                    39.00         *  ...  0.0000  2.6644
BP                    39.00         *  ...  0.0000  3.3525
</code>```

There is a column 'type' which contains if the option is a call or a put. I want to select only call values and plot the quote date against the price. I have the following code:

```<code>#import modules needed
import numpy as np
import pandas_datareader as web
import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
from matplotlib import style
from matplotlib import rc
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import GPy
from numpy.random import randn

#styel of plot
style.use('default')

df = pd.read_csv('BP_2019.csv',index_col = 'underlying',parse_dates = ['expiration','quotedate'])
c = df['type'] = "call"
x = df[c].index
y = df[c]['bid'].tolist()

fig, ax = plt.subplots()
ax.plot(x,y)
</code>```

I am receiving the following error:

```<code>  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'call'
</code>```

答:
Try following:

Instead of c = df['type'] = "call"

Use c = df[df['type'] == "call"]

Body:
I have some data of some options where I want to plot the data yet with the conditions of either a call or a put. The following data looks like this:

            underlying_last  exchange  ...   IVBid   IVAsk
underlying                             ...
BP                    39.00         *  ...  0.0000  4.0743
BP                    39.00         *  ...  0.0000  3.0846
BP                    39.00         *  ...  0.0000  3.9024
BP                    39.00         *  ...  0.0000  2.6644
BP                    39.00         *  ...  0.0000  3.3525

There is a column 'type' which contains if the option is a call or a put. I want to select only call values and plot the quote date against the price. I have the following code:

#import modules needed
import numpy as np
import pandas_datareader as web
import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
from matplotlib import style
from matplotlib import rc
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import GPy
from numpy.random import randn

#styel of plot
style.use('default')

df = pd.read_csv('BP_2019.csv',index_col = 'underlying',parse_dates = ['expiration','quotedate'])
c = df['type'] = "call"
x = df[c].index
y = df[c]['bid'].tolist()

fig, ax = plt.subplots()
ax.plot(x,y)

I am receiving the following error:

  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'call'


问:
How does .Net runtime "understand" that structure still has a reference
The question is how .Net runtime understands that fields of a structure, that was placed onto memory using Marshal.StructureToPtr, must not be freed by GC.

Below the scenario.

I have the following structure:

```<code>[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    public string s;
    public Stream stream;

    public SomeStruct(string s)
    {
        this.s = s;
        this.stream = new MemoryStream(0x100);
    }
}
</code>```

There is a method that instantiates the structure and drops it to memory:

```<code>static IntPtr GetStructRawData()
{
    IntPtr ptr = Marshal.AllocHGlobal(1024);
    Marshal.StructureToPtr(new SomeStruct("hi"), ptr, false);
    return ptr;
}
</code>```

Then I can make new structure from the raw memory:

```<code>IntPtr ptr = GetStructRawData();

GC.Collect();

SomeStruct struct2 = (SomeStruct)Marshal.PtrToStructure(ptr, typeof(SomeStruct));
</code>```

Aftet that struct2 really contains correct string ("hi"), and correct stream. So it seems that there are references to that string and to that stream of struct1. But what holds the references? How does the runtime understands that the string and the stream must not be collected?

答:
Per Marc's comment I've updated my answer.

I modified your program a bit and looked at it in WinDbg to understand it better. In your example the literal string is rooted by the string interning table, which is a static so it will keep all literal strings alive for the lifetime of the process.

If I change your string to be a dynamically created, it is no longer rooted by this table. Instead, as soon as you leave GetStructRawData the !gcroot command reports that the string is no longer rooted. I.e. from the GC's point of view it is no more,  it has ceased to be, it is bereft of life, it rests in peace, it is an ex-string.

I agree with Marc that the reason your program still works is simply by chance. You are able to restore the reference and the object just happens to be in the same location. Don't count on this.

Body:
The question is how .Net runtime understands that fields of a structure, that was placed onto memory using Marshal.StructureToPtr, must not be freed by GC.

Below the scenario.

I have the following structure:

[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    public string s;
    public Stream stream;

    public SomeStruct(string s)
    {
        this.s = s;
        this.stream = new MemoryStream(0x100);
    }
}

There is a method that instantiates the structure and drops it to memory:

static IntPtr GetStructRawData()
{
    IntPtr ptr = Marshal.AllocHGlobal(1024);
    Marshal.StructureToPtr(new SomeStruct("hi"), ptr, false);
    return ptr;
}

Then I can make new structure from the raw memory:

IntPtr ptr = GetStructRawData();

GC.Collect();

SomeStruct struct2 = (SomeStruct)Marshal.PtrToStructure(ptr, typeof(SomeStruct));

Aftet that struct2 really contains correct string ("hi"), and correct stream. So it seems that there are references to that string and to that stream of struct1. But what holds the references? How does the runtime understands that the string and the stream must not be collected?


问:
C++ usual arithmetic conversions not converting
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

```<code>printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);
</code>```

produces the following output:

```<code>Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999
</code>```

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)

答:
A conversion of a negative signed value to an unsigned leads into the binary complement value which corresponds to it. An addition of this unsigned value will lead into an overflow which then results just exactly in the same value as adding the negative value would do.

By the way: That's the trick how the processor does a subtraction (or am I wrong in these modern times?).

Body:
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);

produces the following output:

Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)


问:
Replace value across multiple lines in bash
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

```<code>    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

```<code>pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt
</code>```

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

```<code>./run.sh r.start 0x284569
</code>```

should be

```<code>    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

Here's my best shot for the second part

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

```<code>var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt
</code>```

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

答:
Here is a perl way:

```<code>#!/usr/bin/perl
use strict;
use warnings;

# retrieve the 2 parameters
my $start = shift @ARGV or die "missing 1rst arg";
my $repl =  shift @ARGV or die "missing 2nd arg";

# input file
open my $fh_in, '<', 'file.txt' or die "$!";
# output file
open my $fh_out, '>', 'output' or die "$!";

# loop through input file
while(<$fh_in>) {
    # if we are between /start {1srt parameter} and /end
    if (/^ {4}\/start\h+$start/ ... /^ {4}\/end\h*$/) {
        # substitute 0x.... by {2nd parameter}
        s/^(?: {6}GAIN | {8}CODE "$start" )\K0x\w+/$repl/;
    }
    print $fh_out $_;
}
</code>```

In action:

```<code>cat file.txt
    /start other.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

./test.pl r.start 0x123456

cat output
    /start other.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
    /start r.start ""
      GAIN 0x123456 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x123456 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
</code>```

Body:
I'm struggling even with all the examples available on stackoverflow and google.

Basically i have the following text

    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

and i need to read through this file searching for a name e.g. r.start which is passed as $1 and substitute e.g. 0x256 with a value that i pass as $2.
There a two instance to substitute, line 2 and line 7.

Things i know:

/start is preceded by 4 spaces

GAIN is preceded by 6 spaces

\r\n or \n might be present

CODE is preceded by 8 spaces

Till now i've reached this point

pattern="N;s\s\/start r.start \"\"\n      GAIN 0x\(.*\)"
replacement"\/start r.start \"\"\n      GAIN 0x82"
sed -e "$pattern/$replacement/p" test.txt

but i get nothing.
I was also able to substitute the first line but for whatever reason it pasted me the first two lines twice on top of each other

the expected value assuming the following call

./run.sh r.start 0x284569

should be

    /start r.start ""
      GAIN 0x284569 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x284569 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

Here's my best shot for the second part

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

The problem is that it is deleting everything after the value substitution. I can't put in \2 the following chars

EDIT:

By doing the following

var="r.start"
val="0x48209F82"

pattern="\(CODE \"$var\" \).*\(\s.*\s.*\s.*\)"
replacement="\1$val\2"
sed "s/$pattern/$replacement/g" test.txt

I get what i want but it feels a little bit dirty, how do i reduce the last part in case of a variable number of char? Can i just somehow match everything till end of line?

Body:
Here is a perl way:

#!/usr/bin/perl
use strict;
use warnings;

# retrieve the 2 parameters
my $start = shift @ARGV or die "missing 1rst arg";
my $repl =  shift @ARGV or die "missing 2nd arg";

# input file
open my $fh_in, '<', 'file.txt' or die "$!";
# output file
open my $fh_out, '>', 'output' or die "$!";

# loop through input file
while(<$fh_in>) {
    # if we are between /start {1srt parameter} and /end
    if (/^ {4}\/start\h+$start/ ... /^ {4}\/end\h*$/) {
        # substitute 0x.... by {2nd parameter}
        s/^(?: {6}GAIN | {8}CODE "$start" )\K0x\w+/$repl/;
    }
    print $fh_out $_;
}

In action:

cat file.txt
    /start other.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
    /start r.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end

./test.pl r.start 0x123456

cat output
    /start other.start ""
      GAIN 0x256 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x256 0x2 10 0xA3
      /end MACRO
      OTHER
    /end
    /start r.start ""
      GAIN 0x123456 __POSITIVE 1 FOO
      OTHER
      OTHER
      /start MACRO
        200
        CODE "r.start" 0x123456 0x2 10 0xA3
      /end MACRO
      OTHER
    /end


问:
How to deploy google function from google SDK from local system runtime python
I am trying to deploy Google Cloud Function from local system using the gcloud command-line tool.

My files are compressed in a .zip file. As described in the attached screenshot the zip file contains main.py and requirement.txt

main.py  (took from web for testing)

```<code>from wand.image import Image
from google.cloud import storage
client = storage.Client.from_service_account_json(
         'C:\\Users\\an20086686\\AppData\\Local\\Google\\Cloud SDK\\deploy\\****-*****-poc-e4b410a65986.JSON')
THUMBNAIL_BUCKET = 'a_demo_storage_trigger1'
def make_thumbnail(data, context):

    bucket = client.get_bucket(data['****_my-awesome-bucket'])
    blob = bucket.get_blob(data['name'])
    imagedata = blob.download_as_string()

    newimage = Image(blob=imagedata)
    newimage.sample(200,200)

    bucket = client.get_bucket(THUMBNAIL_BUCKET)
    newblob = bucket.blob('thumbnail-' + data['name'])
    newblob.upload_from_string(newimage.make_blob())
</code>```

requirements.txt

```<code>google-cloud-storage
Wand
</code>```

Using the command below to deploy this function:

```<code>gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize
</code>```

Error 1 : (gcloud.beta.functions.deploy) unrecognized arguments:
  google.storage.object.finalize

When I use:

```<code>gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize
</code>```

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3,message=Function failed on loading user code.

Error message: File main.py that is expected to define function doesn't exist

Log of the encountered error:

Screenshot

答:
As @YaguraStation mentioned the issue is because of the ZIP file. Let me give a bit more of an explanation though.

If you are following this documentation,Deploying from Your Local Machine, in order to deploy your function with the gcloud command your files should not be compressed in a ZIP file.

Your command somehow should look like this:

```<code>gcloud functions deploy make_thumbnail --runtime python37 \
--trigger-resource ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize
</code>```

Note: RUNTIME and TRIGGER are two different values.

If you want to deploy a function and your files to be compressed into a ZIP file then add the --source flag:

```<code>gcloud functions deploy make_thumbnail --runtime python37 \
--trigger-resource ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize \
--source gs://path/to_file/file.zip
</code>```

I tested both of the commands above and they are working for me as intended.

Body:
I am trying to deploy Google Cloud Function from local system using the gcloud command-line tool.

My files are compressed in a .zip file. As described in the attached screenshot the zip file contains main.py and requirement.txt

main.py  (took from web for testing)

from wand.image import Image
from google.cloud import storage
client = storage.Client.from_service_account_json(
         'C:\\Users\\an20086686\\AppData\\Local\\Google\\Cloud SDK\\deploy\\****-*****-poc-e4b410a65986.JSON')
THUMBNAIL_BUCKET = 'a_demo_storage_trigger1'
def make_thumbnail(data, context):

    bucket = client.get_bucket(data['****_my-awesome-bucket'])
    blob = bucket.get_blob(data['name'])
    imagedata = blob.download_as_string()

    newimage = Image(blob=imagedata)
    newimage.sample(200,200)

    bucket = client.get_bucket(THUMBNAIL_BUCKET)
    newblob = bucket.blob('thumbnail-' + data['name'])
    newblob.upload_from_string(newimage.make_blob())

requirements.txt

google-cloud-storage
Wand

Using the command below to deploy this function:

gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize

Error 1 : (gcloud.beta.functions.deploy) unrecognized arguments:
  google.storage.object.finalize

When I use:

gcloud beta functions deploy make_thumbnail --runtime python37 \
--trigger-bucket ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3,message=Function failed on loading user code.

Error message: File main.py that is expected to define function doesn't exist

Log of the encountered error:

Screenshot

Body:
As @YaguraStation mentioned the issue is because of the ZIP file. Let me give a bit more of an explanation though.

If you are following this documentation,Deploying from Your Local Machine, in order to deploy your function with the gcloud command your files should not be compressed in a ZIP file.

Your command somehow should look like this:

gcloud functions deploy make_thumbnail --runtime python37 \
--trigger-resource ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize

Note: RUNTIME and TRIGGER are two different values.

If you want to deploy a function and your files to be compressed into a ZIP file then add the --source flag:

gcloud functions deploy make_thumbnail --runtime python37 \
--trigger-resource ****_my-awesome-bucket \
--trigger-event google.storage.object.finalize \
--source gs://path/to_file/file.zip

I tested both of the commands above and they are working for me as intended.


问:
Is there a Swift bridge for Python?
I developed a script to set attributes for my iTunes music library on my Mac using an Apple Script bridge called AppScript. AppScript Allowed me to write my code in native Python without having to learn Apple Script. AppSript would translate my native Python to Apple Script. Since Apple Script has been replaced with Swift I am wondering if there is a similar bridge for Swift. I have done my research, but no luck. Additionally if there is, can you provide an example of how to control iTunes(now Music) with said library? Thanks in advance

答:
Swift is designed to use MacOS's programming APIs: AppKit, Quartz, CoreFoundation, NSObject, etc, rather than the higher level OSAX event-driven elements (open, print, close, document, window, etc) used in AppleScript.

The system-bundled python (2.7) comes with pyObjC, which allows python to use the same programming APIs that Swift does, e.g. "writing apps". PyObjC also contains a Scripting Bridge to the AppleScript events and objects. The canonical example code does use iTunes:

```<code>from Foundation import *
from ScriptingBridge import *
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
print iTunes.currentTrack().name()
</code>```

(Obvs, this is python2 and you need to put brackets round the print command. Also, personally, I wouldn't import * everything, as it's very slow.)

Here are some other methods/attributes based on the Script Dictionary:

```<code>iTunes.nextTrack()
iTunes.previousTrack()
iTunes.playpause()
iTunes.fastForward()
iTunes.setShuffleEnabled_(False)
iTunes.currentPlaylist().playOnce_(False)
</code>```

The system-bundled version of pyObjC is very old, but the library itself is still being developed. If you're using python3, then you should install the latest version of pyObjC.

FWIW, you can actually run uncompiled Swift as a 'script' in the shell.

Title: Is there a Swift bridge for Python?

Body:
Swift is designed to use MacOS's programming APIs: AppKit, Quartz, CoreFoundation, NSObject, etc, rather than the higher level OSAX event-driven elements (open, print, close, document, window, etc) used in AppleScript.

The system-bundled python (2.7) comes with pyObjC, which allows python to use the same programming APIs that Swift does, e.g. "writing apps". PyObjC also contains a Scripting Bridge to the AppleScript events and objects. The canonical example code does use iTunes:

from Foundation import *
from ScriptingBridge import *
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
print iTunes.currentTrack().name()

(Obvs, this is python2 and you need to put brackets round the print command. Also, personally, I wouldn't import * everything, as it's very slow.)

Here are some other methods/attributes based on the Script Dictionary:

iTunes.nextTrack()
iTunes.previousTrack()
iTunes.playpause()
iTunes.fastForward()
iTunes.setShuffleEnabled_(False)
iTunes.currentPlaylist().playOnce_(False)

The system-bundled version of pyObjC is very old, but the library itself is still being developed. If you're using python3, then you should install the latest version of pyObjC.

FWIW, you can actually run uncompiled Swift as a 'script' in the shell.


问:
Print fixed header and footer on all pages
How to print header and footer on all pages?

Here is a simple example about what I mean:

let table = document.getElementById('table');
for (let i = 1; i <= 100; i++) {
  table.insertAdjacentHTML('beforeend', `<tr><td>${i}</td><td>title ${i}</td><td>${i*3}$</td></tr>`);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media print {
  .invoice-footer {
    height: 2rem;
    position: fixed;
    bottom: 0;
  }
  .no-print {
    display: none
  }
}

table {
  margin-bottom: 2rem;
}</code>```

<button onclick="window.print()" class="no-print">Print</button>

        #
        Title
        Price

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

```

答:
I solved it :) here is a live example:

table {
  width: 100%;
}

table.print-content {
  font-size: 12px;
  border: 1px solid #dee2e6;
  border-collapse: collapse !important;
}

table.print-content th,
table.print-content td {
  padding: .2rem .4rem;
  text-align: left;
  vertical-align: top;
  border-top: 1px solid #dee2e6;
}

@media print {
  .print-footer {
    position: fixed;
    bottom: 0;
    left: 0;
  }
  .no-print {
    display: none
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="window.print()" class="no-print">Print</button>

<table>
  <!-- Start Header -->
  <thead>
    <tr>
      <td>
        <img src="https://logoipsum.com/logo/logo-4.svg" width="300">
      </td>
    </tr>
  </thead>
  <!-- End Header -->
  <tr>
    <td>
      <h1>Some text on the first page only</h1>
      <!-- Start Print Content -->
      <table class="print-content">
        <thead>
          <tr>
            <th>#</th>
            <th>Position</th>
            <th>Dollar</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>Title1</td>
            <td>1$</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Title2</td>
            <td>2$</td>
          </tr>
          <tr>
            <td>3</td>
            <td>Title3</td>
            <td>3$</td>
          </tr>
          <tr>
            <td>4</td>
            <td>Title4</td>
            <td>4$</td>
          </tr>
          <tr>
            <td>5</td>
            <td>Title5</td>
            <td>5$</td>
          </tr>
          <tr>
            <td>6</td>
            <td>Title6</td>
            <td>6$</td>
          </tr>
          <tr>
            <td>7</td>
            <td>Title7</td>
            <td>7$</td>
          </tr>
          <tr>
            <td>8</td>
            <td>Title8</td>
            <td>8$</td>
          </tr>
          <tr>
            <td>9</td>
            <td>Title9</td>
            <td>9$</td>
          </tr>
          <tr>
            <td>10</td>
            <td>Title10</td>
            <td>10$</td>
          </tr>
          <tr>
            <td>11</td>
            <td>Title11</td>
            <td>11$</td>
          </tr>
          <tr>
            <td>12</td>
            <td>Title12</td>
            <td>12$</td>
          </tr>
          <tr>
            <td>13</td>
            <td>Title13</td>
            <td>13$</td>
          </tr>
          <tr>
            <td>14</td>
            <td>Title14</td>
            <td>14$</td>
          </tr>
          <tr>
            <td>15</td>
            <td>Title15</td>
            <td>15$</td>
          </tr>
          <tr>
            <td>16</td>
            <td>Title16</td>
            <td>16$</td>
          </tr>
          <tr>
            <td>17</td>
            <td>Title17</td>
            <td>17$</td>
          </tr>
          <tr>
            <td>18</td>
            <td>Title18</td>
            <td>18$</td>
          </tr>
          <tr>
            <td>19</td>
            <td>Title19</td>
            <td>19$</td>
          </tr>
          <tr>
            <td>20</td>
            <td>Title20</td>
            <td>20$</td>
          </tr>
          <tr>
            <td>21</td>
            <td>Title21</td>
            <td>21$</td>
          </tr>
          <tr>
            <td>22</td>
            <td>Title22</td>
            <td>22$</td>
          </tr>
          <tr>
            <td>23</td>
            <td>Title23</td>
            <td>23$</td>
          </tr>
          <tr>
            <td>24</td>
            <td>Title24</td>
            <td>24$</td>
          </tr>
          <tr>
            <td>25</td>
            <td>Title25</td>
            <td>25$</td>
          </tr>
          <tr>
            <td>26</td>
            <td>Title26</td>
            <td>26$</td>
          </tr>
          <tr>
            <td>27</td>
            <td>Title27</td>
            <td>27$</td>
          </tr>
          <tr>
            <td>28</td>
            <td>Title28</td>
            <td>28$</td>
          </tr>
          <tr>
            <td>29</td>
            <td>Title29</td>
            <td>29$</td>
          </tr>
          <tr>
            <td>30</td>
            <td>Title30</td>
            <td>30$</td>
          </tr>
          <tr>
            <td>31</td>
            <td>Title31</td>
            <td>31$</td>
          </tr>
          <tr>
            <td>32</td>
            <td>Title32</td>
            <td>32$</td>
          </tr>
          <tr>
            <td>33</td>
            <td>Title33</td>
            <td>33$</td>
          </tr>
          <tr>
            <td>34</td>
            <td>Title34</td>
            <td>34$</td>
          </tr>
          <tr>
            <td>35</td>
            <td>Title35</td>
            <td>35$</td>
          </tr>
          <tr>
            <td>36</td>
            <td>Title36</td>
            <td>36$</td>
          </tr>
          <tr>
            <td>37</td>
            <td>Title37</td>
            <td>37$</td>
          </tr>
          <tr>
            <td>38</td>
            <td>Title38</td>
            <td>38$</td>
          </tr>
          <tr>
            <td>39</td>
            <td>Title39</td>
            <td>39$</td>
          </tr>
          <tr>
            <td>40</td>
            <td>Title40</td>
            <td>40$</td>
          </tr>
          <tr>
            <td>41</td>
            <td>Title41</td>
            <td>41$</td>
          </tr>
          <tr>
            <td>42</td>
            <td>Title42</td>
            <td>42$</td>
          </tr>
          <tr>
            <td>43</td>
            <td>Title43</td>
            <td>43$</td>
          </tr>
          <tr>
            <td>44</td>
            <td>Title44</td>
            <td>44$</td>
          </tr>
          <tr>
            <td>45</td>
            <td>Title45</td>
            <td>45$</td>
          </tr>
          <tr>
            <td>46</td>
            <td>Title46</td>
            <td>46$</td>
          </tr>
          <tr>
            <td>47</td>
            <td>Title47</td>
            <td>47$</td>
          </tr>
          <tr>
            <td>48</td>
            <td>Title48</td>
            <td>48$</td>
          </tr>
          <tr>
            <td>49</td>
            <td>Title49</td>
            <td>49$</td>
          </tr>
          <tr>
            <td>50</td>
            <td>Title50</td>
            <td>50$</td>
          </tr>
          <tr>
            <td>51</td>
            <td>Title51</td>
            <td>51$</td>
          </tr>
          <tr>
            <td>52</td>
            <td>Title52</td>
            <td>52$</td>
          </tr>
          <tr>
            <td>53</td>
            <td>Title53</td>
            <td>53$</td>
          </tr>
          <tr>
            <td>54</td>
            <td>Title54</td>
            <td>54$</td>
          </tr>
          <tr>
            <td>55</td>
            <td>Title55</td>
            <td>55$</td>
          </tr>
          <tr>
            <td>56</td>
            <td>Title56</td>
            <td>56$</td>
          </tr>
          <tr>
            <td>57</td>
            <td>Title57</td>
            <td>57$</td>
          </tr>
          <tr>
            <td>58</td>
            <td>Title58</td>
            <td>58$</td>
          </tr>
          <tr>
            <td>59</td>
            <td>Title59</td>
            <td>59$</td>
          </tr>
          <tr>
            <td>60</td>
            <td>Title60</td>
            <td>60$</td>
          </tr>
          <tr>
            <td>61</td>
            <td>Title61</td>
            <td>61$</td>
          </tr>
          <tr>
            <td>62</td>
            <td>Title62</td>
            <td>62$</td>
          </tr>
          <tr>
            <td>63</td>
            <td>Title63</td>
            <td>63$</td>
          </tr>
          <tr>
            <td>64</td>
            <td>Title64</td>
            <td>64$</td>
          </tr>
          <tr>
            <td>65</td>
            <td>Title65</td>
            <td>65$</td>
          </tr>
          <tr>
            <td>66</td>
            <td>Title66</td>
            <td>66$</td>
          </tr>
          <tr>
            <td>67</td>
            <td>Title67</td>
            <td>67$</td>
          </tr>
          <tr>
            <td>68</td>
            <td>Title68</td>
            <td>68$</td>
          </tr>
          <tr>
            <td>69</td>
            <td>Title69</td>
            <td>69$</td>
          </tr>
          <tr>
            <td>70</td>
            <td>Title70</td>
            <td>70$</td>
          </tr>
          <tr>
            <td>71</td>
            <td>Title71</td>
            <td>71$</td>
          </tr>
          <tr>
            <td>72</td>
            <td>Title72</td>
            <td>72$</td>
          </tr>
          <tr>
            <td>73</td>
            <td>Title73</td>
            <td>73$</td>
          </tr>
          <tr>
            <td>74</td>
            <td>Title74</td>
            <td>74$</td>
          </tr>
          <tr>
            <td>75</td>
            <td>Title75</td>
            <td>75$</td>
          </tr>
          <tr>
            <td>76</td>
            <td>Title76</td>
            <td>76$</td>
          </tr>
          <tr>
            <td>77</td>
            <td>Title77</td>
            <td>77$</td>
          </tr>
          <tr>
            <td>78</td>
            <td>Title78</td>
            <td>78$</td>
          </tr>
          <tr>
            <td>79</td>
            <td>Title79</td>
            <td>79$</td>
          </tr>
          <tr>
            <td>80</td>
            <td>Title80</td>
            <td>80$</td>
          </tr>
          <tr>
            <td>81</td>
            <td>Title81</td>
            <td>81$</td>
          </tr>
          <tr>
            <td>82</td>
            <td>Title82</td>
            <td>82$</td>
          </tr>
          <tr>
            <td>83</td>
            <td>Title83</td>
            <td>83$</td>
          </tr>
          <tr>
            <td>84</td>
            <td>Title84</td>
            <td>84$</td>
          </tr>
          <tr>
            <td>85</td>
            <td>Title85</td>
            <td>85$</td>
          </tr>
          <tr>
            <td>86</td>
            <td>Title86</td>
            <td>86$</td>
          </tr>
          <tr>
            <td>87</td>
            <td>Title87</td>
            <td>87$</td>
          </tr>
          <tr>
            <td>88</td>
            <td>Title88</td>
            <td>88$</td>
          </tr>
          <tr>
            <td>89</td>
            <td>Title89</td>
            <td>89$</td>
          </tr>
          <tr>
            <td>90</td>
            <td>Title90</td>
            <td>90$</td>
          </tr>
          <tr>
            <td>91</td>
            <td>Title91</td>
            <td>91$</td>
          </tr>
          <tr>
            <td>92</td>
            <td>Title92</td>
            <td>92$</td>
          </tr>
          <tr>
            <td>93</td>
            <td>Title93</td>
            <td>93$</td>
          </tr>
          <tr>
            <td>94</td>
            <td>Title94</td>
            <td>94$</td>
          </tr>
          <tr>
            <td>95</td>
            <td>Title95</td>
            <td>95$</td>
          </tr>
          <tr>
            <td>96</td>
            <td>Title96</td>
            <td>96$</td>
          </tr>
          <tr>
            <td>97</td>
            <td>Title97</td>
            <td>97$</td>
          </tr>
          <tr>
            <td>98</td>
            <td>Title98</td>
            <td>98$</td>
          </tr>
          <tr>
            <td>99</td>
            <td>Title99</td>
            <td>99$</td>
          </tr>
          <tr>
            <th colspan="2">Sum</th>
            <th>10$</th>
          </tr>
        </tbody>
      </table>
      <!-- End Print Content -->
    </td>
  </tr>
  <tr>
    <td>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
    </td>
  </tr>
  <!-- Start Space For Footer -->
  <tfoot>
    <tr>
      <td style="height: 3cm">
        <!-- Leave this empty and don't remove it. This space is where footer placed on print -->
      </td>
    </tr>
  </tfoot>
  <!-- End Space For Footer -->
</table>

<!-- Start Footer -->
<div class="print-footer">
  <h2>Here is the fixed Footer</h2>
</div>
<!-- End Footer --></code>```

Body:
How to print header and footer on all pages?

Here is a simple example about what I mean:

let table = document.getElementById('table');
for (let i = 1; i <= 100; i++) {
  table.insertAdjacentHTML('beforeend', `<tr><td>${i}</td><td>title ${i}</td><td>${i*3}$</td></tr>`);
}

@media print {
  .invoice-footer {
    height: 2rem;
    position: fixed;
    bottom: 0;
  }
  .no-print {
    display: none
  }
}

table {
  margin-bottom: 2rem;
}

<button onclick="window.print()" class="no-print">Print</button>

        #
        Title
        Price

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Body:
I solved it :) here is a live example:

table {
  width: 100%;
}

table.print-content {
  font-size: 12px;
  border: 1px solid #dee2e6;
  border-collapse: collapse !important;
}

table.print-content th,
table.print-content td {
  padding: .2rem .4rem;
  text-align: left;
  vertical-align: top;
  border-top: 1px solid #dee2e6;
}

@media print {
  .print-footer {
    position: fixed;
    bottom: 0;
    left: 0;
  }
  .no-print {
    display: none
  }
}

<button onclick="window.print()" class="no-print">Print</button>

<table>
  <!-- Start Header -->
  <thead>
    <tr>
      <td>
        <img src="https://logoipsum.com/logo/logo-4.svg" width="300">
      </td>
    </tr>
  </thead>
  <!-- End Header -->
  <tr>
    <td>
      <h1>Some text on the first page only</h1>
      <!-- Start Print Content -->
      <table class="print-content">
        <thead>
          <tr>
            <th>#</th>
            <th>Position</th>
            <th>Dollar</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>Title1</td>
            <td>1$</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Title2</td>
            <td>2$</td>
          </tr>
          <tr>
            <td>3</td>
            <td>Title3</td>
            <td>3$</td>
          </tr>
          <tr>
            <td>4</td>
            <td>Title4</td>
            <td>4$</td>
          </tr>
          <tr>
            <td>5</td>
            <td>Title5</td>
            <td>5$</td>
          </tr>
          <tr>
            <td>6</td>
            <td>Title6</td>
            <td>6$</td>
          </tr>
          <tr>
            <td>7</td>
            <td>Title7</td>
            <td>7$</td>
          </tr>
          <tr>
            <td>8</td>
            <td>Title8</td>
            <td>8$</td>
          </tr>
          <tr>
            <td>9</td>
            <td>Title9</td>
            <td>9$</td>
          </tr>
          <tr>
            <td>10</td>
            <td>Title10</td>
            <td>10$</td>
          </tr>
          <tr>
            <td>11</td>
            <td>Title11</td>
            <td>11$</td>
          </tr>
          <tr>
            <td>12</td>
            <td>Title12</td>
            <td>12$</td>
          </tr>
          <tr>
            <td>13</td>
            <td>Title13</td>
            <td>13$</td>
          </tr>
          <tr>
            <td>14</td>
            <td>Title14</td>
            <td>14$</td>
          </tr>
          <tr>
            <td>15</td>
            <td>Title15</td>
            <td>15$</td>
          </tr>
          <tr>
            <td>16</td>
            <td>Title16</td>
            <td>16$</td>
          </tr>
          <tr>
            <td>17</td>
            <td>Title17</td>
            <td>17$</td>
          </tr>
          <tr>
            <td>18</td>
            <td>Title18</td>
            <td>18$</td>
          </tr>
          <tr>
            <td>19</td>
            <td>Title19</td>
            <td>19$</td>
          </tr>
          <tr>
            <td>20</td>
            <td>Title20</td>
            <td>20$</td>
          </tr>
          <tr>
            <td>21</td>
            <td>Title21</td>
            <td>21$</td>
          </tr>
          <tr>
            <td>22</td>
            <td>Title22</td>
            <td>22$</td>
          </tr>
          <tr>
            <td>23</td>
            <td>Title23</td>
            <td>23$</td>
          </tr>
          <tr>
            <td>24</td>
            <td>Title24</td>
            <td>24$</td>
          </tr>
          <tr>
            <td>25</td>
            <td>Title25</td>
            <td>25$</td>
          </tr>
          <tr>
            <td>26</td>
            <td>Title26</td>
            <td>26$</td>
          </tr>
          <tr>
            <td>27</td>
            <td>Title27</td>
            <td>27$</td>
          </tr>
          <tr>
            <td>28</td>
            <td>Title28</td>
            <td>28$</td>
          </tr>
          <tr>
            <td>29</td>
            <td>Title29</td>
            <td>29$</td>
          </tr>
          <tr>
            <td>30</td>
            <td>Title30</td>
            <td>30$</td>
          </tr>
          <tr>
            <td>31</td>
            <td>Title31</td>
            <td>31$</td>
          </tr>
          <tr>
            <td>32</td>
            <td>Title32</td>
            <td>32$</td>
          </tr>
          <tr>
            <td>33</td>
            <td>Title33</td>
            <td>33$</td>
          </tr>
          <tr>
            <td>34</td>
            <td>Title34</td>
            <td>34$</td>
          </tr>
          <tr>
            <td>35</td>
            <td>Title35</td>
            <td>35$</td>
          </tr>
          <tr>
            <td>36</td>
            <td>Title36</td>
            <td>36$</td>
          </tr>
          <tr>
            <td>37</td>
            <td>Title37</td>
            <td>37$</td>
          </tr>
          <tr>
            <td>38</td>
            <td>Title38</td>
            <td>38$</td>
          </tr>
          <tr>
            <td>39</td>
            <td>Title39</td>
            <td>39$</td>
          </tr>
          <tr>
            <td>40</td>
            <td>Title40</td>
            <td>40$</td>
          </tr>
          <tr>
            <td>41</td>
            <td>Title41</td>
            <td>41$</td>
          </tr>
          <tr>
            <td>42</td>
            <td>Title42</td>
            <td>42$</td>
          </tr>
          <tr>
            <td>43</td>
            <td>Title43</td>
            <td>43$</td>
          </tr>
          <tr>
            <td>44</td>
            <td>Title44</td>
            <td>44$</td>
          </tr>
          <tr>
            <td>45</td>
            <td>Title45</td>
            <td>45$</td>
          </tr>
          <tr>
            <td>46</td>
            <td>Title46</td>
            <td>46$</td>
          </tr>
          <tr>
            <td>47</td>
            <td>Title47</td>
            <td>47$</td>
          </tr>
          <tr>
            <td>48</td>
            <td>Title48</td>
            <td>48$</td>
          </tr>
          <tr>
            <td>49</td>
            <td>Title49</td>
            <td>49$</td>
          </tr>
          <tr>
            <td>50</td>
            <td>Title50</td>
            <td>50$</td>
          </tr>
          <tr>
            <td>51</td>
            <td>Title51</td>
            <td>51$</td>
          </tr>
          <tr>
            <td>52</td>
            <td>Title52</td>
            <td>52$</td>
          </tr>
          <tr>
            <td>53</td>
            <td>Title53</td>
            <td>53$</td>
          </tr>
          <tr>
            <td>54</td>
            <td>Title54</td>
            <td>54$</td>
          </tr>
          <tr>
            <td>55</td>
            <td>Title55</td>
            <td>55$</td>
          </tr>
          <tr>
            <td>56</td>
            <td>Title56</td>
            <td>56$</td>
          </tr>
          <tr>
            <td>57</td>
            <td>Title57</td>
            <td>57$</td>
          </tr>
          <tr>
            <td>58</td>
            <td>Title58</td>
            <td>58$</td>
          </tr>
          <tr>
            <td>59</td>
            <td>Title59</td>
            <td>59$</td>
          </tr>
          <tr>
            <td>60</td>
            <td>Title60</td>
            <td>60$</td>
          </tr>
          <tr>
            <td>61</td>
            <td>Title61</td>
            <td>61$</td>
          </tr>
          <tr>
            <td>62</td>
            <td>Title62</td>
            <td>62$</td>
          </tr>
          <tr>
            <td>63</td>
            <td>Title63</td>
            <td>63$</td>
          </tr>
          <tr>
            <td>64</td>
            <td>Title64</td>
            <td>64$</td>
          </tr>
          <tr>
            <td>65</td>
            <td>Title65</td>
            <td>65$</td>
          </tr>
          <tr>
            <td>66</td>
            <td>Title66</td>
            <td>66$</td>
          </tr>
          <tr>
            <td>67</td>
            <td>Title67</td>
            <td>67$</td>
          </tr>
          <tr>
            <td>68</td>
            <td>Title68</td>
            <td>68$</td>
          </tr>
          <tr>
            <td>69</td>
            <td>Title69</td>
            <td>69$</td>
          </tr>
          <tr>
            <td>70</td>
            <td>Title70</td>
            <td>70$</td>
          </tr>
          <tr>
            <td>71</td>
            <td>Title71</td>
            <td>71$</td>
          </tr>
          <tr>
            <td>72</td>
            <td>Title72</td>
            <td>72$</td>
          </tr>
          <tr>
            <td>73</td>
            <td>Title73</td>
            <td>73$</td>
          </tr>
          <tr>
            <td>74</td>
            <td>Title74</td>
            <td>74$</td>
          </tr>
          <tr>
            <td>75</td>
            <td>Title75</td>
            <td>75$</td>
          </tr>
          <tr>
            <td>76</td>
            <td>Title76</td>
            <td>76$</td>
          </tr>
          <tr>
            <td>77</td>
            <td>Title77</td>
            <td>77$</td>
          </tr>
          <tr>
            <td>78</td>
            <td>Title78</td>
            <td>78$</td>
          </tr>
          <tr>
            <td>79</td>
            <td>Title79</td>
            <td>79$</td>
          </tr>
          <tr>
            <td>80</td>
            <td>Title80</td>
            <td>80$</td>
          </tr>
          <tr>
            <td>81</td>
            <td>Title81</td>
            <td>81$</td>
          </tr>
          <tr>
            <td>82</td>
            <td>Title82</td>
            <td>82$</td>
          </tr>
          <tr>
            <td>83</td>
            <td>Title83</td>
            <td>83$</td>
          </tr>
          <tr>
            <td>84</td>
            <td>Title84</td>
            <td>84$</td>
          </tr>
          <tr>
            <td>85</td>
            <td>Title85</td>
            <td>85$</td>
          </tr>
          <tr>
            <td>86</td>
            <td>Title86</td>
            <td>86$</td>
          </tr>
          <tr>
            <td>87</td>
            <td>Title87</td>
            <td>87$</td>
          </tr>
          <tr>
            <td>88</td>
            <td>Title88</td>
            <td>88$</td>
          </tr>
          <tr>
            <td>89</td>
            <td>Title89</td>
            <td>89$</td>
          </tr>
          <tr>
            <td>90</td>
            <td>Title90</td>
            <td>90$</td>
          </tr>
          <tr>
            <td>91</td>
            <td>Title91</td>
            <td>91$</td>
          </tr>
          <tr>
            <td>92</td>
            <td>Title92</td>
            <td>92$</td>
          </tr>
          <tr>
            <td>93</td>
            <td>Title93</td>
            <td>93$</td>
          </tr>
          <tr>
            <td>94</td>
            <td>Title94</td>
            <td>94$</td>
          </tr>
          <tr>
            <td>95</td>
            <td>Title95</td>
            <td>95$</td>
          </tr>
          <tr>
            <td>96</td>
            <td>Title96</td>
            <td>96$</td>
          </tr>
          <tr>
            <td>97</td>
            <td>Title97</td>
            <td>97$</td>
          </tr>
          <tr>
            <td>98</td>
            <td>Title98</td>
            <td>98$</td>
          </tr>
          <tr>
            <td>99</td>
            <td>Title99</td>
            <td>99$</td>
          </tr>
          <tr>
            <th colspan="2">Sum</th>
            <th>10$</th>
          </tr>
        </tbody>
      </table>
      <!-- End Print Content -->
    </td>
  </tr>
  <tr>
    <td>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
    </td>
  </tr>
  <!-- Start Space For Footer -->
  <tfoot>
    <tr>
      <td style="height: 3cm">
        <!-- Leave this empty and don't remove it. This space is where footer placed on print -->
      </td>
    </tr>
  </tfoot>
  <!-- End Space For Footer -->
</table>

<!-- Start Footer -->
<div class="print-footer">
  <h2>Here is the fixed Footer</h2>
</div>
<!-- End Footer -->


Title: R: How to create a Date object using intervals?

Body:
I am trying to create a Date object with specific features. My original Data set the following:

Year Month Day FivMin   A   B   C   D
2000   1    1    1      1   2   3   4
2000   1    1    2      2   3   0   1
2000   1    1    3      3   4   1   2
2000   1    1    4      0   1   2   3
2000   1    2    1      1   2   3   4
2000   1    2    2      5   3   4   1
2000   1    2    3      3   0   1   2
2000   1    2    4      4   1   9   3
2000   1    3    1      1   2   3   4
2000   1    3    2      0   1   7   1
2000   1    3    3      3   4   1   2
2000   1    3    4      1   -2   2   3
2000   1    4    1      0   2   3   4
2000   1    4    2      2   1   4   1
2000   1    4    3      3   0   1   2
2000   1    4    4      0   2   2   3
2000   1    5    1      1   2   3   4
2000   1    5    2      2   3   4   1
2000   1    5    3      0   -1   1   2
2000   1    5    4      9   1   2   3

The variable FiveMin represents a time interval, it means that 1 is equal to 00:05, 2 is equal to 00:10, and so on. My first idea was to use

Date <- df%>%mutate(date = str_c(year,"/",month,"/",day,"/",fivemin),
         date = ymd_hm(date)%>%
         select(-c(1:8)))

But the result is the following

2020-09-07 01:01:00
2020-09-07 01:02:00
2020-09-07 01:02:00
2020-09-07 01:02:00
NA
NA
NA
NA
2020-09-07 04:01:00
2020-09-07 04:02:00
2020-09-07 04:02:00
2020-09-07 04:02:00
NA
NA
NA
NA

Is there a possibility to use a start for setting the initial hour and the time interval.

Thanks for your help.

Body:
library(dplyr)
library(lubridate)

df %>%
    mutate(Hour = FivMin * 5 %/% 60
       , Minute = FivMin * 5 %% 60) %>%
    mutate(datetime = paste0(Year, "/", Month, "/", Day, "/", Hour, "/", Minute)) %>%
    mutate(datetime = ymd_hm(datetime))

Output:

   Year Month Day   FivMin     A     B     C     D Hour  Minute datetime
  <dbl> <chr> <chr>  <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr>  <dttm>
1  2000 01    01         1     1     2     3     4 00    05     2000-01-01 00:05:00
2  2000 01    01         2     2     3     0     1 00    10     2000-01-01 00:10:00
3  2000 01    01         3     3     4     1     2 00    15     2000-01-01 00:15:00
4  2000 01    01         4     0     1     2     3 00    20     2000-01-01 00:20:00
5  2000 01    02         1     1     2     3     4 00    05     2000-01-02 00:05:00
6  2000 01    02         2     5     3     4     1 00    10     2000-01-02 00:10:00


问:
EclipseRCP get pluginId in which a class is located
I have an objects of class T that belongs to plugin P.
It is possible to retrieve the Plugin ID, trough class T?

I don't have access to plugin object but I have access to a objects that is an inner class of plugin P, I have access to PluginClassDescriptor. I have access to:

```<code>P.T object; // I need P.pluginID
</code>```

Thanks

答:
You can get the Bundle for any plug-in class using:

```<code>Bundle bundle = FrameworkUtil.getBundle(anyobject.getClass());
</code>```

where `anyobject' is an instance of some class belonging to the plug-in.

The plug-in id is known as the 'symbolic name' in the bundle:

```<code>String pluginid = bundle.getSymbolicName();
</code>```

FrameworkUtil is org.osgi.framework.FrameworkUtil in the org.eclipse.osgi plug-in.

Body:
I have an objects of class T that belongs to plugin P.
It is possible to retrieve the Plugin ID, trough class T?

I don't have access to plugin object but I have access to a objects that is an inner class of plugin P, I have access to PluginClassDescriptor. I have access to:

P.T object; // I need P.pluginID

Thanks

Body:
You can get the Bundle for any plug-in class using:

Bundle bundle = FrameworkUtil.getBundle(anyobject.getClass());

where `anyobject' is an instance of some class belonging to the plug-in.

The plug-in id is known as the 'symbolic name' in the bundle:

String pluginid = bundle.getSymbolicName();

FrameworkUtil is org.osgi.framework.FrameworkUtil in the org.eclipse.osgi plug-in.


问:
How to obtain text of a  element from another  element with jquery
I am trying to use a button inside a table division to set a variable as the same value as another division in the same row, but whenever I run my code (below), it returns the value of all the table divisions concatenated together. I am unsure why this was happening, so I replaced '.children()' with 'childnodes[0]' to try and get only the first name, but this just doesn't work and I don't why.

My html looks like this:

```<code>  <table>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td><button>Get First Name</button></td>
    </tr>
  </table>
</code>```

And my Javascript is this:

```<code>$(document).ready(function(){
    $("button").click(function(){
      var first = $(this).closest("tr").childNodes[0].text();
      alert(first)
        })
    });
</code>```

答:
You could use class identifiers to get information you need as well.

```<code><table>
  <tr>
    <td><span class="first-name">John</span></td>
    <td><span class="last-name">Doe</span></td>
    <td>
      <button class="btn-get-data" data-class="first-name">Get First Name</button>
      <button class="btn-get-data" data-class="last-name">Get Last Name</button>
    </td>
  </tr>
</table>

$(document).ready(function() {
  $(".btn-get-data").click(function() {
    $btn = $(this);
    $tr = $btn.closest('tr');
    var first = $tr.find('.' + $btn.attr('data-class')).html();
    alert(first);
  })
});
</code>```

If you make the button click generic like so, you can add additional buttons on the page and use that to get the class within that row.

Here is a working fiddle example: https://jsfiddle.net/b1r0nucq/

Title: How to obtain text of a <td> element from another <td> element with jquery

Body:
I am trying to use a button inside a table division to set a variable as the same value as another division in the same row, but whenever I run my code (below), it returns the value of all the table divisions concatenated together. I am unsure why this was happening, so I replaced '.children()' with 'childnodes[0]' to try and get only the first name, but this just doesn't work and I don't why.

My html looks like this:

      John
      Doe
      <button>Get First Name</button>

And my Javascript is this:

$(document).ready(function(){
    $("button").click(function(){
      var first = $(this).closest("tr").childNodes[0].text();
      alert(first)
        })
    });

Body:
You could use class identifiers to get information you need as well.

<table>
  <tr>
    <td><span class="first-name">John</span></td>
    <td><span class="last-name">Doe</span></td>
    <td>
      <button class="btn-get-data" data-class="first-name">Get First Name</button>
      <button class="btn-get-data" data-class="last-name">Get Last Name</button>
    </td>
  </tr>
</table>

$(document).ready(function() {
  $(".btn-get-data").click(function() {
    $btn = $(this);
    $tr = $btn.closest('tr');
    var first = $tr.find('.' + $btn.attr('data-class')).html();
    alert(first);
  })
});

If you make the button click generic like so, you can add additional buttons on the page and use that to get the class within that row.

Here is a working fiddle example: https://jsfiddle.net/b1r0nucq/


问:
Highest value in row in MySQL query
Could anyone enlighten how we can retrieve the highest value of row using MySQL

For example I have below data in table

```<code>A    B   C   D
3    6   8   10
</code>```

I would like retrieve the from the row

MAX() is acceptable for columns as per my understanding

Hope this is more clear now.

```<code>R1 R2 R3 R4 R5
10D 9D 8D 7D 6D
</code>```

The above data in the table. Ideally I should get a 10D as the greatest but when i execute this query. Select GREATEST(R1, R2, R3, R4, R5) from TableAA I got the output as 9D. Can someone please explain the logic that I got 9D as the greatest.

答:
When you say GREATEST('Def', 'Abc', '0ab') it sorts the text values in lexical (dictionary) order and takes the greatest one. Your values like 9A and 10B are also text strings, and the first one comes after the second one in lexical order. §

GREATEST() on a bunch of numbers does what you expect.

MySql has a hack where you can convert text strings with leading numbers to actual numbers. Add 0 to the string. 0+'10D' gets you the number 10.

So to get what you want, try

```<code>GREATEST(0+R1, 0+R2, 0+R3, 0+R4, 0+R5)
</code>```

And beware, this 0+ hack doesn't work on other makes and models of database server.

§ it doesn't actually sort them, it searches for the the greatest value, but in lexical, not numeric, order.

Title: Highest value in row in MySQL query

Body:
Could anyone enlighten how we can retrieve the highest value of row using MySQL

For example I have below data in table

A    B   C   D
3    6   8   10

I would like retrieve the from the row

MAX() is acceptable for columns as per my understanding

Hope this is more clear now.

R1 R2 R3 R4 R5
10D 9D 8D 7D 6D

The above data in the table. Ideally I should get a 10D as the greatest but when i execute this query. Select GREATEST(R1, R2, R3, R4, R5) from TableAA I got the output as 9D. Can someone please explain the logic that I got 9D as the greatest.

Body:
When you say GREATEST('Def', 'Abc', '0ab') it sorts the text values in lexical (dictionary) order and takes the greatest one. Your values like 9A and 10B are also text strings, and the first one comes after the second one in lexical order. §

GREATEST() on a bunch of numbers does what you expect.

MySql has a hack where you can convert text strings with leading numbers to actual numbers. Add 0 to the string. 0+'10D' gets you the number 10.

So to get what you want, try

GREATEST(0+R1, 0+R2, 0+R3, 0+R4, 0+R5)

And beware, this 0+ hack doesn't work on other makes and models of database server.

§ it doesn't actually sort them, it searches for the the greatest value, but in lexical, not numeric, order.


问:
Snowflake: Data Split from AWS US to AWS Australia
There is 10TB of data in SNOWFLAKE db in AWS US region.  The requirement is to split a subset of data with certain flag in a column to AWS Australia region.

After split, the US data will be around 6TB and Australia around 4TB.
There are 10 applications containing this mix of data.
I could think of 3 options to do this split.

1. Replicate the entire database from A to B.  Then pause application before breaking the replication. In B, delete data in B database where filter is A's data.  In A, repeat the delete where filter is B's data.  Clone application set and configure new set to read/write to B

2. Use CTAS in B with data from A

3. Use SSIS to push data from A to B.  For this option, the application need not be stopped.

Please advise on these options and if there is/are anymore options in which this data split can be achieved.

Regards,
Mani

答:
The whole setup on how these 10 applications access your snowflake table are unclear, but important to provide a solution.

Your best option to sync data over two snowflake accounts is using database replication failover:
https://docs.snowflake.net/manuals/user-guide/database-replication-failover.html

To split data based on a field can easily be done with materialized views that have a where clause containing this field. https://docs.snowflake.net/manuals/user-guide/views-materialized.html


问:
HTML: img inside a tag not working
Why is my image not becoming hyperlinked? Here's my HTML code (with links taken out), and the CSS of the div it's in:</p>

```<code><div class=bannercontainer>
<a href="(working URL here)" target="_blank"><img src="image.png" width="194" height="67" border="0" /></a></div>
.bannercontainer{ margin-left: auto; margin-right:auto; width:900px; height:500px; margin-top:50px;}
</code>```

答:
Adding "clear:both" to .lowerpart is a solution, of sorts. But I'd recommend re-writing your HTML. It doesn't need to be so complicated... or filled with errors :-/

Note: #feature should be a class (.feature), not an ID, as there's many of them in the document.

Tip: Trying verifying your HTML in the future: http://validator.w3.org/

Also maybe getting a book on learning HTML (Headfirst HTML/CSS couldn't make it much easier) or doing some online training: http://www.w3schools.com/html/default.asp

ContentLicense: CC BY-SA 3.0

Title: HTML: img inside a tag not working

Body:
Why is my image not becoming hyperlinked? Here's my HTML code (with links taken out), and the CSS of the div it's in:

.bannercontainer{ margin-left: auto; margin-right:auto; width:900px; height:500px; margin-top:50px;}


问:
Bootstrap tooltip wrong position
I have a simple laravel application where i like to use bootstrap tooltip.

Table:

```<code>            <table id="tableSequence" class="table" style="font-size: 12px">
                    <tr style="font-weight: 600">
                            <td data-toggle="tooltip" data-placement="top" title="Tooltip on left">EZ</td>
                            <td>MZ</td>
                            <td>WZ</td>
                            <td>EP</td>
                            <td>MP</td>
                            <td>WP</td>
                            <td>SZ</td>
                            <td>TZ</td>
                            <td>SP</td>
                            <td>TP</td>
                    </tr>
</code>```

JS

```<code>    $(function(){

    $('[data-toggle="tooltip"]').tooltip({

    });

});
</code>```

When i hoover EZ, the tooltip is shown on the left side of the screen:

Do I have to add additional code to place the tooltip near of the object?

答:
You can check my simple solution for the same problem here:

https://stackoverflow.com/a/60172398/2176096

Title: Bootstrap tooltip wrong position

Body:
I have a simple laravel application where i like to use bootstrap tooltip.

Table:

                            EZ
                            MZ
                            WZ
                            EP
                            MP
                            WP
                            SZ
                            TZ
                            SP
                            TP

JS

    $(function(){

    $('[data-toggle="tooltip"]').tooltip({

    });

});

When i hoover EZ, the tooltip is shown on the left side of the screen:

Do I have to add additional code to place the tooltip near of the object?


问:
My global variable lastValue doesn't update so I can check if and when 6 is generated twice in a row. thx
** As you can see lastValue has a global scope but I don't understand how it doesn't update when returned from the function**</p>

```<code>let numGenerator = Math.floor(Math.random() * 6)+1;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
    if(lastValue === 6 && numGenerator === 6) {
        console.log("Two 6 in a row");
    }
    lastValue = numGenerator;
};
checkForConsecutiveNumbers();
</code>```

答:
I don't understand the issue? lastValue does get updated.

let numGenerator = Math.floor(Math.random() * 6)+1;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
    if(lastValue === 6 && numGenerator === 6) {
        console.log("Two 6 in a row");
    }
    lastValue = numGenerator;
};
checkForConsecutiveNumbers();
console.log('After function call. lastValue = ', lastValue)```
</div>
</div>
</p>

<p>Currently, you are only initializing <code>numGenerator</code> once. If you re-initialize it every call to <code>checkForConsecutiveNumbers</code> it will log when 6 is generated twice. (For the example I will just force <code>numGenerator</code> to always be 6, but replace it with <code>Math.floor(Math.random() * 6)+1</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let numGenerator;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
  numGenerator = 6; // Re-generate here.
  if (lastValue === 6 && numGenerator === 6) {
    console.log("Two 6 in a row");
  }
  lastValue = numGenerator;
};

checkForConsecutiveNumbers();
checkForConsecutiveNumbers();</code>```

Adding the random generation back in and just calling it multiple times.

If you run this snippet multiple times, you will see it picks up the sequential 6's.

let numGenerator;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
  numGenerator = Math.floor(Math.random() * 6) + 1
  if (lastValue === 6 && numGenerator === 6) {
    console.log("Two 6 in a row");
  }
  lastValue = numGenerator;
};

for (let i = 0; i < 100; i++) {
  checkForConsecutiveNumbers();
}```

Body:
** As you can see lastValue has a global scope but I don't understand how it doesn't update when returned from the function**

let numGenerator = Math.floor(Math.random() * 6)+1;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
    if(lastValue === 6 && numGenerator === 6) {
        console.log("Two 6 in a row");
    }
    lastValue = numGenerator;
};
checkForConsecutiveNumbers();

Body:
I don't understand the issue? lastValue does get updated.

let numGenerator = Math.floor(Math.random() * 6)+1;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
    if(lastValue === 6 && numGenerator === 6) {
        console.log("Two 6 in a row");
    }
    lastValue = numGenerator;
};
checkForConsecutiveNumbers();
console.log('After function call. lastValue = ', lastValue)

Currently, you are only initializing numGenerator once. If you re-initialize it every call to checkForConsecutiveNumbers it will log when 6 is generated twice. (For the example I will just force numGenerator to always be 6, but replace it with Math.floor(Math.random() * 6)+1.

let numGenerator;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
  numGenerator = 6; // Re-generate here.
  if (lastValue === 6 && numGenerator === 6) {
    console.log("Two 6 in a row");
  }
  lastValue = numGenerator;
};

checkForConsecutiveNumbers();
checkForConsecutiveNumbers();

Adding the random generation back in and just calling it multiple times.

If you run this snippet multiple times, you will see it picks up the sequential 6's.

let numGenerator;
let lastValue; // undefined ?????

function checkForConsecutiveNumbers() {
  numGenerator = Math.floor(Math.random() * 6) + 1
  if (lastValue === 6 && numGenerator === 6) {
    console.log("Two 6 in a row");
  }
  lastValue = numGenerator;
};

for (let i = 0; i < 100; i++) {
  checkForConsecutiveNumbers();
}


问:
Typescript: How to declare the type for a function with custom properties that is returned from an IIFE
Say I have an object like this

```<code>const someObject: SomeObject = {
  someMethod: (function() {
    function mainMethod(x) {return x+1}
    yolo.subMethod = function(x) { return x-1 }

    return mainMethod;
  })()
}
</code>```

I tried defining its type like this:

```<code>type SomeObject = {
  someMethod: {
    (x:number): number
    subMethod(x:number): number
  }
}
</code>```

however I am getting Parameter 'x' implicitly has an 'any' type. warnings in everything inside the IIFE, which means my type is not applied.

I have already read this similar answer however it doesn't seem to work.

I am quite new to TS, and I am not yet familiar with more intricate usecases such as this, so any help would be much appreciated.

答:
Contextual typing (where TS infers parameter types based on expected type) has its limitations. One of them is that the function has to be assigned directly to a typed reference. Since mainMethod is not directly assigned anywhere upon declaration it will not benefit form contextual typing. It will be checked in the return, but it will not be contextually typed.

You will have to declare the parameter types explicitly to the functions. If you want to keep things dry you could define the type in relation to the inferred constant type instead:

```<code>const someObject = {
    someMethod: (function () {
        function mainMethod(x: number) { return x + 1 }
        mainMethod.subMethod = function (x: number) { return x - 1 }

        return mainMethod;
    })()
}

type SomeObject = typeof someObject

</code>```

Playground Link

Body:
Say I have an object like this

const someObject: SomeObject = {
  someMethod: (function() {
    function mainMethod(x) {return x+1}
    yolo.subMethod = function(x) { return x-1 }

    return mainMethod;
  })()
}

I tried defining its type like this:

type SomeObject = {
  someMethod: {
    (x:number): number
    subMethod(x:number): number
  }
}

however I am getting Parameter 'x' implicitly has an 'any' type. warnings in everything inside the IIFE, which means my type is not applied.

I have already read this similar answer however it doesn't seem to work.

I am quite new to TS, and I am not yet familiar with more intricate usecases such as this, so any help would be much appreciated.

Body:
Contextual typing (where TS infers parameter types based on expected type) has its limitations. One of them is that the function has to be assigned directly to a typed reference. Since mainMethod is not directly assigned anywhere upon declaration it will not benefit form contextual typing. It will be checked in the return, but it will not be contextually typed.

You will have to declare the parameter types explicitly to the functions. If you want to keep things dry you could define the type in relation to the inferred constant type instead:

const someObject = {
    someMethod: (function () {
        function mainMethod(x: number) { return x + 1 }
        mainMethod.subMethod = function (x: number) { return x - 1 }

        return mainMethod;
    })()
}

type SomeObject = typeof someObject

Playground Link


问:
ActiveRecord #includes, with condition, but load all relations, not just those matching condition
I have ActiveRecord models Parent and Kid.  Parents have many Kids.

I have a Parent whose name is Dad, with 3 Kids, whose names are Abel, Bobby, and Cain.  I want to find the Parent based on the name of only 1 of the Kids.

```<code>parent = Parent.includes(:kids).
  find_by(kids: { name: 'Bobby' })
</code>```

The above query provides me the Parent I want, but parent.kids only includes Bobby.  I want Abel and Cain to be included in parent.kids as well, just like if I did:

```<code>Parent.find_by(name: 'Dad').kids
</code>```

I could do:

```<code>Parent.includes(:kids).
  find_by(kids: { name: 'Bobby' }).
  tap { |parent| parent&.kids.reload }
</code>```

But is there not a “better” way of fetching the rest of the kids?  For instance, is there a way I could load all the kids of the parent while querying for the parent (via one SQL statement)?

答:
You want an INNER JOIN:

```<code>parents = Parent.joins(:kids).where(kids: { name: 'Bobby' })
</code>```

This will only include rows from parents with a match in the kids table. You can apply it as a subquery to avoid removing the rest of the joined rows:

```<code>parents = Parent.where(
            id: Parent.joins(:kids).where(kids: { name: 'Bobby' })
          ).includes(:kids)
</code>```

Body:
I have ActiveRecord models Parent and Kid.  Parents have many Kids.

I have a Parent whose name is Dad, with 3 Kids, whose names are Abel, Bobby, and Cain.  I want to find the Parent based on the name of only 1 of the Kids.

parent = Parent.includes(:kids).
  find_by(kids: { name: 'Bobby' })

The above query provides me the Parent I want, but parent.kids only includes Bobby.  I want Abel and Cain to be included in parent.kids as well, just like if I did:

Parent.find_by(name: 'Dad').kids

I could do:

Parent.includes(:kids).
  find_by(kids: { name: 'Bobby' }).
  tap { |parent| parent&.kids.reload }

But is there not a “better” way of fetching the rest of the kids?  For instance, is there a way I could load all the kids of the parent while querying for the parent (via one SQL statement)?

Body:
You want an INNER JOIN:

parents = Parent.joins(:kids).where(kids: { name: 'Bobby' })

This will only include rows from parents with a match in the kids table. You can apply it as a subquery to avoid removing the rest of the joined rows:

parents = Parent.where(
            id: Parent.joins(:kids).where(kids: { name: 'Bobby' })
          ).includes(:kids)


问:
How to close a popup by pressing outside of it
I used this command CloseWhenBackgroundIsClicked = "True" to close the popup but it is not working, how can I close the popup by clicking outside it without having to add a close button</p>

```<code><?xml version="1.0" encoding="utf-8" ?>
    <pages:PopupPage
           xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
                 xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
                 xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Agtmovel.Views.MnUsuario"
                 CloseWhenBackgroundIsClicked="True"
                   >
</code>```

答:
Xaml Side Changes= CloseWhenBackgroundIsClicked="True" => BackgroundClicked="CloseClick"

```<code><?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
       xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
       xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
       xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       x:Class="Agtmovel.Views.MnUsuario"
       BackgroundClicked="CloseClick">
</code>```

BackgroundClicked Property Event =

```<code>private async void CloseClick(object sender, EventArgs e)
{
    await PopupNavigation.Instance.PopAsync();
}
</code>```

Body:
I used this command CloseWhenBackgroundIsClicked = "True" to close the popup but it is not working, how can I close the popup by clicking outside it without having to add a close button

<?xml version="1.0" encoding="utf-8" ?>
    <pages:PopupPage
           xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
                 xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
                 xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Agtmovel.Views.MnUsuario"
                 CloseWhenBackgroundIsClicked="True"
                   >

Body:
Xaml Side Changes= CloseWhenBackgroundIsClicked="True" => BackgroundClicked="CloseClick"

<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
       xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
       xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
       xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       x:Class="Agtmovel.Views.MnUsuario"
       BackgroundClicked="CloseClick">

BackgroundClicked Property Event =

private async void CloseClick(object sender, EventArgs e)
{
    await PopupNavigation.Instance.PopAsync();
}


问:
Wordpress translation PO file
I've got an issue with a Wordpress that I'm taking over now.

There is a .mo file containing some translations and a .po file that seems to be the source. The .po file seems have been generated somehow but its structure look a little weird to me.

Here is what can be found inside.

```<code>#: /Users/yui/Sites/fondation/wp-content/themes/fondation/taxonomy-programme.php:24
msgid "Exhibitions"
msgstr "Expositions"

#: /Users/yui/Sites/fondation/wp-content/themes/fondation/archive.php:69
#: /Users/yui/Sites/fondation/wp-content/themes/fondation/single.php:43
msgid "[:en]Events[:fr]Evénements[:de]Events[:pl]Events"
msgstr ""
</code>```

When I try to generate the .mo file msgcat fondation-fr_FR.po | msgfmt -o fondation-fr_FR.mo - the .mo file contains only the first one (with both msgid and msgstr) but not the other one. The website also have an issue with that and display only the translation found in the .mo file.

Any thoughts on how to fix the .po file? Is it an old format?

答:
For the records.

The .po file had been generated by an old version of qtranslate plugin for Wordpress which didn't know how to properly handle the gettext functions in its firsts versions.

Nothing could be done to get the .po file to work. I had to create a new one manually.

Title: Wordpress translation PO file

Body:
I've got an issue with a Wordpress that I'm taking over now.

There is a .mo file containing some translations and a .po file that seems to be the source. The .po file seems have been generated somehow but its structure look a little weird to me.

Here is what can be found inside.

#: /Users/yui/Sites/fondation/wp-content/themes/fondation/taxonomy-programme.php:24
msgid "Exhibitions"
msgstr "Expositions"

#: /Users/yui/Sites/fondation/wp-content/themes/fondation/archive.php:69
#: /Users/yui/Sites/fondation/wp-content/themes/fondation/single.php:43
msgid "[:en]Events[:fr]Evénements[:de]Events[:pl]Events"
msgstr ""

When I try to generate the .mo file msgcat fondation-fr_FR.po | msgfmt -o fondation-fr_FR.mo - the .mo file contains only the first one (with both msgid and msgstr) but not the other one. The website also have an issue with that and display only the translation found in the .mo file.

Any thoughts on how to fix the .po file? Is it an old format?


问:
Method to extract exact 95% confidence values from stat_smooth(method = "glm")
I have produced a glm interaction plot using ggplot2. I have attached the code I have used and the plot

 .

I know that the grey shaded areas represent the 95% condfidence interval, but I am wondering if there is a method to get the exact values of the grey shaded areas and therefore 95% confidence interval?

```<code>#bind data togther
</code>```

Modern_EarlyHolocene<-rbind(FladenF30, FladenB30, Early_Holocene)

```<code>#Build modern vs Holocene model
</code>```

Modern_EarlyHolocene<-glm(Max_Height~Age+Time_period, data=Modern_EarlyHolocene,family = gaussian)

```<code>#Produce gg interaction plot
</code>```

Modern_EarlyHolocene_plot<-ggplot(data=Modern_EarlyHolocene) +
  aes(x = Age, y = Max_Height, group = Time_period, color = Time_period,) +>
  geom_point( alpha = .7) +
  stat_smooth(method = "glm", level=0.95) +
  expand_limits(y=c(0,90), x=c(0,250))

#add axis labels

Modern_EarlyHolocene_plot + labs(x = "Age (years)", y = 'Maximum height (mm)') +
  theme(legend.text = element_text(size = 14, colour = "Black"),
        legend.title=element_blank()) +
 theme(axis.text=element_text(size=14),
        axis.title=element_text(size=16,face="bold"))

答: You can access de plot data with layer_data(Modern_EarlyHolocene_plot, i) with i corresponding to the layer to return, in the order added to the plot

Body:
I have produced a glm interaction plot using ggplot2. I have attached the code I have used and the plot

 .

I know that the grey shaded areas represent the 95% condfidence interval, but I am wondering if there is a method to get the exact values of the grey shaded areas and therefore 95% confidence interval?

#bind data togther

Modern_EarlyHolocene<-rbind(FladenF30, FladenB30, Early_Holocene)

#Build modern vs Holocene model

Modern_EarlyHolocene<-glm(Max_Height~Age+Time_period, data=Modern_EarlyHolocene,family = gaussian)

#Produce gg interaction plot

Modern_EarlyHolocene_plot<-ggplot(data=Modern_EarlyHolocene) +
  aes(x = Age, y = Max_Height, group = Time_period, color = Time_period,) +>
  geom_point( alpha = .7) +
  stat_smooth(method = "glm", level=0.95) +
  expand_limits(y=c(0,90), x=c(0,250))

#add axis labels

Modern_EarlyHolocene_plot + labs(x = "Age (years)", y = 'Maximum height (mm)') +
  theme(legend.text = element_text(size = 14, colour = "Black"),
        legend.title=element_blank()) +
 theme(axis.text=element_text(size=14),
        axis.title=element_text(size=16,face="bold"))


问:
Apps Script (Google Sheets) How to perform .setHiddenValues with an Array
I have some values stored in an Array and now I want to remove ALL the values stored in this array from a filter.
The values are stored correctly in the array but I don't manage to remove the values from the filter.

The Array's name is HideValues

Here is some code:

```<code>  var p = 0;

  spreadsheet.getSheetByName('TEM Tool Data').getRange('\'TEM Tool Data\'!E1').activate();
  var criteria = SpreadsheetApp.newFilterCriteria();

  //Remove all PID´s from the filter
  while (p < HideValues.length){
  criteria.setHiddenValues([HideValues[p]]).build();
  p++;}

  //Filter
  spreadsheet.getSheetByName('TEM Tool Data').getFilter().setColumnFilterCriteria(5, criteria);

  //Copy filtered area
  spreadsheet.getRange('A2:I1386').activate();

  //Paste
  spreadsheet.getSheetByName('Visualization').getRange('A5').activate();
  spreadsheet.getRange('\'TEM Tool Data\'!A2:I1386').copyTo(SpreadsheetApp.getActiveRange(),
  SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.getSheetByName('Visualization').getRange('J3').activate();
};
</code>```

答:
You don't need to loop through the array

If your array is something like var HideValues = [1,2,3,4,5];,

you can simply specify criteria.setHiddenValues(HideValues).build(); - without the while loop

Also:

To a filter, you should create it first (if not already done) and apply it to a range, not sheet:

```<code>  var filter = spreadsheet.getSheetByName('TEM Tool Data').getDataRange().createFilter();
  filter.setColumnFilterCriteria(3, criteria);
</code>```

You should apply it to a range, not a sheet

Body:
I have some values stored in an Array and now I want to remove ALL the values stored in this array from a filter.
The values are stored correctly in the array but I don't manage to remove the values from the filter.

The Array's name is HideValues

Here is some code:

  var p = 0;

  spreadsheet.getSheetByName('TEM Tool Data').getRange('\'TEM Tool Data\'!E1').activate();
  var criteria = SpreadsheetApp.newFilterCriteria();

  //Remove all PID´s from the filter
  while (p < HideValues.length){
  criteria.setHiddenValues([HideValues[p]]).build();
  p++;}

  //Filter
  spreadsheet.getSheetByName('TEM Tool Data').getFilter().setColumnFilterCriteria(5, criteria);

  //Copy filtered area
  spreadsheet.getRange('A2:I1386').activate();

  //Paste
  spreadsheet.getSheetByName('Visualization').getRange('A5').activate();
  spreadsheet.getRange('\'TEM Tool Data\'!A2:I1386').copyTo(SpreadsheetApp.getActiveRange(),
  SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.getSheetByName('Visualization').getRange('J3').activate();
};

Body:
You don't need to loop through the array

If your array is something like var HideValues = [1,2,3,4,5];,

you can simply specify criteria.setHiddenValues(HideValues).build(); - without the while loop

Also:

To a filter, you should create it first (if not already done) and apply it to a range, not sheet:

  var filter = spreadsheet.getSheetByName('TEM Tool Data').getDataRange().createFilter();
  filter.setColumnFilterCriteria(3, criteria);

You should apply it to a range, not a sheet


问:
Jquery clone original HTML not DOM
I need to clone a section of markup that has already been modified in the DOM. I want to get the original HTML source - what is seen in View > Source.

clone() uses what's in the DOM

答:
A straightforward approach would be to preserve the original markup in a hidden div.  Then, clone that hidden content.

Another option would be to do an AJAX request to retrieve the original document, then load the HTML you want to duplicate from there.

Title: Jquery clone original HTML not DOM