问:
How to copy between two existing objects in javascript
I have two objects that are the same type and I want to copy the content of one of them to the other.

```<code>const Invoice1 = new InvoiceModel();

const Invoice2 = new InvoiceModel();
</code>```

now in order to have something like : Invoice2 = Invoice1

After reading :

How do I correctly clone a JavaScript object?

I tried to use any of below commands but all of them say that invoice2 is not defined at runtime:

```<code> Invoice2 = { ...Invoice1 };  //OR

 Invoice2 = Object.assign({}, Invoice1);  //OR

 Invoice2 = JSON.parse(JSON.stringify(Invoice1));
</code>```

finally I used this function to copy the content of objects by reading this article (https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d):

```<code>function CopyObject(src, target) {
  for (let prop in src) {
    if (src.hasOwnProperty(prop)) {
      target[prop] = src[prop];
    }
  }
  return target;
}
</code>```

I wonder is there any cleaner way to do that except using above function?

I have read many post regarding this issue but all of them create a new object.

答:
I have implemented a deep copier of objects, it does not override anything in the target option, but if you need that, you can achieve that as well:

```<code>var defaults = {
        options: {
                remove: true,
                enable: false,
                instance: {}
        },

        log: {
                warn: true,
                error: true
        }
};

var config = {
        options: {
                remove: false,
                instance: null
        }
};

function applyDefaults(d, t) {
    if ((typeof d !== "object") && (typeof d !== "array")) {
        return d;
    }

    if (t === undefined) {
        if (typeof d === "object") {
            t = {};
        } else if (typeof d === "array") {
            t = [];
        }
    }

    for (var key in d) {
        if (t[key] === undefined) {
            t[key] = d[key];
        } else {
            applyDefaults(d[key], t[key]);
        }
    }
    return t;
}

applyDefaults(defaults, config);
console.log(config);
</code>```

However, this will not copy "private" stuff, not defined as members of this.

Body:
I have two objects that are the same type and I want to copy the content of one of them to the other.

const Invoice1 = new InvoiceModel();

const Invoice2 = new InvoiceModel();

now in order to have something like : Invoice2 = Invoice1

After reading :

How do I correctly clone a JavaScript object?

I tried to use any of below commands but all of them say that invoice2 is not defined at runtime:

 Invoice2 = { ...Invoice1 };  //OR

 Invoice2 = Object.assign({}, Invoice1);  //OR

 Invoice2 = JSON.parse(JSON.stringify(Invoice1));

finally I used this function to copy the content of objects by reading this article (https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d):

function CopyObject(src, target) {
  for (let prop in src) {
    if (src.hasOwnProperty(prop)) {
      target[prop] = src[prop];
    }
  }
  return target;
}

I wonder is there any cleaner way to do that except using above function?

I have read many post regarding this issue but all of them create a new object.

Body:
I have implemented a deep copier of objects, it does not override anything in the target option, but if you need that, you can achieve that as well:

var defaults = {
        options: {
                remove: true,
                enable: false,
                instance: {}
        },

        log: {
                warn: true,
                error: true
        }
};

var config = {
        options: {
                remove: false,
                instance: null
        }
};

function applyDefaults(d, t) {
    if ((typeof d !== "object") && (typeof d !== "array")) {
        return d;
    }

    if (t === undefined) {
        if (typeof d === "object") {
            t = {};
        } else if (typeof d === "array") {
            t = [];
        }
    }

    for (var key in d) {
        if (t[key] === undefined) {
            t[key] = d[key];
        } else {
            applyDefaults(d[key], t[key]);
        }
    }
    return t;
}

applyDefaults(defaults, config);
console.log(config);

However, this will not copy "private" stuff, not defined as members of this.


来源: stackexchange

问:
Updating JAVA_HOME using a bash script
I'm new to bash scripting thus the question,
I've a function which install java in a system and updates the path in bashrc.

```<code>install_java(){
  echo "Installing Java 8 & 11 and setting JAVA_HOME to 8"
  brew tap adoptopenjdk/openjdk
  brew cask install adoptopenjdk8
  brew cask install adoptopenjdk11
  echo "export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home"
}
</code>```

I want to update the hardcoded version string with the output of java -version
This is my output of java -version

```<code>java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)
</code>```

Can someone help me extract the version number from the first line an substitute it for the version number in the JAVA_HOME variable?

答:
Here java version is parsed using java -version|grep -oP 'java version\s"\K[^"]+' and stored in java_ver variable and later substituted in JAVA_HOME assignment.

```<code>install_java(){
  echo "Installing Java 8 & 11 and setting JAVA_HOME to 8"
  brew tap adoptopenjdk/openjdk
  brew cask install adoptopenjdk8
  brew cask install adoptopenjdk11
  java_ver=$(java -version 2>&1|grep -oP 'version\s"\K[^"]+')
  echo "export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk${java_ver}.jdk/Contents/Home"
}
</code>```

Explanation of java -version 2>&1|grep -oP 'version\s"\K[^"]+':

grep -o: this will only extract the matching content not the matching line, -P flag enable PCRE, now the regex is java version followed be space(\s) then followed by " till next " is seen. Also, ignore anything on the left of \K.

If you do not have -P enabled on your grep then you can use awk command:

```<code>install_java(){
  echo "Installing Java 8 & 11 and setting JAVA_HOME to 8"
  brew tap adoptopenjdk/openjdk
  brew cask install adoptopenjdk8
  brew cask install adoptopenjdk11
  java_ver=$(java -version 2>&1|awk '/version/{gsub(/"/,"",$NF);print $NF}')
  echo "export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk${java_ver}.jdk/Contents/Home"
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Updating JAVA_HOME using a bash script

Body:
I'm new to bash scripting thus the question,
I've a function which install java in a system and updates the path in bashrc.

install_java(){
  echo "Installing Java 8 & 11 and setting JAVA_HOME to 8"
  brew tap adoptopenjdk/openjdk
  brew cask install adoptopenjdk8
  brew cask install adoptopenjdk11
  echo "export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home"
}

I want to update the hardcoded version string with the output of java -version
This is my output of java -version

java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)

Can someone help me extract the version number from the first line an substitute it for the version number in the JAVA_HOME variable?

Body:
Here java version is parsed using java -version|grep -oP 'java version\s"\K[^"]+' and stored in java_ver variable and later substituted in JAVA_HOME assignment.

install_java(){
  echo "Installing Java 8 & 11 and setting JAVA_HOME to 8"
  brew tap adoptopenjdk/openjdk
  brew cask install adoptopenjdk8
  brew cask install adoptopenjdk11
  java_ver=$(java -version 2>&1|grep -oP 'version\s"\K[^"]+')
  echo "export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk${java_ver}.jdk/Contents/Home"
}

Explanation of java -version 2>&1|grep -oP 'version\s"\K[^"]+':

grep -o: this will only extract the matching content not the matching line, -P flag enable PCRE, now the regex is java version followed be space(\s) then followed by " till next " is seen. Also, ignore anything on the left of \K.

If you do not have -P enabled on your grep then you can use awk command:

install_java(){
  echo "Installing Java 8 & 11 and setting JAVA_HOME to 8"
  brew tap adoptopenjdk/openjdk
  brew cask install adoptopenjdk8
  brew cask install adoptopenjdk11
  java_ver=$(java -version 2>&1|awk '/version/{gsub(/"/,"",$NF);print $NF}')
  echo "export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk${java_ver}.jdk/Contents/Home"
}


问:
How to make ScrollView consume touch event even when it's scrolled to the end?
I have an FSPagerView, which has an item that contains scrollable barchart (scrollview having multiple stackviews). When I scroll barchart, if there is a scrollable space, then touch event is consumed by the barchart and it scrolls. If there is no scrollable space on a side and I keep scrolling to that side touching barchart, it does not consume touch event anymore and instead the whole FSPagerView scrolls. How can I make scrollview consume touch event even in such case? In short, I don't want to scroll FSPagerView when touching barchart.

Here is a video:
https://streamable.com/kuxta

答:
You can try to manipulate UIScrollView's gesture recognizer:

scrollView.panGestureRecognizer

I never tested it with UIScrollView's panGestureRecognizer, but general idea is to
add a gesture recognizer to FSPagerView and to set relations (using UIGestureRecognizer's delegate) between that recognizer and panGestureRecognizer to prevent it from firing


问:
Why does it not show the value when it is 0?
I have to use aggregate for my assignment but I'm facing this problem

when I try to get the count of credit that are more than 2, it works because the count value is more than 0, but when i try finding the count of credit that is more than 6, where value of the count is 0, it does not print

db.Subject.aggregate([{"$match":{"subject.credit":{"$gt":2}}},{"$count": "Total"}])

{"Total" : 7}

db.Subject.aggregate([{"$match":{"subject.credit":{"$gt":6}}},{"$count": "Total"}])

does not print cause value is 0

I expected the out put to show {"Total" : 0} but it does not show that.

答: That's because the $match stage returns no document, as a result of which the subsequent stage ($count) doesn't come into the picture at all


问:
ARG substitution in RUN command not working for Dockerfile
In my Dockerfile I have the following:

```<code>ARG a-version
RUN wget -q -O /tmp/alle.tar.gz http://someserver/server/$a-version/a-server-$a-version.tar.gz && \
    mkdir /opt/apps/$a-version
</code>```

However when building this with:

```<code>--build-arg http_proxy=http://myproxy","--build-arg a-version=a","--build-arg b-version=b"
</code>```

Step 10/15 : RUN wget... is shown with $a-version in the path instead of the substituted value and the build fails.

I have followed the instructions shown here but must be missing something else.

My questions is, what could be causing this issue and how can i solve
  it?

答:
I had the same problem using Windows containers for Windows.

Instead of doing this (Which works in linux containers)

```<code>FROM alpine
ARG TARGETPLATFORM
RUN echo "I'm building for $TARGETPLATFORM"
</code>```

You need to do this

```<code>FROM mcr.microsoft.com/windows/servercore
ARG TARGETPLATFORM
RUN echo "I'm building for %TARGETPLATFORM%"
</code>```

Just change the variable resolution according to the OS.

ContentLicense: CC BY-SA 3.0

Body:
In my Dockerfile I have the following:

ARG a-version
RUN wget -q -O /tmp/alle.tar.gz http://someserver/server/$a-version/a-server-$a-version.tar.gz && \
    mkdir /opt/apps/$a-version

However when building this with:

--build-arg http_proxy=http://myproxy","--build-arg a-version=a","--build-arg b-version=b"

Step 10/15 : RUN wget... is shown with $a-version in the path instead of the substituted value and the build fails.

I have followed the instructions shown here but must be missing something else.

My questions is, what could be causing this issue and how can i solve
  it?

Body:
I had the same problem using Windows containers for Windows.

Instead of doing this (Which works in linux containers)

FROM alpine
ARG TARGETPLATFORM
RUN echo "I'm building for $TARGETPLATFORM"

You need to do this

FROM mcr.microsoft.com/windows/servercore
ARG TARGETPLATFORM
RUN echo "I'm building for %TARGETPLATFORM%"

Just change the variable resolution according to the OS.


问:
How do I open a link in a new tab but stay on the same page using HTML code?
try this code...</p>

```<code><a href="http://example.com/"  target="_blank">Open New Link</a>
</code>```

答:
You can try using window.open to open the new window and returning false to prevent the default action.</p>

```<code><a href="http://example.com/"  target="_blank" onclick="window.open( 'http://example.com/' ); return false;">Open New Link</a>
</code>```

Body:
try this code...

Open New Link

Body:
You can try using window.open to open the new window and returning false to prevent the default action.

<a href="http://example.com/"  target="_blank" onclick="window.open( 'http://example.com/' ); return false;">Open New Link</a>


问:
How to generate hyperlinks in table using go template
I want to generate an html table which includes some hyperlink strings in one table cell.
e.g,

```<code><a href="http://logd/logs/2800643/">2800643</a>
<a href="http://logd/logs/2800795/">2800795</a>
<a href="http://logd/logs/2801109/">2801109</a>
</code>```

I've defined one template which can handle the table very well except this hyperlink thing.

```<code>{{ range . }}
<tr>
<td>{{ .Name }}</td>
<td>{{ .Logs }}</td>
</tr>
{{ end }}
</code>```

Here I want to have Logs to be hyperlinked.
If I pass a formatted string into Logs here, < > will be parsed like below:

```<code><a href="http://logd/logs/2801103/">2801103</a&gt
</code>```

Based on the information I learned from go website, looks like I need to define another template embedded into this one.
Suppose it's to replace {{ .Logs }} here. Like:

```<code>{{ range . }}
<a href="http://logd/logs/{{.LogID}}/">{{.LogID}}</a>
{{ end }}
</code>```

Wonder is there any example available ? Thanks

答:
There exist especially for html an html-template which uses type html:

HTML encapsulates a known safe HTML document fragment.

That means:

Based on the information I learned from go website, looks like I need to define another template embedded into this one. Suppose it's to replace {{ .Logs }} here.

Instead of using string, use type html in your struct.

Body:
I want to generate an html table which includes some hyperlink strings in one table cell.
e.g,

2800643
2800795
2801109

I've defined one template which can handle the table very well except this hyperlink thing.

{{ range . }}

{{ .Name }}
{{ .Logs }}

{{ end }}

Here I want to have Logs to be hyperlinked.
If I pass a formatted string into Logs here, < > will be parsed like below:

2801103</a&gt

Based on the information I learned from go website, looks like I need to define another template embedded into this one.
Suppose it's to replace {{ .Logs }} here. Like:

{{ range . }}
{{.LogID}}
{{ end }}

Wonder is there any example available ? Thanks


问:
numba ahead of time compilation of recursive function
I am trying to compile a recursive function ahead of time. As a MCVE, let's take the following function:

```<code>#import numba as nb
from numba.pycc import CC
cc = CC('precompiled')

#@nb.njit
@cc.export('gsum', 'int64(int64)')
def gsum(n):
    if n>1:
        return n+gsum(n-1)
    else:
        return 1

if __name__== '__main__':
##    print(gsum(5))
    cc.compile()
</code>```

If I run this code, I get the following error trace:

```<code>Traceback (most recent call last):
  File "numba_ahead.py", line 17, in <module>
    cc.compile()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/cc.py", line 212, in compile
    objects, dll_exports = self._compile_object_files(build_dir)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/cc.py", line 200, in _compile_object_files
    compiler.write_native_object(temp_obj, wrap=True)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/compiler.py", line 198, in write_native_object
    library = self._cull_exports()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/compiler.py", line 157, in _cull_exports
    locals={}, library=library)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 904, in compile_extra
    return pipeline.compile_extra(func)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 367, in compile_extra
    return self._compile_bytecode()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 835, in _compile_bytecode
    return self._compile_core()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 822, in _compile_core
    res = pm.run(self.status)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 253, in run
    raise patched_exception
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 244, in run
    stage()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 477, in stage_nopython_frontend
    self.locals)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 1005, in type_inference_stage
    infer.build_constraint()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 816, in build_constraint
    self.constrain_statement(inst)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1016, in constrain_statement
    self.typeof_assign(inst)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1079, in typeof_assign
    self.typeof_global(inst, inst.target, value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1177, in typeof_global
    typ = self.resolve_value_type(inst, gvar.value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1100, in resolve_value_type
    raise TypingError(msg, loc=inst.loc)
numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Untyped global name 'gsum': cannot determine Numba type of <class 'function'>

File "numba_ahead.py", line 9:
def gsum(n):
    <source elided>
    if n>1:
        return n+gsum(n-1)
        ^
</code>```

So apparently cc.export doesn't know the type of the function it is compiling, if that function calls itself. Is there any way to fix the problem? When I compile the same code just in time with njit (commented-out lines) the code compiles just fine.

答:
I've found that when using numbasometimes simply changing the way I do particular loops and calculations can fix these issues.  In your case gsum below works:

#import numba as nb
from numba.pycc import CC
cc = CC('precompiled')

#@nb.njit
@cc.export('gsum', 'int64(int64)')
def gsum(n):
    run=True
    sm=n
    while n:
        n=n-1
        sm+=n
    return sm

def slow_gsum(n):
    run=True
    sm=n
    while n:
        n=n-1
        sm+=n
    return sm

def slow_gsum2(n):
    if n>1:
        return n+slow_gsum2(n-1)
    else:
        return 1

cc.compile()
```

<p>You can test it like so:</p>

<pre class="lang-py prettyprint-override"><code>import precompiled
N=1e2
%time out1=precompiled.gsum(N)
%time out2=slow_gsum(N)
%time out3=slow_gsum2(N)
out1==out2,out1==out3,out1

"""output:
CPU times: user 6 µs, sys: 0 ns, total: 6 µs
Wall time: 11 µs
CPU times: user 12 µs, sys: 1e+03 ns, total: 13 µs
Wall time: 15 µs
CPU times: user 44 µs, sys: 1e+03 ns, total: 45 µs
Wall time: 48.9 µs
(True, True, 5050)
"""
</code>```

Here I set N=1e2 so we could test against your recursive solution (going higher gives a max-recursion error).  You can really see the numba speed up by going to higher values of N:

N=1e8
%time out1=precompiled.gsum(N)
%time out2=slow_gsum(N)
out1==out2,out1

"""output:
CPU times: user 7 µs, sys: 1e+03 ns, total: 8 µs
Wall time: 11 µs
CPU times: user 6.14 s, sys: 10.9 ms, total: 6.15 s
Wall time: 6.16 s
(True, 5000000050000000)
"""
```

Body:
I am trying to compile a recursive function ahead of time. As a MCVE, let's take the following function:

#import numba as nb
from numba.pycc import CC
cc = CC('precompiled')

#@nb.njit
@cc.export('gsum', 'int64(int64)')
def gsum(n):
    if n>1:
        return n+gsum(n-1)
    else:
        return 1

if __name__== '__main__':
##    print(gsum(5))
    cc.compile()

If I run this code, I get the following error trace:

Traceback (most recent call last):
  File "numba_ahead.py", line 17, in <module>
    cc.compile()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/cc.py", line 212, in compile
    objects, dll_exports = self._compile_object_files(build_dir)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/cc.py", line 200, in _compile_object_files
    compiler.write_native_object(temp_obj, wrap=True)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/compiler.py", line 198, in write_native_object
    library = self._cull_exports()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/pycc/compiler.py", line 157, in _cull_exports
    locals={}, library=library)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 904, in compile_extra
    return pipeline.compile_extra(func)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 367, in compile_extra
    return self._compile_bytecode()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 835, in _compile_bytecode
    return self._compile_core()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 822, in _compile_core
    res = pm.run(self.status)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 253, in run
    raise patched_exception
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 244, in run
    stage()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 477, in stage_nopython_frontend
    self.locals)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/compiler.py", line 1005, in type_inference_stage
    infer.build_constraint()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 816, in build_constraint
    self.constrain_statement(inst)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1016, in constrain_statement
    self.typeof_assign(inst)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1079, in typeof_assign
    self.typeof_global(inst, inst.target, value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1177, in typeof_global
    typ = self.resolve_value_type(inst, gvar.value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numba/typeinfer.py", line 1100, in resolve_value_type
    raise TypingError(msg, loc=inst.loc)
numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Untyped global name 'gsum': cannot determine Numba type of <class 'function'>

File "numba_ahead.py", line 9:
def gsum(n):
    <source elided>
    if n>1:
        return n+gsum(n-1)
        ^

So apparently cc.export doesn't know the type of the function it is compiling, if that function calls itself. Is there any way to fix the problem? When I compile the same code just in time with njit (commented-out lines) the code compiles just fine.

Body:
I've found that when using numbasometimes simply changing the way I do particular loops and calculations can fix these issues.  In your case gsum below works:

#import numba as nb
from numba.pycc import CC
cc = CC('precompiled')

#@nb.njit
@cc.export('gsum', 'int64(int64)')
def gsum(n):
    run=True
    sm=n
    while n:
        n=n-1
        sm+=n
    return sm

def slow_gsum(n):
    run=True
    sm=n
    while n:
        n=n-1
        sm+=n
    return sm

def slow_gsum2(n):
    if n>1:
        return n+slow_gsum2(n-1)
    else:
        return 1

cc.compile()

You can test it like so:

import precompiled
N=1e2
%time out1=precompiled.gsum(N)
%time out2=slow_gsum(N)
%time out3=slow_gsum2(N)
out1==out2,out1==out3,out1

"""output:
CPU times: user 6 µs, sys: 0 ns, total: 6 µs
Wall time: 11 µs
CPU times: user 12 µs, sys: 1e+03 ns, total: 13 µs
Wall time: 15 µs
CPU times: user 44 µs, sys: 1e+03 ns, total: 45 µs
Wall time: 48.9 µs
(True, True, 5050)
"""

Here I set N=1e2 so we could test against your recursive solution (going higher gives a max-recursion error).  You can really see the numba speed up by going to higher values of N:

N=1e8
%time out1=precompiled.gsum(N)
%time out2=slow_gsum(N)
out1==out2,out1

"""output:
CPU times: user 7 µs, sys: 1e+03 ns, total: 8 µs
Wall time: 11 µs
CPU times: user 6.14 s, sys: 10.9 ms, total: 6.15 s
Wall time: 6.16 s
(True, 5000000050000000)
"""


问:
Random number generator in VHDL
I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user.
I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

```<code>RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;
</code>```

Is there any alternatives for this problem?

答:
Just for the record, in case anyone needs something similar, I used the above ideas by creating a do file which first writes the date in a file and then runs the do file of the actual test bench which reads this number as suggested before.</p>

```<code>set t [clock seconds]
set outputFile [open date.txt w]
puts $outputFile $t
close $outputFile
do testbench.do
</code>```

Title: Random number generator in VHDL

Body:
I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user.
I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;

Is there any alternatives for this problem?

Body:
Just for the record, in case anyone needs something similar, I used the above ideas by creating a do file which first writes the date in a file and then runs the do file of the actual test bench which reads this number as suggested before.

set t [clock seconds]
set outputFile [open date.txt w]
puts $outputFile $t
close $outputFile
do testbench.do


问:
In R, assigning a number to a date, where the number corresponds to the nth rolling, non-overlapping period in a year that the date is included in
I need to calculate rolling but non-overlapping 7-day means in a huge dataset so that I can calculate the number of 7-day mean exceedences (means above a certain threshold) for each station.  The dataset looks something like this:

```<code>STATION  DATE         VALUE
A   1/15/2010   4
A   1/18/2010   5
A   1/25/2011   2
A   1/30/2011   1
A   2/2/2011    14
B   5/6/2012    6
B   5/14/2012   4
B   5/17/2012   3
B   1/29/2013   16
</code>```

I want it to look like this:

```<code>STATION DATE         VALUE  7DAYPERIOD  YEAR-7DAYPERIOD
A   1/15/2010   4   1   2010-1
A   1/18/2010   5   1   2010-1
A   1/25/2011   2   1   2011-1
A   1/30/2011   1   1   2011-1
A   2/2/2011    14  2   2011-2
B   5/6/2012    6   1   2012-1
B   5/14/2012   4   2   2012-2
B   5/17/2012   3   2   2012-2
B   1/29/2013   16  1   2013-1
</code>```

where the "7DAYPERIOD" corresponds to the nth non-overlapping 7-day period relative to the earliest date in a year for a station.  I was then going to concatenate the year with this number ("YEAR-7DAYPERIOD") and then aggregate by this identifier and station to calculate the means for each station.

I initially thought that lubridate "week" would help me out with this.  But "week" gives a number relative to January 1st.  I need the number to be relative to the earliest date in the year that is represented in the dataset AND have it be specific for a station.

答:
This reproduces your example, but you don't have any cases dealing with year boundaries. We can do integer division with %/% to count the number of whole 7 day periods since the first date in a year. Implicitly, because we group_by both STATION and YEAR, this will cut short any 7 day period that crosses the end of the year (which can have ramifications if you are aggregating these values).

library(tidyverse)

library(lubridate)
tbl <- read_table2(
"STATION  DATE         VALUE
A   1/15/2010   4
A   1/18/2010   5
A   1/25/2011   2
A   1/30/2011   1
A   2/2/2011    14
B   5/6/2012    6
B   5/14/2012   4
B   5/17/2012   3
B   1/29/2013   16"
)
tbl %>%
  mutate(
    DATE = mdy(DATE),
    YEAR = year(DATE)
  ) %>%
  group_by(STATION, YEAR) %>%
  mutate(
    `7DAYPERIOD` = as.integer(DATE - first(DATE)) %/% 7 + 1,
    `YEAR-7DAYPERIOD` = str_c(YEAR, "-", `7DAYPERIOD`)
  )
#> # A tibble: 9 x 6
#> # Groups:   STATION, YEAR [4]
#>   STATION DATE       VALUE  YEAR `7DAYPERIOD` `YEAR-7DAYPERIOD`
#>   <chr>   <date>     <dbl> <dbl>        <dbl> <chr>
#> 1 A       2010-01-15     4  2010            1 2010-1
#> 2 A       2010-01-18     5  2010            1 2010-1
#> 3 A       2011-01-25     2  2011            1 2011-1
#> 4 A       2011-01-30     1  2011            1 2011-1
#> 5 A       2011-02-02    14  2011            2 2011-2
#> 6 B       2012-05-06     6  2012            1 2012-1
#> 7 B       2012-05-14     4  2012            2 2012-2
#> 8 B       2012-05-17     3  2012            2 2012-2
#> 9 B       2013-01-29    16  2013            1 2013-1
```

Created on 2019-05-28 by the reprex package (v0.3.0)

Body:
I need to calculate rolling but non-overlapping 7-day means in a huge dataset so that I can calculate the number of 7-day mean exceedences (means above a certain threshold) for each station.  The dataset looks something like this:

STATION  DATE         VALUE
A   1/15/2010   4
A   1/18/2010   5
A   1/25/2011   2
A   1/30/2011   1
A   2/2/2011    14
B   5/6/2012    6
B   5/14/2012   4
B   5/17/2012   3
B   1/29/2013   16

I want it to look like this:

STATION DATE         VALUE  7DAYPERIOD  YEAR-7DAYPERIOD
A   1/15/2010   4   1   2010-1
A   1/18/2010   5   1   2010-1
A   1/25/2011   2   1   2011-1
A   1/30/2011   1   1   2011-1
A   2/2/2011    14  2   2011-2
B   5/6/2012    6   1   2012-1
B   5/14/2012   4   2   2012-2
B   5/17/2012   3   2   2012-2
B   1/29/2013   16  1   2013-1

where the "7DAYPERIOD" corresponds to the nth non-overlapping 7-day period relative to the earliest date in a year for a station.  I was then going to concatenate the year with this number ("YEAR-7DAYPERIOD") and then aggregate by this identifier and station to calculate the means for each station.

I initially thought that lubridate "week" would help me out with this.  But "week" gives a number relative to January 1st.  I need the number to be relative to the earliest date in the year that is represented in the dataset AND have it be specific for a station.

Body:
This reproduces your example, but you don't have any cases dealing with year boundaries. We can do integer division with %/% to count the number of whole 7 day periods since the first date in a year. Implicitly, because we group_by both STATION and YEAR, this will cut short any 7 day period that crosses the end of the year (which can have ramifications if you are aggregating these values).

library(tidyverse)

library(lubridate)
tbl <- read_table2(
"STATION  DATE         VALUE
A   1/15/2010   4
A   1/18/2010   5
A   1/25/2011   2
A   1/30/2011   1
A   2/2/2011    14
B   5/6/2012    6
B   5/14/2012   4
B   5/17/2012   3
B   1/29/2013   16"
)
tbl %>%
  mutate(
    DATE = mdy(DATE),
    YEAR = year(DATE)
  ) %>%
  group_by(STATION, YEAR) %>%
  mutate(
    `7DAYPERIOD` = as.integer(DATE - first(DATE)) %/% 7 + 1,
    `YEAR-7DAYPERIOD` = str_c(YEAR, "-", `7DAYPERIOD`)
  )
#> # A tibble: 9 x 6
#> # Groups:   STATION, YEAR [4]
#>   STATION DATE       VALUE  YEAR `7DAYPERIOD` `YEAR-7DAYPERIOD`
#>   <chr>   <date>     <dbl> <dbl>        <dbl> <chr>
#> 1 A       2010-01-15     4  2010            1 2010-1
#> 2 A       2010-01-18     5  2010            1 2010-1
#> 3 A       2011-01-25     2  2011            1 2011-1
#> 4 A       2011-01-30     1  2011            1 2011-1
#> 5 A       2011-02-02    14  2011            2 2011-2
#> 6 B       2012-05-06     6  2012            1 2012-1
#> 7 B       2012-05-14     4  2012            2 2012-2
#> 8 B       2012-05-17     3  2012            2 2012-2
#> 9 B       2013-01-29    16  2013            1 2013-1

Created on 2019-05-28 by the reprex package (v0.3.0)


问:
Updating all packages with Npm
I have a fairly large number of packages that are outdated and I want to update. I tried running npm update as described in the npm documentation: npm update --depth 9999 -dev
The update took a long time and at the end it failed. I tried a few more time, I set the stack size to unlimited, etc, but it always takes hours and at the end it fails.

I tried updating a single package with --depth 999 (not 9999) and that failed as well.

Is there any recommended way how to update all packages that works?

```<code>**Edit:** At first I was getting  `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit`
</code>```

Then I got a heap exceeded exception:

```<code>FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
</code>```

And finally, I got Max call stack size exceeded.

I set the stack size to unlimited and lowered the depth, but it's been running for hours with no result.

答:
Run:

```<code>npm cache clean
</code>```

and try again.

Title: Updating all packages with Npm

Body:
I have a fairly large number of packages that are outdated and I want to update. I tried running npm update as described in the npm documentation: npm update --depth 9999 -dev
The update took a long time and at the end it failed. I tried a few more time, I set the stack size to unlimited, etc, but it always takes hours and at the end it fails.

I tried updating a single package with --depth 999 (not 9999) and that failed as well.

Is there any recommended way how to update all packages that works?

**Edit:** At first I was getting  `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit`

Then I got a heap exceeded exception:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

And finally, I got Max call stack size exceeded.

I set the stack size to unlimited and lowered the depth, but it's been running for hours with no result.

Body:
Run:

npm cache clean

and try again.


问:
Case based If then statements in a userform
Scenario 1: If Combobox 2 displays the same text/value currently in the
worksheet MRFL Range(A1:A250) and combobox 1 displays the same text/value as in worksheet MFRL Range(B1:B250) then only change the value of column AE in the same row as the combobox 2 value in Worksheet MFGLR.

Scenario 2: If Combobox 2 displays the same text/value currently in the worksheet MRFL Range(A1:A250) and combobox 1 displays a different text then in worksheet MFRL Range(B1:B250) then add the values of combobox1 and combobox2 at the next available row in worksheet MFRL, Combobox1 in column B and Combobox2 in column A. And then only change the value of column AE in the same row as the combobox 2 value in Worksheet MFGLR.

Scenario 3: If Combobox 2 displays a different text/value currently in the worksheet MRFL Range(A1:A250) and combobox 1 displays a different text then in worksheet MFRL Range(B1:B250) then add the values of combobox1 and combobox2 at the next available row in worksheet MFRL, add combobox2 value at the next available row in Column A in the worksheet CT and add the combobox 2 value in the next available row in Column A of worksheet MFGLR Combobox1 in column B and Combobox2 in column A. And then only change the value of column AE in the same row as the combobox 2 value in Worksheet MFGLR.

For Scenarios 1 and 2, I'm having trouble having the code find the same row as combobox2 value and then pasting the textbox1 value 31 columns to the right as that. This is what I have so far.

```<code>With Worksheets("MFGLR").Range("a1:a500")
Set C = .Find(ComboBox2.Value, LookIn:=xlValues)
If Not C Is Nothing Then
firstAddress = C.Address
Do
    C.Value = TextBox1.Value
    Set C = .FindNext(C)
Loop While Not C Is Nothing
End If
End With
</code>```

The scenarios don't seem to be holding true for all the cases

I would like the border of CT to go from the lastrow Column A to Column V

I would like the border of MFRL to go from lastrow Column A to Column E

I would like the border of MFRL to go from lastrow Column A to Column AM

Fill down from the last row in MFGLR column AF to column AH

This is my WIP for all the scenarios with borders and filldown.

```<code>Option Explicit
Private Sub CommandButton1_Click()

Dim ColA As New Scripting.Dictionary  'Need Microsoft Scripting Runtime Reference
Dim ColB As New Scripting.Dictionary
Dim LastRow As Long
Dim Criteria1 As Boolean
Dim Criteria2 As Boolean
Dim C As Range

With ThisWorkbook.Sheets("MFRL")
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'This gets the last row on column A
    For Each C In .Range("A1:A" & LastRow) 'loop through the whole column
    On Error Resume Next
        'If you have duplicated entries this will throw an error
        ColA.Add C.Value, C.Row 'add the values from column A to DictA, also store it's row for later purposes
        ColB.Add C.Offset(0, 1).Value, C.Row 'add the values from column B to DictB, also store it's row for later purposes
    Next C
    'Criterias will give value of True if matched or False if not
    Criteria1 = ColA.Exists(ComboBox2.Value) 'this is getting matched with ColA Dictionary
    Criteria2 = ColB.Exists(ComboBox1.Value) 'this is getting matched with ColB Dictionary
    If Criteria1 And Criteria2 Then 'SCENARIO 1
        .Cells(ColA(ComboBox2.Value), "AE:100") = TextBox1.Value
    ElseIf Criteria1 And Not Criteria2 Then 'SCENARIO 2
        .Cells(LastRow + 1, 1) = ComboBox2.Value
        .Cells(LastRow + 1, 2) = ComboBox1.Value
        .Cells(ColA(ComboBox2.Value), "AE") = TextBox1.Value
    With Worksheets("MFRL")
        .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).AutoFill .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2)
        .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2).Borders.LineStyle = xlContinuous
        End With
    ElseIf Not Criteria1 And Not Criteria2 Then 'SCENARIO 3
        .Cells(LastRow + 1, 1) = ComboBox2.Value
        .Cells(LastRow + 1, 2) = ComboBox1.Value
        'Add data to the column A next blank row in sheet CT
        LastRow = ThisWorkbook.Sheets("CT").Cells(ThisWorkbook.Sheets("CT").Rows.Count, 1).End(xlUp).Row + 1
        ThisWorkbook.Sheets("CT").Cells(LastRow, 1) = ComboBox2.Value
        ThisWorkbook.Sheets("CT").Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 21).AutoFill .Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 21).Resize(2)
        ThisWorkbook.Sheets("CT").Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 21).Resize(2).Borders.LineStyle = xlContinuous
        'Add data to the column A next blank row in sheet MFGLR
        LastRow = ThisWorkbook.Sheets("MFGL R").Cells(ThisWorkbook.Sheets("MFGLR").Rows.Count, 1).End(xlUp).Row + 1
        ThisWorkbook.Sheets("MFGLR").Cells(LastRow, 1) = ComboBox2.Value
        ThisWorkbook.Sheets("MFGLR").Cells(LastRow, "AE") = TextBox1.Value
        ThisWorkbook.Sheets("MFGLR").Cells(Rows.Count, "AE").End(xlUp).Offset(-1, 1).Resize(, 3).AutoFill .Cells(Rows.Count, "AE").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2)
        ThisWorkbook.Sheets("MFGLR").Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 38).Resize(2).Borders.LineStyle = xlContinuous
        ThisWorkbook.Sheets("MFRL").Cells(LastRow, 1) = ComboBox2.Value
        ThisWorkbook.Sheets("MFRL").Cells(LastRow, 2) = ComboBox1.Value
        ThisWorkbook.Sheets("MFRL").Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).AutoFill .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2)
        ThisWorkbook.Sheets("MFRL").Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2).Borders.LineStyle = xlContinuous
   End If
 End With
 ActiveWorkbook.RefreshAll
 Unload Me
 End Sub
</code>```

答:
If I understood all your scenarios ok this should do it, otherwise, please feel free to amend the code:</p>

```<code>Option Explicit 'always get this, it forces you to declare all your variables
Sub Test()

    Dim ColA As New Scripting.Dictionary  'Need Microsoft Scripting Runtime Reference
    Dim ColB As New Scripting.Dictionary
    Dim LastRow As Long
    Dim Criteria1 As Boolean
    Dim Criteria2 As Boolean
    Dim C As Range

    With ThisWorkbook.Sheets("MFGLR")
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'This gets the last row on column A
        For Each C In .Range("A1:A" & LastRow) 'loop through the whole column
            'If you have duplicated entries this will throw an error
            ColA.Add C.Value, C.Row 'add the values from column A to DictA, also store it's row for later purposes
            ColB.Add C.Offset(0, 1).Value, C.Row 'add the values from column B to DictB, also store it's row for later purposes
        Next C
        'Criterias will give value of True if matched or False if not
        Criteria1 = ColA.Exists(Combobox2.Value) 'this is getting matched with ColA Dictionary
        Criteria2 = ColB.Exists(Combobox1.Value) 'this is getting matched with ColB Dictionary
        If Criteria1 And Criteria2 Then 'SCENARIO 1
            .Cells(ColA(Combobox2.Value), "AE") = Combobox2.Value
        ElseIf Criteria1 And Not Criteria2 Then 'SCENARIO 2
            .Cells(LastRow + 1, 1) = Combobox2.Value
            .Cells(LastRow + 1, 2) = Combobox1.Value
        ElseIf Not Criteria1 And Not Criteria2 Then 'SCENARIO 3
            .Cells(LastRow + 1, 1) = Combobox2.Value
            .Cells(LastRow + 1, 2) = Combobox1.Value
            'Add data to the column A next blank row in sheet CT
            LastRow = ThisWorkbook.Sheets("CT").Cells(ThisWorkbook.Sheets("CT").Rows.Count, 1).End(xlUp).Row + 1
            ThisWorkbook.Sheets("CT").Cells(LastRow, 1) = Combobox2.Value
            'Add data to the column A next blank row in sheet MFGLR
            LastRow = ThisWorkbook.Sheets("MFGLR ").Cells(ThisWorkbook.Sheets("MFGLR ").Rows.Count, 1).End(xlUp).Row + 1
            ThisWorkbook.Sheets("MFGLR").Cells(LastRow, 1) = Combobox2.Value
            ThisWorkbook.Sheets("MFGLR").Cells(LastRow, 2) = Combobox1.Value
            ThisWorkbook.Sheets("MFGLR").Cells(LastRow + 1, "AE") = Combobox2.Value
        End If
    End With

End Sub
</code>```

Body:
Scenario 1: If Combobox 2 displays the same text/value currently in the
worksheet MRFL Range(A1:A250) and combobox 1 displays the same text/value as in worksheet MFRL Range(B1:B250) then only change the value of column AE in the same row as the combobox 2 value in Worksheet MFGLR.

Scenario 2: If Combobox 2 displays the same text/value currently in the worksheet MRFL Range(A1:A250) and combobox 1 displays a different text then in worksheet MFRL Range(B1:B250) then add the values of combobox1 and combobox2 at the next available row in worksheet MFRL, Combobox1 in column B and Combobox2 in column A. And then only change the value of column AE in the same row as the combobox 2 value in Worksheet MFGLR.

Scenario 3: If Combobox 2 displays a different text/value currently in the worksheet MRFL Range(A1:A250) and combobox 1 displays a different text then in worksheet MFRL Range(B1:B250) then add the values of combobox1 and combobox2 at the next available row in worksheet MFRL, add combobox2 value at the next available row in Column A in the worksheet CT and add the combobox 2 value in the next available row in Column A of worksheet MFGLR Combobox1 in column B and Combobox2 in column A. And then only change the value of column AE in the same row as the combobox 2 value in Worksheet MFGLR.

For Scenarios 1 and 2, I'm having trouble having the code find the same row as combobox2 value and then pasting the textbox1 value 31 columns to the right as that. This is what I have so far.

With Worksheets("MFGLR").Range("a1:a500")
Set C = .Find(ComboBox2.Value, LookIn:=xlValues)
If Not C Is Nothing Then
firstAddress = C.Address
Do
    C.Value = TextBox1.Value
    Set C = .FindNext(C)
Loop While Not C Is Nothing
End If
End With

The scenarios don't seem to be holding true for all the cases

I would like the border of CT to go from the lastrow Column A to Column V

I would like the border of MFRL to go from lastrow Column A to Column E

I would like the border of MFRL to go from lastrow Column A to Column AM

Fill down from the last row in MFGLR column AF to column AH

This is my WIP for all the scenarios with borders and filldown.

Option Explicit
Private Sub CommandButton1_Click()

Dim ColA As New Scripting.Dictionary  'Need Microsoft Scripting Runtime Reference
Dim ColB As New Scripting.Dictionary
Dim LastRow As Long
Dim Criteria1 As Boolean
Dim Criteria2 As Boolean
Dim C As Range

With ThisWorkbook.Sheets("MFRL")
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'This gets the last row on column A
    For Each C In .Range("A1:A" & LastRow) 'loop through the whole column
    On Error Resume Next
        'If you have duplicated entries this will throw an error
        ColA.Add C.Value, C.Row 'add the values from column A to DictA, also store it's row for later purposes
        ColB.Add C.Offset(0, 1).Value, C.Row 'add the values from column B to DictB, also store it's row for later purposes
    Next C
    'Criterias will give value of True if matched or False if not
    Criteria1 = ColA.Exists(ComboBox2.Value) 'this is getting matched with ColA Dictionary
    Criteria2 = ColB.Exists(ComboBox1.Value) 'this is getting matched with ColB Dictionary
    If Criteria1 And Criteria2 Then 'SCENARIO 1
        .Cells(ColA(ComboBox2.Value), "AE:100") = TextBox1.Value
    ElseIf Criteria1 And Not Criteria2 Then 'SCENARIO 2
        .Cells(LastRow + 1, 1) = ComboBox2.Value
        .Cells(LastRow + 1, 2) = ComboBox1.Value
        .Cells(ColA(ComboBox2.Value), "AE") = TextBox1.Value
    With Worksheets("MFRL")
        .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).AutoFill .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2)
        .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2).Borders.LineStyle = xlContinuous
        End With
    ElseIf Not Criteria1 And Not Criteria2 Then 'SCENARIO 3
        .Cells(LastRow + 1, 1) = ComboBox2.Value
        .Cells(LastRow + 1, 2) = ComboBox1.Value
        'Add data to the column A next blank row in sheet CT
        LastRow = ThisWorkbook.Sheets("CT").Cells(ThisWorkbook.Sheets("CT").Rows.Count, 1).End(xlUp).Row + 1
        ThisWorkbook.Sheets("CT").Cells(LastRow, 1) = ComboBox2.Value
        ThisWorkbook.Sheets("CT").Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 21).AutoFill .Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 21).Resize(2)
        ThisWorkbook.Sheets("CT").Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 21).Resize(2).Borders.LineStyle = xlContinuous
        'Add data to the column A next blank row in sheet MFGLR
        LastRow = ThisWorkbook.Sheets("MFGL R").Cells(ThisWorkbook.Sheets("MFGLR").Rows.Count, 1).End(xlUp).Row + 1
        ThisWorkbook.Sheets("MFGLR").Cells(LastRow, 1) = ComboBox2.Value
        ThisWorkbook.Sheets("MFGLR").Cells(LastRow, "AE") = TextBox1.Value
        ThisWorkbook.Sheets("MFGLR").Cells(Rows.Count, "AE").End(xlUp).Offset(-1, 1).Resize(, 3).AutoFill .Cells(Rows.Count, "AE").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2)
        ThisWorkbook.Sheets("MFGLR").Cells(Rows.Count, "A").End(xlUp).Offset(-1, 1).Resize(, 38).Resize(2).Borders.LineStyle = xlContinuous
        ThisWorkbook.Sheets("MFRL").Cells(LastRow, 1) = ComboBox2.Value
        ThisWorkbook.Sheets("MFRL").Cells(LastRow, 2) = ComboBox1.Value
        ThisWorkbook.Sheets("MFRL").Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).AutoFill .Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2)
        ThisWorkbook.Sheets("MFRL").Cells(Rows.Count, "B").End(xlUp).Offset(-1, 1).Resize(, 3).Resize(2).Borders.LineStyle = xlContinuous
   End If
 End With
 ActiveWorkbook.RefreshAll
 Unload Me
 End Sub

Body:
If I understood all your scenarios ok this should do it, otherwise, please feel free to amend the code:

Option Explicit 'always get this, it forces you to declare all your variables
Sub Test()

    Dim ColA As New Scripting.Dictionary  'Need Microsoft Scripting Runtime Reference
    Dim ColB As New Scripting.Dictionary
    Dim LastRow As Long
    Dim Criteria1 As Boolean
    Dim Criteria2 As Boolean
    Dim C As Range

    With ThisWorkbook.Sheets("MFGLR")
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'This gets the last row on column A
        For Each C In .Range("A1:A" & LastRow) 'loop through the whole column
            'If you have duplicated entries this will throw an error
            ColA.Add C.Value, C.Row 'add the values from column A to DictA, also store it's row for later purposes
            ColB.Add C.Offset(0, 1).Value, C.Row 'add the values from column B to DictB, also store it's row for later purposes
        Next C
        'Criterias will give value of True if matched or False if not
        Criteria1 = ColA.Exists(Combobox2.Value) 'this is getting matched with ColA Dictionary
        Criteria2 = ColB.Exists(Combobox1.Value) 'this is getting matched with ColB Dictionary
        If Criteria1 And Criteria2 Then 'SCENARIO 1
            .Cells(ColA(Combobox2.Value), "AE") = Combobox2.Value
        ElseIf Criteria1 And Not Criteria2 Then 'SCENARIO 2
            .Cells(LastRow + 1, 1) = Combobox2.Value
            .Cells(LastRow + 1, 2) = Combobox1.Value
        ElseIf Not Criteria1 And Not Criteria2 Then 'SCENARIO 3
            .Cells(LastRow + 1, 1) = Combobox2.Value
            .Cells(LastRow + 1, 2) = Combobox1.Value
            'Add data to the column A next blank row in sheet CT
            LastRow = ThisWorkbook.Sheets("CT").Cells(ThisWorkbook.Sheets("CT").Rows.Count, 1).End(xlUp).Row + 1
            ThisWorkbook.Sheets("CT").Cells(LastRow, 1) = Combobox2.Value
            'Add data to the column A next blank row in sheet MFGLR
            LastRow = ThisWorkbook.Sheets("MFGLR ").Cells(ThisWorkbook.Sheets("MFGLR ").Rows.Count, 1).End(xlUp).Row + 1
            ThisWorkbook.Sheets("MFGLR").Cells(LastRow, 1) = Combobox2.Value
            ThisWorkbook.Sheets("MFGLR").Cells(LastRow, 2) = Combobox1.Value
            ThisWorkbook.Sheets("MFGLR").Cells(LastRow + 1, "AE") = Combobox2.Value
        End If
    End With

End Sub


问:
Map each tensor value to the closest value in a list
I have a tensor A with size [batchSize,2,2,2] where batchSize is a placeholder. In a custom layer, I would like to map each value of this tensor to the closest value in a list c with length n. The list is my codebook and I would like to quantize each value in the tensor based on this codebook; i.e. find the closest value to each tensor value in the list and replace the tensor value with that.
I could not figure out a 'clean' tensor operation that will quickly do that. I can not loop over the batchSize. Is there a method to do this in Tensorflow?

答:
If I understand correctly, this is doable with tf.HashTable. As an illustration, I used a normal distribution with mean=0, stddev=4.

```<code>a = tf.random.normal(
  shape = [batch, 2, 2, 2],
  mean=0.0,
  stddev=4
)
</code>```

And I used a quantization with only 5 buckets (see the figure marked with number 0, 1, 2, 3, 4). This is extensible to any length n. Note I intentionally made the buckets have variable length.

My codebook is therefore:

```<code>a <= -2          -> bucket 4
-2 < a < -0.5    -> bucket 3
-0.5 <= a < 0.5  -> bucket 0
0.5 <= a < 2.5   -> bucket 1
a >= 2.5         -> bucket 2
</code>```

The idea is to pre-create a key/value mapping from a scaled a to the bucket number. (the number of <key,value> pairs is dependent on the input granularity you need. Here I scaled by 10). Below is the code to initialize the mapping table and the produced mapping (input scaled by 10).

```<code># The boundary is chosen based on that we clip by min=-4, max=4.
# after scaling, the boundary becomes -40 and 40.
keys = range(-40, 41)
values  = []
for k in keys:
  if k <= -20:
    values.append(4)
  elif k < -5:
    values.append(3)
  elif k < 5:
    values.append(0)
  elif k < 25:
    values.append(1)
  else:
    values.append(2)
for (k, v) in zip(keys, values):
  print ("%2d -> %2d" % (k, v))

-40 ->  4
-39 ->  4
...
-22 ->  4
-21 ->  4
-20 ->  4
-19 ->  3
-18 ->  3
...
-7 ->  3
-6 ->  3
-5 ->  0
-4 ->  0
...
 3 ->  0
 4 ->  0
 5 ->  1
 6 ->  1
 ...
23 ->  1
24 ->  1
25 ->  2
26 ->  2
...
40 ->  2
</code>```

batch = 3
a = tf.random.normal(
    shape = [batch, 2, 2, 2],
    mean=0.0,
    stddev=4,
    dtype=tf.dtypes.float32
)
clip_a = tf.clip_by_value(a, clip_value_min=-4, clip_value_max=4)
SCALE = 10
scaled_clip_a = tf.cast(clip_a * SCALE, tf.int32)

table = tf.contrib.lookup.HashTable(
    tf.contrib.lookup.KeyValueTensorInitializer(keys, values), -1)
quantized_a = tf.reshape(
    table.lookup(tf.reshape(scaled_clip_a, [-1])),
    [batch, 2, 2, 2])

with tf.Session() as sess:
  table.init.run()
  a, clip_a, scaled_clip_a, quantized_a = sess.run([a, clip_a, scaled_clip_a, quantized_a])
  print ('a\n%s' % a)
  print ('clip_a\n%s' % clip_a)
  print ('scaled_clip_a\n%s' % scaled_clip_a)
  print ('quantized_a\n%s' % quantized_a)
```

<p>Result:</p>

```a
[[[[-0.26980758 -5.56331968]
   [ 5.04240322 -7.18292665]]

  [[-7.11545467 -3.24369478]
   [ 1.01861215 -0.04510783]]]

 [[[-0.28768024  0.2472897 ]
   [ 2.17780781 -5.79106379]]

  [[ 8.45582008  4.53902292]
   [ 0.138162   -6.19155598]]]

 [[[-7.5134449   4.56302166]
   [-0.30592337 -0.60313278]]

  [[-0.06204566  3.42917275]
   [-1.14547718  3.31167102]]]]
clip_a
[[[[-0.26980758 -4.        ]
   [ 4.         -4.        ]]

  [[-4.         -3.24369478]
   [ 1.01861215 -0.04510783]]]

 [[[-0.28768024  0.2472897 ]
   [ 2.17780781 -4.        ]]

  [[ 4.          4.        ]
   [ 0.138162   -4.        ]]]

 [[[-4.          4.        ]
   [-0.30592337 -0.60313278]]

  [[-0.06204566  3.42917275]
   [-1.14547718  3.31167102]]]]
scaled_clip_a
[[[[ -2 -40]
   [ 40 -40]]

  [[-40 -32]
   [ 10   0]]]

 [[[ -2   2]
   [ 21 -40]]

  [[ 40  40]
   [  1 -40]]]

 [[[-40  40]
   [ -3  -6]]

  [[  0  34]
   [-11  33]]]]
quantized_a
[[[[0 4]
   [2 4]]

  [[4 4]
   [1 0]]]

 [[[0 0]
   [1 4]]

  [[2 2]
   [0 4]]]

 [[[4 2]
   [0 3]]

  [[0 2]
   [3 2]]]]
```

Body:
If I understand correctly, this is doable with tf.HashTable. As an illustration, I used a normal distribution with mean=0, stddev=4.

a = tf.random.normal(
  shape = [batch, 2, 2, 2],
  mean=0.0,
  stddev=4
)

And I used a quantization with only 5 buckets (see the figure marked with number 0, 1, 2, 3, 4). This is extensible to any length n. Note I intentionally made the buckets have variable length.

My codebook is therefore:

a <= -2          -> bucket 4
-2 < a < -0.5    -> bucket 3
-0.5 <= a < 0.5  -> bucket 0
0.5 <= a < 2.5   -> bucket 1
a >= 2.5         -> bucket 2

The idea is to pre-create a key/value mapping from a scaled a to the bucket number. (the number of <key,value> pairs is dependent on the input granularity you need. Here I scaled by 10). Below is the code to initialize the mapping table and the produced mapping (input scaled by 10).

# The boundary is chosen based on that we clip by min=-4, max=4.
# after scaling, the boundary becomes -40 and 40.
keys = range(-40, 41)
values  = []
for k in keys:
  if k <= -20:
    values.append(4)
  elif k < -5:
    values.append(3)
  elif k < 5:
    values.append(0)
  elif k < 25:
    values.append(1)
  else:
    values.append(2)
for (k, v) in zip(keys, values):
  print ("%2d -> %2d" % (k, v))

-40 ->  4
-39 ->  4
...
-22 ->  4
-21 ->  4
-20 ->  4
-19 ->  3
-18 ->  3
...
-7 ->  3
-6 ->  3
-5 ->  0
-4 ->  0
...
 3 ->  0
 4 ->  0
 5 ->  1
 6 ->  1
 ...
23 ->  1
24 ->  1
25 ->  2
26 ->  2
...
40 ->  2

batch = 3
a = tf.random.normal(
    shape = [batch, 2, 2, 2],
    mean=0.0,
    stddev=4,
    dtype=tf.dtypes.float32
)
clip_a = tf.clip_by_value(a, clip_value_min=-4, clip_value_max=4)
SCALE = 10
scaled_clip_a = tf.cast(clip_a * SCALE, tf.int32)

table = tf.contrib.lookup.HashTable(
    tf.contrib.lookup.KeyValueTensorInitializer(keys, values), -1)
quantized_a = tf.reshape(
    table.lookup(tf.reshape(scaled_clip_a, [-1])),
    [batch, 2, 2, 2])

with tf.Session() as sess:
  table.init.run()
  a, clip_a, scaled_clip_a, quantized_a = sess.run([a, clip_a, scaled_clip_a, quantized_a])
  print ('a\n%s' % a)
  print ('clip_a\n%s' % clip_a)
  print ('scaled_clip_a\n%s' % scaled_clip_a)
  print ('quantized_a\n%s' % quantized_a)

Result:

a
[[[[-0.26980758 -5.56331968]
   [ 5.04240322 -7.18292665]]

  [[-7.11545467 -3.24369478]
   [ 1.01861215 -0.04510783]]]

 [[[-0.28768024  0.2472897 ]
   [ 2.17780781 -5.79106379]]

  [[ 8.45582008  4.53902292]
   [ 0.138162   -6.19155598]]]

 [[[-7.5134449   4.56302166]
   [-0.30592337 -0.60313278]]

  [[-0.06204566  3.42917275]
   [-1.14547718  3.31167102]]]]
clip_a
[[[[-0.26980758 -4.        ]
   [ 4.         -4.        ]]

  [[-4.         -3.24369478]
   [ 1.01861215 -0.04510783]]]

 [[[-0.28768024  0.2472897 ]
   [ 2.17780781 -4.        ]]

  [[ 4.          4.        ]
   [ 0.138162   -4.        ]]]

 [[[-4.          4.        ]
   [-0.30592337 -0.60313278]]

  [[-0.06204566  3.42917275]
   [-1.14547718  3.31167102]]]]
scaled_clip_a
[[[[ -2 -40]
   [ 40 -40]]

  [[-40 -32]
   [ 10   0]]]

 [[[ -2   2]
   [ 21 -40]]

  [[ 40  40]
   [  1 -40]]]

 [[[-40  40]
   [ -3  -6]]

  [[  0  34]
   [-11  33]]]]
quantized_a
[[[[0 4]
   [2 4]]

  [[4 4]
   [1 0]]]

 [[[0 0]
   [1 4]]

  [[2 2]
   [0 4]]]

 [[[4 2]
   [0 3]]

  [[0 2]
   [3 2]]]]


问:
How do I access my API if it is at a different "route"?
Let's say my current page is at the location:
http://myserver/client/index.html

And my API is at the url:
http://myserver/api/getMyData

How can I access the API without hardcoding it like this:

```<code>fetch('http://myserver/api/getMyData')
</code>```

and instead like this:

```<code>fetch('../api/getMyData')
</code>```

?

Thanks

答:
You can use a forward slash to indicate that the url path is relative to the domain root.

Regardless of current page location, fetch('/api/getMyData') will translate to http://myserver/api/getMyData

Body:
Let's say my current page is at the location:
http://myserver/client/index.html

And my API is at the url:
http://myserver/api/getMyData

How can I access the API without hardcoding it like this:

fetch('http://myserver/api/getMyData')

and instead like this:

fetch('../api/getMyData')

?

Thanks


问:
ASP.NET Core session objects with binary serialization
I have a use case to store the huge object in session, which has bunch of private variables (so can't use Json serialization), is there a way to accomplish it ?
does binary serialization work by chance with ISession ?

(i understand its not best practice to store this kind of object in session)

答: ISession has Set and TryGetValue methods that both work with byte[] to set and get binary values, respectively. You'll to take care of serializing to binary yourself; ISession won't handle that for you, but once you have the byte[], you can set it in the session.


问:
avoid sorting in X axis in matplotlib and plot common X axis with multiple y axis
I wish to clarify two queries in this post.

I have a pandas df like below picture.

1. Plotting problem : .
When i try to plot column 0 with column 1, the values gets sorted.

example : in col_0 I have values starting from 112 till 0.
the values gets sorted in ascending order and the graph shows reversed X axis plot when i use the below code.

```<code>plt.plot(df.col_0, df.col_1)
</code>```

What will be best way to avoid sorting X axis values. ?

2. All paramaters in single graph
I would like to plot all the params in a single plot. Except X axis all other params values are between 0 to 1 (same scale)
What will be best pythonic way of doing.
Any help would be appreciated.

答:
Try to draw the series/dataframe against the index:

```<code>col_to_draw = [col for col in df.columns if col!='col0']

# if your data frame is indexed as 0,1,2,... ignore this step
tmp_df = df.reset_index()

ax = tmp_df[col_to_draw].plot(figsize=(10,6))
xtick_vals = ax.get_xticks()
ax.set_xticklabels(tmp_df.col0[xtick_vals].tolist())
</code>```

Output:

Body:
I wish to clarify two queries in this post.

I have a pandas df like below picture.

1. Plotting problem : .
When i try to plot column 0 with column 1, the values gets sorted.

example : in col_0 I have values starting from 112 till 0.
the values gets sorted in ascending order and the graph shows reversed X axis plot when i use the below code.

plt.plot(df.col_0, df.col_1)

What will be best way to avoid sorting X axis values. ?

2. All paramaters in single graph
I would like to plot all the params in a single plot. Except X axis all other params values are between 0 to 1 (same scale)
What will be best pythonic way of doing.
Any help would be appreciated.

Body:
Try to draw the series/dataframe against the index:

col_to_draw = [col for col in df.columns if col!='col0']

# if your data frame is indexed as 0,1,2,... ignore this step
tmp_df = df.reset_index()

ax = tmp_df[col_to_draw].plot(figsize=(10,6))
xtick_vals = ax.get_xticks()
ax.set_xticklabels(tmp_df.col0[xtick_vals].tolist())

Output:


问:
Show results of joined tables even if some values don't match
Access Database

```<code>table contacts
--------------
id
surname
name

table relations
---------------
contact_id
relation_id
</code>```

Both contact_id and relation_id are foreign keys referenced to table contacts' id

I want to execute a query to get both the contact's surname/name and the relation's surname/name if a relation for the current contact exist. If it doesn't exist I want to get the contact's surname/name and blank values for the relation's fields.

All this in one query

EDIT:

I used left join. I am running the query using VB.NET:

```<code>Dim myOleDbDataReader As OleDbDataReader = _
    New OleDbCommand( _
    "SELECT c.id           AS contact_id " & _
    "     , c.surname      AS contact_surname " & _
    "     , c.name         AS contact_name " & _
    "     , c2.id          AS related_id " & _
    "     , c2.surname     AS related_surname " & _
    "     , c2.name        AS related_name " & _
    "FROM ((contacts c " & _
    "LEFT JOIN relations r " & _
    "ON c.id = r.contact_id) " & _
    "INNER JOIN contacts c2 " & _
    "ON c2.id = r.relation_id)" _
    , connection).ExecuteReader()
</code>```

I get OleDbException: Join expression not supported.

They say in another post that:
"Access won't let you use conventional joins in the where clause when you use LEFT/RIGHT/INNER JOINS in the FROM clause. It is probably intentional to get you to buy more expensive software." - ( Is the join expression not supported by MS Access? )

It is not exactly that. From some examples I tried I came to the conclusion that:

Access won't let you use outer joins (LEFT/RIGHT) together with one or more INNER JOINS.
What in John Carmack's name can I do?
I would like to avoid seperate select queries.
Please help...

答:
```<code>SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , c2.id      AS related_id
     , c2.surname AS related_surname
     , c2.name    AS related_name
FROM contacts c
  LEFT JOIN relations r
    ON c.id = r.contact_id
  JOIN contacts c2
    ON r.relation_id = c2.id
</code>```

The above does NOT work in MS-Access.

This is slightly different (two left joins) but it works:

```<code>SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , c2.id      AS related_id
     , c2.surname AS related_surname
     , c2.name    AS related_name
FROM contacts c
  LEFT JOIN
    ( relations r
      LEFT  JOIN contacts AS c2
        ON r.relation_id = c2.id
    )
    ON c.id = r.contact_id
</code>```

Despite the second LEFT JOIN, it will give same result set, since the second LEFT JOIN involves a Foreign Key relationship (in the direction from many -> one).

To have a LEFT JOIN with an INNER JOIN you could use:

```<code>SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , g.id       AS related_id
     , g.surname  AS related_surname
     , g.name     AS related_name
FROM contacts c
  LEFT JOIN
    ( SELECT r.contact_id
           , c2.id
           , c2.surname
           , c2.name
      FROM relations r
        INNER JOIN contacts AS c2
          ON r.relation_id = c2.id
    )  AS g
    ON c.id = g.contact_id
</code>```

Body:
Access Database

table contacts
--------------
id
surname
name

table relations
---------------
contact_id
relation_id

Both contact_id and relation_id are foreign keys referenced to table contacts' id

I want to execute a query to get both the contact's surname/name and the relation's surname/name if a relation for the current contact exist. If it doesn't exist I want to get the contact's surname/name and blank values for the relation's fields.

All this in one query

EDIT:

I used left join. I am running the query using VB.NET:

Dim myOleDbDataReader As OleDbDataReader = _
    New OleDbCommand( _
    "SELECT c.id           AS contact_id " & _
    "     , c.surname      AS contact_surname " & _
    "     , c.name         AS contact_name " & _
    "     , c2.id          AS related_id " & _
    "     , c2.surname     AS related_surname " & _
    "     , c2.name        AS related_name " & _
    "FROM ((contacts c " & _
    "LEFT JOIN relations r " & _
    "ON c.id = r.contact_id) " & _
    "INNER JOIN contacts c2 " & _
    "ON c2.id = r.relation_id)" _
    , connection).ExecuteReader()

I get OleDbException: Join expression not supported.

They say in another post that:
"Access won't let you use conventional joins in the where clause when you use LEFT/RIGHT/INNER JOINS in the FROM clause. It is probably intentional to get you to buy more expensive software." - ( Is the join expression not supported by MS Access? )

It is not exactly that. From some examples I tried I came to the conclusion that:

Access won't let you use outer joins (LEFT/RIGHT) together with one or more INNER JOINS.
What in John Carmack's name can I do?
I would like to avoid seperate select queries.
Please help...

Body:
SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , c2.id      AS related_id
     , c2.surname AS related_surname
     , c2.name    AS related_name
FROM contacts c
  LEFT JOIN relations r
    ON c.id = r.contact_id
  JOIN contacts c2
    ON r.relation_id = c2.id

The above does NOT work in MS-Access.

This is slightly different (two left joins) but it works:

SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , c2.id      AS related_id
     , c2.surname AS related_surname
     , c2.name    AS related_name
FROM contacts c
  LEFT JOIN
    ( relations r
      LEFT  JOIN contacts AS c2
        ON r.relation_id = c2.id
    )
    ON c.id = r.contact_id

Despite the second LEFT JOIN, it will give same result set, since the second LEFT JOIN involves a Foreign Key relationship (in the direction from many -> one).

To have a LEFT JOIN with an INNER JOIN you could use:

SELECT c.id       AS contact_id
     , c.surname  AS contact_surname
     , c.name     AS contact_name
     , g.id       AS related_id
     , g.surname  AS related_surname
     , g.name     AS related_name
FROM contacts c
  LEFT JOIN
    ( SELECT r.contact_id
           , c2.id
           , c2.surname
           , c2.name
      FROM relations r
        INNER JOIN contacts AS c2
          ON r.relation_id = c2.id
    )  AS g
    ON c.id = g.contact_id


问:
Thymeleaf: pass a parameter from the get form action in the url
I have a parameter in my controller and I want to get it back in the URL in a get form

I want to search in a list the objects by the agency but the problem is that thymeleaf gives me a fake URL, here is the example

here I will search with the keyword agency

```<code><form th:action="@{lien(key=${key})}" method="get">
<input type="text" name="agence" th:value="${agence}" class="form-control"
                     placeholder=" Agence client..." />
</code>```

and this is clientController :

```<code>@RequestMapping(value = "/lien")
public String droitUtilisateur(Model model,
        @RequestParam(name = "key", defaultValue = "0") int key,
        @RequestParam(name = "page", defaultValue = "0") int p,
        @RequestParam(name = "size", defaultValue = "5") int s,
        @RequestParam(name = "agence", defaultValue = "") String agence) {
    String result = "";
    switch(key) {
    case 24421:
        Page<Client> pageClients = clientRepository.chercherParNom("%" + agence + "%", new PageRequest(p, s));
        model.addAttribute("listClient",pageClients.getContent()) ;
        int[] pages = new int[pageClients.getTotalPages()];
        model.addAttribute("pages", pages);
        model.addAttribute("pageCourante", p);
        model.addAttribute("size", s);
        model.addAttribute("key", key);
        model.addAttribute("agence", agence);
        result= key+"";
        break;

    }

    return result;
}
</code>```

which returns this link :

```<code>http://localhost:6262/lien?agence=100
</code>```

with this error

Template name cannot be null or empty

but it should be like this

```<code>http://localhost:6262/lien?key=24421&agence=100
</code>```

答:
You can't mix parameters in the url with parameters in form fields.  You should add a hidden input for key:

```<code><form th:action="@{lien}" method="get">
    <input type="hidden" name="key" th:value="${key}" />
    <input type="text" name="agence" th:value="${agence}" class="form-control" placeholder=" Agence client..." />
</code>```

Body:
I have a parameter in my controller and I want to get it back in the URL in a get form

I want to search in a list the objects by the agency but the problem is that thymeleaf gives me a fake URL, here is the example

here I will search with the keyword agency

<form th:action="@{lien(key=${key})}" method="get">
<input type="text" name="agence" th:value="${agence}" class="form-control"
                     placeholder=" Agence client..." />

and this is clientController :

@RequestMapping(value = "/lien")
public String droitUtilisateur(Model model,
        @RequestParam(name = "key", defaultValue = "0") int key,
        @RequestParam(name = "page", defaultValue = "0") int p,
        @RequestParam(name = "size", defaultValue = "5") int s,
        @RequestParam(name = "agence", defaultValue = "") String agence) {
    String result = "";
    switch(key) {
    case 24421:
        Page<Client> pageClients = clientRepository.chercherParNom("%" + agence + "%", new PageRequest(p, s));
        model.addAttribute("listClient",pageClients.getContent()) ;
        int[] pages = new int[pageClients.getTotalPages()];
        model.addAttribute("pages", pages);
        model.addAttribute("pageCourante", p);
        model.addAttribute("size", s);
        model.addAttribute("key", key);
        model.addAttribute("agence", agence);
        result= key+"";
        break;

    }

    return result;
}

which returns this link :

http://localhost:6262/lien?agence=100

with this error

Template name cannot be null or empty

but it should be like this

http://localhost:6262/lien?key=24421&agence=100

Body:
You can't mix parameters in the url with parameters in form fields.  You should add a hidden input for key:

<form th:action="@{lien}" method="get">
    <input type="hidden" name="key" th:value="${key}" />
    <input type="text" name="agence" th:value="${agence}" class="form-control" placeholder=" Agence client..." />


问:
Issues to space
 elements with pourcentage
I can't space these li elements of my footer with pourcentage on padding left... Otherwise, the inline-block I used don't work anymore...

I already tried to use % but then it stops to be inline...

Can you help me ?

footer {
  position: fixed;
  bottom: 0px;
  left: 0;
  height: 65px;
  width: 100%;
  margin: auto;
  z-index: 99;
}

.footer ul {
  position: absolute;
  display: block;
  text-align: right;
  list-style-type: none;
  bottom: 15px;
  right: 5%;
}

.footer li {
  display: inline-block;
  position: relative;
  padding-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="footer">

    <ul>
      <li>
        <div id="humidity">15%</div>
      </li>
      <li>
        <div id="temp">15°C</div>
      </li>
      <li>
        <div id="clock">15h15m15s</div>
      </li>
      <li>
        <div id="date" class="date">15.15.15</div>
      </li>
    </ul>

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1670 97" preserveAspectRatio="none">
<g>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
</g>
</svg>

  </div>
</footer></code>```

答:
You must set width: 100%; on ul element.

I created a pen for what you want to achieve:

codepen

Title: Issues to space <li> elements with pourcentage

Body:
I can't space these li elements of my footer with pourcentage on padding left... Otherwise, the inline-block I used don't work anymore...

I already tried to use % but then it stops to be inline...

Can you help me ?

footer {
  position: fixed;
  bottom: 0px;
  left: 0;
  height: 65px;
  width: 100%;
  margin: auto;
  z-index: 99;
}

.footer ul {
  position: absolute;
  display: block;
  text-align: right;
  list-style-type: none;
  bottom: 15px;
  right: 5%;
}

.footer li {
  display: inline-block;
  position: relative;
  padding-left: 50px;
}

15%

15°C

15h15m15s

15.15.15

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1670 97" preserveAspectRatio="none">
<g>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
 <path fill="#FE4A11" d="M1669,52.659V97H847.357H0V52.659l122.675-16.814l142.712,3.871c0,0,231.45-27.464,236.787-27.78
  c5.336-0.316,272.148,27.132,272.148,27.132l198.221-14.81l360.398,14.679l231.414-15.818L1669,52.659z"/>
</g>
</svg>


问:
Routing error after implementing bootstrap
Creating a "Hack this site" as a fun project, but stumbled upon a routing error after adding the bootstrap gem, along with jquery.

app/assets/stylesheets/Application.scss

```<code>@import "bootstrap";
</code>```

app/assets/javascripts/Application.js

//= require jquery3
//= require popper
//= require bootstrap-sprockets
```

<p>Gem file</p>

<pre class="lang-rb prettyprint-override"><code>gem 'rails', '~> 5.2.3'
gem 'devise'
gem 'bootstrap', '~> 4.3.1'
gem 'jquery-rails'
</code>```

routes.rb

Rails.application.routes.draw do

  resources :pages, path: "", only: [] do
    collection do
      get :stage1
      get :stage2
      end
      end
  get 'resources/Videos'
  get 'resources/Photos'
  get 'layouts/home'
  root '_layouts#home'
  get "/pages/:page" => "pages#show"
  resources :posts
  devise_for :users
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

```

<p>Followed the Bootstrap-rubygem repository installation instructions, and ended up getting the following errors when trying to load the page.</p>

```ActionController::RoutingError (No route matches [GET] "/vendor/bootstrap/js/bootstrap.bundle.min.js"):
ActionController::RoutingError (No route matches [GET] "/vendor/jquery/jquery.min.js"):

```

Got no clue as to what i have done wrong (Probably a lot of things), so i'd appreciate any answers that could lead to resolving this issue!

答:
Found a solution that worked for me (for now atleast).

Aparantly the application.scss had a subfile named application.css under it (using Jetbrains RubyMine).

Deleted the file application.css containing

@import Bootstrap
```

And now its atleast loading the page properly with the bootstrap css, although the error messages are showing in the server terminal.

Will try to iron out the error messages and post it here if i find a solution to them.

Body:
Creating a "Hack this site" as a fun project, but stumbled upon a routing error after adding the bootstrap gem, along with jquery.

app/assets/stylesheets/Application.scss

@import "bootstrap";

app/assets/javascripts/Application.js

//= require jquery3
//= require popper
//= require bootstrap-sprockets

Gem file

gem 'rails', '~> 5.2.3'
gem 'devise'
gem 'bootstrap', '~> 4.3.1'
gem 'jquery-rails'

routes.rb

Rails.application.routes.draw do

  resources :pages, path: "", only: [] do
    collection do
      get :stage1
      get :stage2
      end
      end
  get 'resources/Videos'
  get 'resources/Photos'
  get 'layouts/home'
  root '_layouts#home'
  get "/pages/:page" => "pages#show"
  resources :posts
  devise_for :users
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

Followed the Bootstrap-rubygem repository installation instructions, and ended up getting the following errors when trying to load the page.

ActionController::RoutingError (No route matches [GET] "/vendor/bootstrap/js/bootstrap.bundle.min.js"):
ActionController::RoutingError (No route matches [GET] "/vendor/jquery/jquery.min.js"):

Got no clue as to what i have done wrong (Probably a lot of things), so i'd appreciate any answers that could lead to resolving this issue!

Body:
Found a solution that worked for me (for now atleast).

Aparantly the application.scss had a subfile named application.css under it (using Jetbrains RubyMine).

Deleted the file application.css containing

@import Bootstrap

And now its atleast loading the page properly with the bootstrap css, although the error messages are showing in the server terminal.

Will try to iron out the error messages and post it here if i find a solution to them.


问:
Changing year only in date in column with case statement
I have a table with end dates in different years and would like to change any year ending in '2004' to '4712'. The column is Date type and I keep getting an error

I have tried different codes and case statements but none of which worked

```<code>select
    case
        when h.EndDate like '2004%' then '4712%'
        else h.EndDate
    end as EndDate
from table h

1/31/2004
2/28/2004
3/31/2004
</code>```

and so on would be the only years changed to:

```<code>1/31/4712
2/28/4712
3/31/4712
</code>```

答:
You can do this using dateadd(). Like works with string data type like varchar, nvarchar etc. When working with dates you need to use functions prepared to works with this data types (date, datetime etc.) To your date I added 2708 year which added to 4712.

```<code>update table
set EndDate = dateadd(year, 2708, EndDate)
where year(EndDate) = 2004
</code>```

Body:
I have a table with end dates in different years and would like to change any year ending in '2004' to '4712'. The column is Date type and I keep getting an error

I have tried different codes and case statements but none of which worked

select
    case
        when h.EndDate like '2004%' then '4712%'
        else h.EndDate
    end as EndDate
from table h

1/31/2004
2/28/2004
3/31/2004

and so on would be the only years changed to:

1/31/4712
2/28/4712
3/31/4712

Body:
You can do this using dateadd(). Like works with string data type like varchar, nvarchar etc. When working with dates you need to use functions prepared to works with this data types (date, datetime etc.) To your date I added 2708 year which added to 4712.

update table
set EndDate = dateadd(year, 2708, EndDate)
where year(EndDate) = 2004


问:
Regex giving incorrect results
Working in Javascript attempting to use a regular expression to capture data in a string.

My string appears as this starting with the left bracket

```<code>['ABC']['ABC.5']['ABC.5.1']
</code>```

My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.

```<code>var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
</code>```

The output I see is only the [ for each element.

I would like the array to be like this for example

```<code>myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
</code>```

What is the correct regular expression and or function to get the above-desired output?

答:
You can use this regex with split:

```<code>\[[^\]]+
</code>```

Details

\[ - Matches [

[^\]]+ - Matches anything except ] one or more time

\] - Matches ]

let str =  `['ABC']['ABC.5']['ABC.5.1']`

let op = str.split(/(\[[^\]]+\])/).filter(Boolean)

console.log(op)```

Title: Regex giving incorrect results

Body:
Working in Javascript attempting to use a regular expression to capture data in a string.

My string appears as this starting with the left bracket

['ABC']['ABC.5']['ABC.5.1']

My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.

var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);

The output I see is only the [ for each element.

I would like the array to be like this for example

myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']

What is the correct regular expression and or function to get the above-desired output?

Body:
You can use this regex with split:

\[[^\]]+

Details

\[ - Matches [

[^\]]+ - Matches anything except ] one or more time

\] - Matches ]

let str =  `['ABC']['ABC.5']['ABC.5.1']`

let op = str.split(/(\[[^\]]+\])/).filter(Boolean)

console.log(op)


问:
How should I use DispatchGroup for two url requests?
I am using DispatchGroup for two url requests but didn't get any data. I tried each method separately without DispatchGroup, it works fine. So the problem is that I didn't use DispatchGroup correctly. Please help.</p>

```<code>    let buildingManager =  BuildingManager()
    let anaManager = AnalyticsManager()
    let group = DispatchGroup()
    let queue = DispatchQueue.global(qos: .background)

    queue.async(group: group) {
        buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
            guard let self = self else {return}

            if success {
                self.buildings = buildings
                print("success")
            } else {
                print("No building infos")
            }
        })
    }

    queue.async(group: group) {
        anaManager.getAnaData(completion: {[weak self] (anaData, success) in
            guard let self = self else {return}

            if success {
                self.analyticsData = anaData
                print("success")
            } else {
                print("No analytics data")
            }
        })
    }

        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.dataTableView.reloadData()
        }
</code>```

答:
In the past, I had same problem that you, and I learned a bit more of parallel process in Swift.
I can be wrong, but in your place I would use the OperationQueue. You can try do this:

```<code>let queue = OperationQueue()

queue.addOperation {
 buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
            guard let self = self else {return}

            if success {
                self.buildings = buildings
                print("success")
            } else {
                print("No building infos")
            }

            DispatchQueue.main.async {
                self?.dataTableView.reloadData()
            }
        })
}

queue.addOperation {
 anaManager.getAnaData(completion: {[weak self] (anaData, success) in
            guard let self = self else {return}

            if success {
                self.analyticsData = anaData
                print("success")
            } else {
                print("No analytics data")
            }

                DispatchQueue.main.async {
                    self?.dataTableView.reloadData()
                }
        })
}
</code>```

This is more a opinion than answer.

Ref.: https://www.raywenderlich.com/5293-operation-and-operationqueue-tutorial-in-swift

Body:
I am using DispatchGroup for two url requests but didn't get any data. I tried each method separately without DispatchGroup, it works fine. So the problem is that I didn't use DispatchGroup correctly. Please help.

    let buildingManager =  BuildingManager()
    let anaManager = AnalyticsManager()
    let group = DispatchGroup()
    let queue = DispatchQueue.global(qos: .background)

    queue.async(group: group) {
        buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
            guard let self = self else {return}

            if success {
                self.buildings = buildings
                print("success")
            } else {
                print("No building infos")
            }
        })
    }

    queue.async(group: group) {
        anaManager.getAnaData(completion: {[weak self] (anaData, success) in
            guard let self = self else {return}

            if success {
                self.analyticsData = anaData
                print("success")
            } else {
                print("No analytics data")
            }
        })
    }

        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.dataTableView.reloadData()
        }

Body:
In the past, I had same problem that you, and I learned a bit more of parallel process in Swift.
I can be wrong, but in your place I would use the OperationQueue. You can try do this:

let queue = OperationQueue()

queue.addOperation {
 buildingManager.getBuildingInfos(completion: { [weak self] (buildings, success) in
            guard let self = self else {return}

            if success {
                self.buildings = buildings
                print("success")
            } else {
                print("No building infos")
            }

            DispatchQueue.main.async {
                self?.dataTableView.reloadData()
            }
        })
}

queue.addOperation {
 anaManager.getAnaData(completion: {[weak self] (anaData, success) in
            guard let self = self else {return}

            if success {
                self.analyticsData = anaData
                print("success")
            } else {
                print("No analytics data")
            }

                DispatchQueue.main.async {
                    self?.dataTableView.reloadData()
                }
        })
}

This is more a opinion than answer.

Ref.: https://www.raywenderlich.com/5293-operation-and-operationqueue-tutorial-in-swift


问:
How to group matched elements to process both at once?
I'm working on a school project and we have to use XML and XSLT to generate our HTML. My project is a family tree. I achieved to select the root persons, but now I want group married persons and process them both at once and not every one on its own.

At the moment I select every root person and then search for the married person and display them together. But as every one is processed on its own I get all results two times.

My Data looks like this:

```<code><persons>
    <person id="1" marriedTo="2" father="0" mother="0">
        <name>Father</name>
    </person>
    <person id="2" marriedTo="1" father="0" mother="0">
        <name>Mother</name>
    </person>
    ....
</persons>
</code>```

My xslt code:

```<code><xsl:template match="/persons/person[@father='0' and @mother='0']">
    <div class="person">
         <xsl:value-of select="name"/>
    </div>
    <div class="person">
         <xsl:value-of select="key('couple',@marriedTo)/name"/>
    </div>
</xsl:template>
</code>```

Is there any way to get two elements and process them together? Maybe like

```<code><div>
    <xsl:value-of select="person[0]/name"/>
</div>
<div>
    <xsl:value-of select="person[1]/name"/>
</div>
</code>```

答:
If you don't mind whether you select the father or mother first, change your existing template to match only the person record where the marriedTo is greater than their id. And have a second template that matches the opposite that then ignores that person.

```<code><xsl:template match="/persons/person[@father='0' and @mother='0'][@marriedTo > @id]">
    <div class="person">
         <xsl:value-of select="name"/>
    </div>
    <div class="person">
         <xsl:value-of select="key('couple',@marriedTo)/name"/>
    </div>
</xsl:template>

<xsl:template match="/persons/person[@father='0' and @mother='0'][@marriedTo < @id]" />
</code>```

Of course, you might need extra templates if one person in the couple does have a father or mother, but it should give you the general idea.

Body:
I'm working on a school project and we have to use XML and XSLT to generate our HTML. My project is a family tree. I achieved to select the root persons, but now I want group married persons and process them both at once and not every one on its own.

At the moment I select every root person and then search for the married person and display them together. But as every one is processed on its own I get all results two times.

My Data looks like this:

<persons>
    <person id="1" marriedTo="2" father="0" mother="0">
        <name>Father</name>
    </person>
    <person id="2" marriedTo="1" father="0" mother="0">
        <name>Mother</name>
    </person>
    ....
</persons>

My xslt code:

<xsl:template match="/persons/person[@father='0' and @mother='0']">

         <xsl:value-of select="name"/>

         <xsl:value-of select="key('couple',@marriedTo)/name"/>

</xsl:template>

Is there any way to get two elements and process them together? Maybe like

    <xsl:value-of select="person[0]/name"/>

    <xsl:value-of select="person[1]/name"/>

Body:
If you don't mind whether you select the father or mother first, change your existing template to match only the person record where the marriedTo is greater than their id. And have a second template that matches the opposite that then ignores that person.

<xsl:template match="/persons/person[@father='0' and @mother='0'][@marriedTo &gt; @id]">
    <div class="person">
         <xsl:value-of select="name"/>
    </div>
    <div class="person">
         <xsl:value-of select="key('couple',@marriedTo)/name"/>
    </div>
</xsl:template>

<xsl:template match="/persons/person[@father='0' and @mother='0'][@marriedTo &lt; @id]" />

Of course, you might need extra templates if one person in the couple does have a father or mother, but it should give you the general idea.