问:
Vanilla JavaScript getAttribute("href") from link with image inside
I am trying to create tabs with vanilla JavaScript, each tab has an icon and a title inside the link

```<code><div class="tabs-bar-item">
  <a href="#tab3">
    <img class="icon" src="img/school.png">
    <h3 class="title">Instruktāžas datu aizsardzībā</h3>
  </a>
</div>
</code>```

It should open the tab content

```<code><div id="tab3" class="tabs-content-item">
</code>```

The problem is that .getAttribute("href"); returns null when I have  and
 elements inside the link.
Everything works if I change the tab to

```<code><div class="tabs-bar-item">
    <img class="icon" src="img/school.png">
    <a href="#tab3">Instruktāžas datu aizsardzībā</a>
</div>
</code>```

but I want the tab content to open when clicked anywhere on .tabs-bar-item. How can it be done in vanilla JavaScript?

Full JS code:

```<code>let tabs = document.querySelectorAll('.tabs-bar .tabs-bar-item');

    function tabClicks(tabClickEvent) {
        for (let i = 0; i < tabs.length; i++) {
            tabs[i].classList.remove("active");
        }

        let clickedTab = tabClickEvent.currentTarget;

        clickedTab.classList.add("active");
        tabClickEvent.preventDefault();

        let contentPanes = document.querySelectorAll('.tabs-content-item');

        for (i = 0; i < contentPanes.length; i++) {
            contentPanes[i].classList.remove("active");
        }

        let anchorReference = tabClickEvent.target;
        let activePaneId = anchorReference.getAttribute("href");
        let activePane = document.querySelector(activePaneId);

        activePane.classList.add("active");
    }

    for (i = 0; i < tabs.length; i++) {
        tabs[i].addEventListener("click", tabClicks)
    }
</code>```

Css for tab content:

```<code>.tabs-content .tabs-content-item {
    display: none;
}
.tabs-content .tabs-content-item.active {
    display: block;
}
</code>```

答:
Element.closest searchs up the DOM to find an element matching the selector passed as argument. If Element already matches the selector, Element (the node on which closest is called) is returned.

Hence try changing

```<code> let anchorReference = tabClickEvent.target;
</code>```

to

```<code> let anchorReference = tabClickEvent.target.closest('a');
</code>```

as for example in

let tabs = document.querySelectorAll('.tabs-bar .tabs-bar-item');

function tabClicks(tabClickEvent) {
    for (let i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove("active");
    }

    let clickedTab = tabClickEvent.currentTarget;

    clickedTab.classList.add("active");
    tabClickEvent.preventDefault();

    let contentPanes = document.querySelectorAll('.tabs-content-item');

    for (i = 0; i < contentPanes.length; i++) {
        contentPanes[i].classList.remove("active");
    }

    let anchorReference = tabClickEvent.target.closest('a');
    console.log( anchorReference);
    let activePaneId = anchorReference.getAttribute("href");
    let activePane = document.querySelector(activePaneId);

    activePane.classList.add("active");
}

for (i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", tabClicks)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabs-content .tabs-content-item {
    display: none;
}
.tabs-content .tabs-content-item.active {
    display: block;
}</code>```

Instruktāžas datu aizsardzībā

     content of tab3 with self contained link: here. Clicking "here" should not close the tab!

  ```

Body:
I am trying to create tabs with vanilla JavaScript, each tab has an icon and a title inside the link

Instruktāžas datu aizsardzībā

It should open the tab content

The problem is that .getAttribute("href"); returns null when I have  and
 elements inside the link.
Everything works if I change the tab to

    Instruktāžas datu aizsardzībā

but I want the tab content to open when clicked anywhere on .tabs-bar-item. How can it be done in vanilla JavaScript?

Full JS code:

let tabs = document.querySelectorAll('.tabs-bar .tabs-bar-item');

    function tabClicks(tabClickEvent) {
        for (let i = 0; i < tabs.length; i++) {
            tabs[i].classList.remove("active");
        }

        let clickedTab = tabClickEvent.currentTarget;

        clickedTab.classList.add("active");
        tabClickEvent.preventDefault();

        let contentPanes = document.querySelectorAll('.tabs-content-item');

        for (i = 0; i < contentPanes.length; i++) {
            contentPanes[i].classList.remove("active");
        }

        let anchorReference = tabClickEvent.target;
        let activePaneId = anchorReference.getAttribute("href");
        let activePane = document.querySelector(activePaneId);

        activePane.classList.add("active");
    }

    for (i = 0; i < tabs.length; i++) {
        tabs[i].addEventListener("click", tabClicks)
    }

Css for tab content:

.tabs-content .tabs-content-item {
    display: none;
}
.tabs-content .tabs-content-item.active {
    display: block;
}

Body:
Element.closest searchs up the DOM to find an element matching the selector passed as argument. If Element already matches the selector, Element (the node on which closest is called) is returned.

Hence try changing

 let anchorReference = tabClickEvent.target;

to

 let anchorReference = tabClickEvent.target.closest('a');

as for example in

let tabs = document.querySelectorAll('.tabs-bar .tabs-bar-item');

function tabClicks(tabClickEvent) {
    for (let i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove("active");
    }

    let clickedTab = tabClickEvent.currentTarget;

    clickedTab.classList.add("active");
    tabClickEvent.preventDefault();

    let contentPanes = document.querySelectorAll('.tabs-content-item');

    for (i = 0; i < contentPanes.length; i++) {
        contentPanes[i].classList.remove("active");
    }

    let anchorReference = tabClickEvent.target.closest('a');
    console.log( anchorReference);
    let activePaneId = anchorReference.getAttribute("href");
    let activePane = document.querySelector(activePaneId);

    activePane.classList.add("active");
}

for (i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", tabClicks)
}

.tabs-content .tabs-content-item {
    display: none;
}
.tabs-content .tabs-content-item.active {
    display: block;
}

<div class="tabs-bar">
  <div class="tabs-bar-item">
    <a href="#tab3">
      <img class="icon" src="img/school.png">
      <h3 class="title">Instruktāžas datu aizsardzībā</h3>
    </a>
  </div>
</div>
<div class=tabs-content>
  <div id="tab3" class="tabs-content-item">
     content of tab3 with self contained link: <a id="here" href="#here">here</a>. Clicking "here" should not close the tab!
  </div>
</div>


来源: stackexchange

答:
First off : you can do this in pure CSS with the :target pseudo-class, no JS needed.

.tabs-content .tabs-content-item {
    display: none;
}
.tabs-content .tabs-content-item:target {
    display: block;
}
```

In the near future, you can also style the tab link for the currently open tab by using the :local-link pseudo-class.

In your code, tabClickEvent.currentTarget always refers to the DIV element that you attached the listener to. That element has no href. There are multiple ways to fix that. Removing the DIV altogether would be a good start, then you can attach a listener to the links, or make a global listener that checks if it's been clicked on a link or its descendant (using element.closest('a')).

Either way, properly implementing navigation with JavaScript is not as easy as you might think (this is also why the pure CSS solution is good). For example, if the user wants to open the link in a new (browser) tab, you'd have to add some code to read the page's fragment on load and open the correct tab without user interaction.

ContentLicense: CC BY-SA 4.0

Title: Vanilla JavaScript getAttribute("href") from link with image inside

Body:
First off : you can do this in pure CSS with the :target pseudo-class, no JS needed.

.tabs-content .tabs-content-item {
    display: none;
}
.tabs-content .tabs-content-item:target {
    display: block;
}

In the near future, you can also style the tab link for the currently open tab by using the :local-link pseudo-class.

In your code, tabClickEvent.currentTarget always refers to the DIV element that you attached the listener to. That element has no href. There are multiple ways to fix that. Removing the DIV altogether would be a good start, then you can attach a listener to the links, or make a global listener that checks if it's been clicked on a link or its descendant (using element.closest('a')).

Either way, properly implementing navigation with JavaScript is not as easy as you might think (this is also why the pure CSS solution is good). For example, if the user wants to open the link in a new (browser) tab, you'd have to add some code to read the page's fragment on load and open the correct tab without user interaction.


问:
Is it possible to move MacOS TMPDIR to another drive?
Some programs write to the macOS TMPDIR that is on the booth volume, but unfortunately, some write huge files on it (for scratch disk, Lightroom for example) and this depletes the available space, but more importantly the remaining HD space on the boot volumes (especially nowadays with Apple's soldered SSDs) the remaining pace is not enough for the scratch disk and it fails. I experience it a lot with Lightroom doing Panorama,s temp files can be hundred of Gigagbytes. Unfortunately, you can't set the scratch disk location, contrary to photoshop. It writes to the TMPDIR.

So I would like to move that TMPDIR  to another external SSD.
I tried the symbolic link but unfortunately, I don't have the permission to overwrite or rename the current temporary folder.

Maybe there's a way to change the way the TMPDIR is create so it does it on another drive than the boot drive, or maybe I could get the permission to modify the current one.

Given the fact that lots of program used that location that is often too small, it would be a major boon to get a method to put that TMPDIR on another drive.

答: Have you tried TMPDIR=/your/tmp/dir open -n /Applications/Lightroom.app from terminal?


问:
How do I remove blank lines from text in PHP?
I need to remove blank lines (with whitespace or absolutely blank) in PHP. I use this regular expression, but it does not work:

```<code>$str = ereg_replace('^[ \t]*$\r?\n', '', $str);
$str = preg_replace('^[ \t]*$\r?\n', '', $str);
</code>```

I want a result of:

```<code>blahblah

blahblah

   adsa

sad asdasd
</code>```

will:

```<code>blahblah
blahblah
   adsa
sad asdasd
</code>```

答:
Your ereg-replace() solution is wrong because the ereg/eregi methods are deprecated.  Your preg_replace() won't even compile, but if you add delimiters and set multiline mode, it will work fine:

```<code>$str = preg_replace('/^[ \t]*[\r\n]+/m', '', $str);
</code>```

The m modifier allows ^ to match the beginning of a logical line rather than just the beginning of the whole string.  The start-of-line anchor is necessary because without it the regex would match the newline at the end of every line, not just the blank ones.  You don't need the end-of-line anchor ($) because you're actively matching the newline characters, but it doesn't hurt.

The accepted answer gets the job done, but it's more complicated than it needs to be.  The regex has to match either the beginning of the string (^[\r\n]*, multiline mode not set) or at least one newline ([\r\n]+), followed by at least one newline ([\r\n]+).  So, in the special case of a string that starts with one or more blank lines, they'll be replaced with one blank line. I'm pretty sure that's not the desired outcome.

But most of the time it replaces two or more consecutive newlines, along with any horizontal whitespace (spaces or tabs) that lies between them, with one linefeed.  That's the intent, anyway. The author seems to expect \s to match just the space character (\x20), when in fact it matches any whitespace character.  That's a very common mistake.  The actual list varies from one regex flavor to the next, but at minimum you can expect \s to match whatever [ \t\f\r\n] matches.

Actually, in PHP you have a better option:

```<code>$str = preg_replace('/^\h*\v+/m', '', $str);
</code>```

\h matches any horizontal whitespace character, and \v matches vertical whitespace.

OwnerDisplayName: StoneHeart

Body:
I need to remove blank lines (with whitespace or absolutely blank) in PHP. I use this regular expression, but it does not work:

$str = ereg_replace('^[ \t]*$\r?\n', '', $str);
$str = preg_replace('^[ \t]*$\r?\n', '', $str);

I want a result of:

blahblah

blahblah

   adsa

sad asdasd

will:

blahblah
blahblah
   adsa
sad asdasd

LastEditorDisplayName: StoneHeart

Body:
Your ereg-replace() solution is wrong because the ereg/eregi methods are deprecated.  Your preg_replace() won't even compile, but if you add delimiters and set multiline mode, it will work fine:

$str = preg_replace('/^[ \t]*[\r\n]+/m', '', $str);

The m modifier allows ^ to match the beginning of a logical line rather than just the beginning of the whole string.  The start-of-line anchor is necessary because without it the regex would match the newline at the end of every line, not just the blank ones.  You don't need the end-of-line anchor ($) because you're actively matching the newline characters, but it doesn't hurt.

The accepted answer gets the job done, but it's more complicated than it needs to be.  The regex has to match either the beginning of the string (^[\r\n]*, multiline mode not set) or at least one newline ([\r\n]+), followed by at least one newline ([\r\n]+).  So, in the special case of a string that starts with one or more blank lines, they'll be replaced with one blank line. I'm pretty sure that's not the desired outcome.

But most of the time it replaces two or more consecutive newlines, along with any horizontal whitespace (spaces or tabs) that lies between them, with one linefeed.  That's the intent, anyway. The author seems to expect \s to match just the space character (\x20), when in fact it matches any whitespace character.  That's a very common mistake.  The actual list varies from one regex flavor to the next, but at minimum you can expect \s to match whatever [ \t\f\r\n] matches.

Actually, in PHP you have a better option:

$str = preg_replace('/^\h*\v+/m', '', $str);

\h matches any horizontal whitespace character, and \v matches vertical whitespace.

OwnerDisplayName: Alan M


问:
Flutter web can't load network image from another domain
I can't load network images in flutter web from other domains with API calls. getting this error

Trying to load an image from another domain? Find answers at:
https://flutter.dev/docs/development/platform-integration/web-images
ImageCodecException: Failed to load network image.

any help?

答:
Simply add this in your Flutter (web/index.html):

```

Body:
Simply add this in your Flutter (web/index.html):

<script type="text/javascript">
    window.flutterWebRenderer = "html";
</script>


问:
How to use grepl function to subset rows based on multiple conditions across columns in R
I am trying to subset a dataset using the grepl function.

I want to retain rows where all columns contain '@'

I tried this code but it doesn't work.

```<code>all_nullx <- riv %>% with(riv, riv[ grepl( '@', col1) & grepl( '@', col2) & grepl('@', col3) & grepl('@', left_index) & grepl('@', right_middle) & grepl('@', col4), ])
</code>```

Thanks

答:
Tidyverse

We can apply a function across all columns using everything() inside of across, then keep only rows that have @ in every column.

```<code>library(tidyverse)

riv %>%
  filter(across(everything(), ~ grepl("@", .)))
</code>```

Or with stringr:

```<code>riv %>%
  filter(across(everything(), ~ str_detect(., "@")))
</code>```

base R

Or we can use grepl with Reduce from base R:

```<code>riv[Reduce(`&`, lapply(riv, grepl, pattern = "@")),]
</code>```

Or one more base R possibility:

```<code>riv[apply(riv , 1 , function(x) all(grepl("@", x))), ]
</code>```

Output

```<code>    a   b   c
1 A@r C@r F@r
2 B@r D@r G@r
</code>```

Data

```<code>riv <- structure(list(
  a = c("A@r", "B@r", "Rr"),
  b = c("C@r", "D@r", "E@r"),
  c = c("F@r", "G@r", "Hr")
),
class = "data.frame",
row.names = c(NA,-3L))
</code>```

Body:
I am trying to subset a dataset using the grepl function.

I want to retain rows where all columns contain '@'

I tried this code but it doesn't work.

all_nullx <- riv %>% with(riv, riv[ grepl( '@', col1) & grepl( '@', col2) & grepl('@', col3) & grepl('@', left_index) & grepl('@', right_middle) & grepl('@', col4), ])

Thanks

Body:
Tidyverse

We can apply a function across all columns using everything() inside of across, then keep only rows that have @ in every column.

library(tidyverse)

riv %>%
  filter(across(everything(), ~ grepl("@", .)))

Or with stringr:

riv %>%
  filter(across(everything(), ~ str_detect(., "@")))

base R

Or we can use grepl with Reduce from base R:

riv[Reduce(`&`, lapply(riv, grepl, pattern = "@")),]

Or one more base R possibility:

riv[apply(riv , 1 , function(x) all(grepl("@", x))), ]

Output

    a   b   c
1 A@r C@r F@r
2 B@r D@r G@r

Data

riv <- structure(list(
  a = c("A@r", "B@r", "Rr"),
  b = c("C@r", "D@r", "E@r"),
  c = c("F@r", "G@r", "Hr")
),
class = "data.frame",
row.names = c(NA,-3L))


问:
value changes after adding optimization flag in Clang
I have written a little program:

#include <stdio.h>

void tester() {
    int x = 69;
}

void x() {
    int x;
    printf("%d\n", x);
}

int main() {
    tester();
    x();

}
```

which I expect to print out 69. It prints out 69 when I compile without optimization, but with O1-O3, it prints out large numbers. Why is this?

答:
Attempting to read an uninitialized variable that never had its address taken triggers undefined behavior, which basically means that the program is not required to behave in any particular way.

It's clear that you were attempting to have the uninitialized variable x in the function x to get the "left over" value of x in tester.  With optimization disabled this is how it happens to work.  With optimization enabled, the compiler takes advantage of undefined behavior to assume it does not happen and make certain optimizations based on that fact.

So with optimization enabled, the compiler is basically assuming you won't read an uninialized variable which is why you see different output.

Body:
I have written a little program:

#include <stdio.h>

void tester() {
    int x = 69;
}

void x() {
    int x;
    printf("%d\n", x);
}

int main() {
    tester();
    x();

}

which I expect to print out 69. It prints out 69 when I compile without optimization, but with O1-O3, it prints out large numbers. Why is this?


问:
Proportionally scaling UIPanGesture actions to zoom level in a SpriteKit scene
I have a SpriteKit scene in my iOS app that makes use of both pan and pinch gestures - panning for moving the view of the scene's camera, and and pinch gestures for zooming in and out of the scene by scaling the scene's camera.

Zooming works well:

```<code>@objc func pinchGestureAction(_ sender: UIPinchGestureRecognizer) {

    guard let camera = canvasScene.camera else {
        return
    }

    if sender.state == .began {
        previousCameraScale = camera.xScale
    } else if sender.state == .ended {
        previousCameraScale = camera.xScale
        return
    }

    camera.setScale(previousCameraScale * 1 / sender.scale)

    print(camera.xScale)
    print(camera.yScale)
}
</code>```

The issue is with the panning, which is done using the pan gesture recognizer:

```<code>@objc func panGestureAction(_ sender: UIPanGestureRecognizer) {

    if sender.state != .changed {
       return
    }

    guard let camera = canvasScene.camera else {
       return
    }

    // Get touch delta
    let translation = sender.translation(in: sender.view!)

    // Move camera
    self.canvasScene.camera?.position.x -= translation.x
    self.canvasScene.camera?.position.y += translation.y

    // Reset
    sender.setTranslation(CGPoint.zero, in: sender.view)
}
</code>```

Panning works pretty well when the user is zoomed in really close to the objects on the canvas. When the camera is zoomed further out, it takes a considerably large amount of gestures to pan through the canvas scene than it did when the camera view was zoomed in at a closer view.

I tried scaling the values of the camera position by that of the camera's scaling factor like so:

```<code>self.canvasScene.camera?.position.x -= translation.x * camera.xScale
self.canvasScene.camera?.position.y += translation.y * camera.yScale
</code>```

But that does not seem to work. Any ideas on how to best implement proper camera panning behavior based on that of how far a camera is zoomed in to a scene?

答:
To get the desired behavior, I had to apply an additional scaling factor to the SKScene's camera position:

```<code>@objc func panGestureAction(_ sender: UIPanGestureRecognizer) {
    if sender.state != .changed {
        return
    }

    guard let camera = canvasScene.camera else {
        return
    }

    // Get touch delta
    let translation = sender.translation(in: sender.view!)

    // Move camera
    self.canvasScene.camera?.position.x -= translation.x * camera.xScale / 1.5
    self.canvasScene.camera?.position.y += translation.y * camera.yScale / 1.5

    // Reset
    sender.setTranslation(CGPoint.zero, in: sender.view)
}
</code>```

Body:
I have a SpriteKit scene in my iOS app that makes use of both pan and pinch gestures - panning for moving the view of the scene's camera, and and pinch gestures for zooming in and out of the scene by scaling the scene's camera.

Zooming works well:

@objc func pinchGestureAction(_ sender: UIPinchGestureRecognizer) {

    guard let camera = canvasScene.camera else {
        return
    }

    if sender.state == .began {
        previousCameraScale = camera.xScale
    } else if sender.state == .ended {
        previousCameraScale = camera.xScale
        return
    }

    camera.setScale(previousCameraScale * 1 / sender.scale)

    print(camera.xScale)
    print(camera.yScale)
}

The issue is with the panning, which is done using the pan gesture recognizer:

@objc func panGestureAction(_ sender: UIPanGestureRecognizer) {

    if sender.state != .changed {
       return
    }

    guard let camera = canvasScene.camera else {
       return
    }

    // Get touch delta
    let translation = sender.translation(in: sender.view!)

    // Move camera
    self.canvasScene.camera?.position.x -= translation.x
    self.canvasScene.camera?.position.y += translation.y

    // Reset
    sender.setTranslation(CGPoint.zero, in: sender.view)
}

Panning works pretty well when the user is zoomed in really close to the objects on the canvas. When the camera is zoomed further out, it takes a considerably large amount of gestures to pan through the canvas scene than it did when the camera view was zoomed in at a closer view.

I tried scaling the values of the camera position by that of the camera's scaling factor like so:

self.canvasScene.camera?.position.x -= translation.x * camera.xScale
self.canvasScene.camera?.position.y += translation.y * camera.yScale

But that does not seem to work. Any ideas on how to best implement proper camera panning behavior based on that of how far a camera is zoomed in to a scene?

Body:
To get the desired behavior, I had to apply an additional scaling factor to the SKScene's camera position:

@objc func panGestureAction(_ sender: UIPanGestureRecognizer) {
    if sender.state != .changed {
        return
    }

    guard let camera = canvasScene.camera else {
        return
    }

    // Get touch delta
    let translation = sender.translation(in: sender.view!)

    // Move camera
    self.canvasScene.camera?.position.x -= translation.x * camera.xScale / 1.5
    self.canvasScene.camera?.position.y += translation.y * camera.yScale / 1.5

    // Reset
    sender.setTranslation(CGPoint.zero, in: sender.view)
}


问:
Overload resolution between two constructors from std::initializer_list
In following program, struct C has two constructors : one from std::initializer_list and the other from std::initializer_list. Then an object of the struct is created with C{{1}}:

```<code>#include <initializer_list>

struct A {
    int i;
};

struct B {
    constexpr explicit B(int) {}
};

struct C {
    int v;
    constexpr C(std::initializer_list<A>) : v(1) {}
    constexpr C(std::initializer_list<B>) : v(2) {}
};

static_assert( C{{1}}.v == 1 );
</code>```

Since only aggregate A can be implicitly constructed from int, one could expect that C(std::initializer_list) is preferred and the program succeeds. And indeed it does in Clang.

However GCC complains:

```<code>error: call of overloaded 'C(<brace-enclosed initializer list>)' is ambiguous
note: candidate: 'constexpr C::C(std::initializer_list<B>)'
note: candidate: 'constexpr C::C(std::initializer_list<A>)'
</code>```

and so does MSVC:

```<code>error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'C'
note: No constructor could take the source type, or constructor overload resolution was ambiguous
</code>```

Demo: https://gcc.godbolt.org/z/joz91q4ed

Which compiler is correct here?

答:
The wording could be clearer (which is unsurprising), but GCC and MSVC are correct here: the relevant rule ([over.ics.list]/7) checks only that

overload resolution […] chooses a single best constructor […] to perform the initialization of an object of type X from the argument initializer list

so the fact that the initialization of B from {1} would be ill-formed is irrelevant.

There are several such places where implicit conversion sequences are more liberal than actual initialization, causing certain cases to be ambiguous even though some of the possibilities wouldn’t actually work.  If the programmer was confused and thought one of those near misses was actually a better match, it’s a feature that the ambiguity is reported.

Body:
In following program, struct C has two constructors : one from std::initializer_list and the other from std::initializer_list. Then an object of the struct is created with C{{1}}:

#include <initializer_list>

struct A {
    int i;
};

struct B {
    constexpr explicit B(int) {}
};

struct C {
    int v;
    constexpr C(std::initializer_list) : v(1) {}
    constexpr C(std::initializer_list) : v(2) {}
};

static_assert( C{{1}}.v == 1 );

Since only aggregate A can be implicitly constructed from int, one could expect that C(std::initializer_list) is preferred and the program succeeds. And indeed it does in Clang.

However GCC complains:

error: call of overloaded 'C(<brace-enclosed initializer list>)' is ambiguous
note: candidate: 'constexpr C::C(std::initializer_list)'
note: candidate: 'constexpr C::C(std::initializer_list)'

and so does MSVC:

error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'C'
note: No constructor could take the source type, or constructor overload resolution was ambiguous

Demo: https://gcc.godbolt.org/z/joz91q4ed

Which compiler is correct here?


问:
join eloquent table with custom format response
I'm just join 3 eloquent tables. it works but the response json format is not what I want. I need to customizing the format response so it will easy to read.

this is my join table code

```<code>$showPresensi = Event::join('presensis', 'presensis.event_id', '=', 'events.id')
            ->join('anggotas', 'presensis.anggota_id', '=', 'anggotas.id')
            ->where('presensis.event_id', 2)
            ->get(['events.*', 'anggotas.nama_lengkap','presensis.kehadiran']);
    return $this->ok($showPresensi, "Success");
</code>```

and  this is my current response json

```<code>{
"message": "Success",
"success": true,
"code": 200,
"data": [
    {
        "id": 2,
        "nama": "Event 2",
        "tanggal": "Sabtu, 12 Februari 2022",
        "permintaan_dari": "Yang bersangkutan",
        "hasil_kegiatan": "nothing",
        "created_at": "2022-02-12T21:53:14.000000Z",
        "updated_at": "2022-02-12T21:53:14.000000Z",
        "nama_lengkap": "user 1",
        "kehadiran": "0"
    },
    {
        "id": 2,
        "nama": "Event 2",
        "tanggal": "Sabtu, 12 Februari 2022",
        "permintaan_dari": "Yang bersangkutan",
        "hasil_kegiatan": "nothing",
        "created_at": "2022-02-12T21:53:14.000000Z",
        "updated_at": "2022-02-12T21:53:14.000000Z",
        "nama_lengkap": "user 3",
        "kehadiran": "0"
    },
    {
        "id": 2,
        "nama": "Event 2",
        "tanggal": "Sabtu, 12 Februari 2022",
        "permintaan_dari": "Yang bersangkutan",
        "hasil_kegiatan": "nothing",
        "created_at": "2022-02-12T21:53:14.000000Z",
        "updated_at": "2022-02-12T21:53:14.000000Z",
        "nama_lengkap": "user 2",
        "kehadiran": "1"
    }
    ]
}
</code>```

I want to column of nama_lengkap and kehadiran become an array so it will become like this:

```<code>{
  "message": "Success",
  "success": true,
  "code": 200,
  "data": [
    {
      "id": 2,
      "nama": "Event 2",
      "tanggal": "Sabtu, 12 Februari 2022",
      "permintaan_dari": "Yang bersangkutan",
      "hasil_kegiatan": "nothing",
      "created_at": "2022-02-12T21:53:14.000000Z",
      "updated_at": "2022-02-12T21:53:14.000000Z",
      "presensi": [
        {
          "nama_lengkap": "user 1",
          "kehadiran": "0"
        },
        {
          "nama_lengkap": "user 3",
          "kehadiran": "0"
        },
        {
          "nama_lengkap": "user 2",
          "kehadiran": "1"
        }
      ]
    }
  ]
}
</code>```

is there any solution for this? any clues are helps. thank you

答:
The easiest way would be to use nested eager loading with Eloquent.

Then you could do:

```<code>$showPresensi = Event::with('presensis', 'presensis.anggotas').find(2);
</code>```

The structure should match more closely what you're going for. Then you could either modify the collection to get exactly what you want, or add accessors to your models.

Body:
I'm just join 3 eloquent tables. it works but the response json format is not what I want. I need to customizing the format response so it will easy to read.

this is my join table code

$showPresensi = Event::join('presensis', 'presensis.event_id', '=', 'events.id')
            ->join('anggotas', 'presensis.anggota_id', '=', 'anggotas.id')
            ->where('presensis.event_id', 2)
            ->get(['events.*', 'anggotas.nama_lengkap','presensis.kehadiran']);
    return $this->ok($showPresensi, "Success");

and  this is my current response json

{
"message": "Success",
"success": true,
"code": 200,
"data": [
    {
        "id": 2,
        "nama": "Event 2",
        "tanggal": "Sabtu, 12 Februari 2022",
        "permintaan_dari": "Yang bersangkutan",
        "hasil_kegiatan": "nothing",
        "created_at": "2022-02-12T21:53:14.000000Z",
        "updated_at": "2022-02-12T21:53:14.000000Z",
        "nama_lengkap": "user 1",
        "kehadiran": "0"
    },
    {
        "id": 2,
        "nama": "Event 2",
        "tanggal": "Sabtu, 12 Februari 2022",
        "permintaan_dari": "Yang bersangkutan",
        "hasil_kegiatan": "nothing",
        "created_at": "2022-02-12T21:53:14.000000Z",
        "updated_at": "2022-02-12T21:53:14.000000Z",
        "nama_lengkap": "user 3",
        "kehadiran": "0"
    },
    {
        "id": 2,
        "nama": "Event 2",
        "tanggal": "Sabtu, 12 Februari 2022",
        "permintaan_dari": "Yang bersangkutan",
        "hasil_kegiatan": "nothing",
        "created_at": "2022-02-12T21:53:14.000000Z",
        "updated_at": "2022-02-12T21:53:14.000000Z",
        "nama_lengkap": "user 2",
        "kehadiran": "1"
    }
    ]
}

I want to column of nama_lengkap and kehadiran become an array so it will become like this:

{
  "message": "Success",
  "success": true,
  "code": 200,
  "data": [
    {
      "id": 2,
      "nama": "Event 2",
      "tanggal": "Sabtu, 12 Februari 2022",
      "permintaan_dari": "Yang bersangkutan",
      "hasil_kegiatan": "nothing",
      "created_at": "2022-02-12T21:53:14.000000Z",
      "updated_at": "2022-02-12T21:53:14.000000Z",
      "presensi": [
        {
          "nama_lengkap": "user 1",
          "kehadiran": "0"
        },
        {
          "nama_lengkap": "user 3",
          "kehadiran": "0"
        },
        {
          "nama_lengkap": "user 2",
          "kehadiran": "1"
        }
      ]
    }
  ]
}

is there any solution for this? any clues are helps. thank you

Body:
The easiest way would be to use nested eager loading with Eloquent.

Then you could do:

$showPresensi = Event::with('presensis', 'presensis.anggotas').find(2);

The structure should match more closely what you're going for. Then you could either modify the collection to get exactly what you want, or add accessors to your models.


问:
Can we set up Intelephense in VS Code as per WordPress coding Standard?
I am using PHPCS and PHPCBF for WordPress development in VS Code.
( as per instructions mentioned in https://github.com/tommcfarlin/phpcs-wpcs-vscode )

While PHPCBF is formatting the codes as per WPCS, I still feel that the code looks really ugly, especially when Html tags are present in the PHP document.

When I use Intelephense to format the Php codes, the code looks visually pleasant including properly indented Html tags. The tradeoff of using Intelephense is that the code is not WPCS compliant anymore. There is an option to include WordPress as stubs in Intelephense but that is only for including WordPress specific functions and not related to formatting.

Some issues faced while formatting with Intelephense are:

No space after opening and before the closing parenthesis, (phpcs)

There must be no blank line before the file comment (phpcs)

<?php
// this is a blank line inserted by Intelephense which is causing error no.2 provided in summary above
/**
 * This is a sample file
 *
 * @package something.
 * something something
 * something something
 */

get_header();
if (have_posts()) {
    while (have_posts()) {
// No space is inserted by Intelephense After opening and before Closing parenthesis which is causing error no.1 provided in summary above
        the_post(); ?>

            "><?php the_title(); ?>

        <?php the_content(); ?>

<?php
    }
}
get_footer();
?>
```

答:
This issue was closed with the conclusion "This extension doesn't use phpcbf though", so I'm not sure how you could do it specifically with Intelephense for VS Code.

But if you're looking for a solution to use phpcbf as your formatter for php files in VS Code, and your phpcbf is set up and you have all your coding standards installed, you can use phpcbf from Per Soderlind.

Then, if you reload the editor and try to format a php file with Ctrl+Shift+I (or your preferred method) a popup will appear where you have to select your preferred formatter.

then you should select the one that says valeryanm.vscode-phpsab

Or if the popup doesn't appear, just add the following to your settings.json:

```<code>"[php]": {
        "editor.defaultFormatter": "valeryanm.vscode-phpsab"
    },
</code>```

Now anytime you try to format it phpcbf will run on the whole document.

Body:
I am using PHPCS and PHPCBF for WordPress development in VS Code.
( as per instructions mentioned in https://github.com/tommcfarlin/phpcs-wpcs-vscode )

While PHPCBF is formatting the codes as per WPCS, I still feel that the code looks really ugly, especially when Html tags are present in the PHP document.

When I use Intelephense to format the Php codes, the code looks visually pleasant including properly indented Html tags. The tradeoff of using Intelephense is that the code is not WPCS compliant anymore. There is an option to include WordPress as stubs in Intelephense but that is only for including WordPress specific functions and not related to formatting.

Some issues faced while formatting with Intelephense are:

No space after opening and before the closing parenthesis, (phpcs)

There must be no blank line before the file comment (phpcs)

<?php
// this is a blank line inserted by Intelephense which is causing error no.2 provided in summary above
/**
 * This is a sample file
 *
 * @package something.
 * something something
 * something something
 */

get_header();
if (have_posts()) {
    while (have_posts()) {
// No space is inserted by Intelephense After opening and before Closing parenthesis which is causing error no.1 provided in summary above
        the_post(); ?>

            <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

        <?php the_content(); ?>

<?php
    }
}
get_footer();
?>

Body:
This issue was closed with the conclusion "This extension doesn't use phpcbf though", so I'm not sure how you could do it specifically with Intelephense for VS Code.

But if you're looking for a solution to use phpcbf as your formatter for php files in VS Code, and your phpcbf is set up and you have all your coding standards installed, you can use phpcbf from Per Soderlind.

Then, if you reload the editor and try to format a php file with Ctrl+Shift+I (or your preferred method) a popup will appear where you have to select your preferred formatter.

then you should select the one that says valeryanm.vscode-phpsab

Or if the popup doesn't appear, just add the following to your settings.json:

"[php]": {
        "editor.defaultFormatter": "valeryanm.vscode-phpsab"
    },

Now anytime you try to format it phpcbf will run on the whole document.


问:
Interface get returns null value
I'm new with C# and my console application for some reason the interface IService doesn't transfer the value to the Service.  I tried to debug: _service.GetAccountName(name), name has value and then I get System.NullReferenceException for _service.GetAccountName. What I'm doing wrong here? Thank you for your patience.

Program:

```<code>static void Main(string[] args)
{
    var newMenu = new Menu();
    newMenu.Show();

}
</code>```

Menu

```<code> public class Menu
{
    private IService _service { get; set; }

    public void Show()
    {

        var shouldStop = "";

        while (shouldStop.ToLower() != "yes")
        {
            Console.WriteLine("Please select one of the following options:");
            Console.WriteLine("1.Create BC \n2.View BC\n3.Edit BC\n4.Delete BC");
            var response = int.Parse(Console.ReadLine());

            switch (response)
            {
                case 1:
                    Console.WriteLine("You choose to create bank account");
                    ChooseTypeOfAccount();
                    break;
                case 2:
                    Console.WriteLine("You choose to view bank account");
                    var user = ChooseToViewBankAccount();
                    if (user != null)
                    {
                        Console.WriteLine("Id:" + user.Id + "\n"+ user.Name + "\n" + user.Surname);
                    }
                    else
                    {
                        Console.WriteLine("User can not be found");
                    }

                    Console.WriteLine("ALL USERS");
                    var allUs = _service.GetAllUsers();
                    for(var i = 0; i < allUs.Item1.Count; i++)
                    {
                        Console.WriteLine(allUs.Item1[i].Name + " " + allUs.Item1[i].Surname);
                        for(var j = 0; j < allUs.Item2.Count; j++)
                        {
                            Console.WriteLine(allUs.Item2[i].Name + " " + allUs.Item2[i].Surname);
                        }
                    }

                    break;
                case 3:
                    Console.WriteLine("You choose to edit BC");
                    break;
                case 4:
                    Console.WriteLine("You choose to delete BC");
                    break;
                default:
                    Console.WriteLine("oops wrong choice");
                    break;
            }
            Console.WriteLine("To exit type yes");
            shouldStop = Console.ReadLine();
        }

    }

    private User ChooseToViewBankAccount()
    {
        Console.WriteLine("Please enter your name");
        var name = Console.ReadLine();

        User user = _service.GetAccountByName(name);

        return user;
    }
</code>```

Service:

```<code>public class Service : IService
{
    public AccountsData _accountsRepository { get; set; }

    public ChildAccountsData _childAccountRepository { get; set; }

    public Service()
    {
        _accountsRepository = new AccountsData();
        _childAccountRepository = new ChildAccountsData();
    }
</code>```

IService

```<code>public interface IService
{
    User GetAccountByName(string name);
    void CreateRegularAccount(string name, string surname);
    void CreateChildAccount(string childName, string childSurname);
    (List<Account>, List<ChildAccount>) GetAllUsers();
}
</code>```

答:
as currently written you need to do

```<code>static void Main(string[] args)
{
    var newMenu = new Menu();
    newMenu.Service = new Service();
    newMenu.Show();

}
</code>```

you would need ot change

```<code>      private IService _service { get; set; }
</code>```

to

```<code>      public IService _service { get; set; }
</code>```

but thats probably not what you want (allow callers to change Service as you go along). SO do this

```<code>       private IService _service = new Service();
</code>```

PS, dont call you service IService call it something useful like IDBAccess or somethig like that.

Title: Interface get returns null value

Body:
I'm new with C# and my console application for some reason the interface IService doesn't transfer the value to the Service.  I tried to debug: _service.GetAccountName(name), name has value and then I get System.NullReferenceException for _service.GetAccountName. What I'm doing wrong here? Thank you for your patience.

Program:

static void Main(string[] args)
{
    var newMenu = new Menu();
    newMenu.Show();

}

Menu

 public class Menu
{
    private IService _service { get; set; }

    public void Show()
    {

        var shouldStop = "";

        while (shouldStop.ToLower() != "yes")
        {
            Console.WriteLine("Please select one of the following options:");
            Console.WriteLine("1.Create BC \n2.View BC\n3.Edit BC\n4.Delete BC");
            var response = int.Parse(Console.ReadLine());

            switch (response)
            {
                case 1:
                    Console.WriteLine("You choose to create bank account");
                    ChooseTypeOfAccount();
                    break;
                case 2:
                    Console.WriteLine("You choose to view bank account");
                    var user = ChooseToViewBankAccount();
                    if (user != null)
                    {
                        Console.WriteLine("Id:" + user.Id + "\n"+ user.Name + "\n" + user.Surname);
                    }
                    else
                    {
                        Console.WriteLine("User can not be found");
                    }

                    Console.WriteLine("ALL USERS");
                    var allUs = _service.GetAllUsers();
                    for(var i = 0; i < allUs.Item1.Count; i++)
                    {
                        Console.WriteLine(allUs.Item1[i].Name + " " + allUs.Item1[i].Surname);
                        for(var j = 0; j < allUs.Item2.Count; j++)
                        {
                            Console.WriteLine(allUs.Item2[i].Name + " " + allUs.Item2[i].Surname);
                        }
                    }

                    break;
                case 3:
                    Console.WriteLine("You choose to edit BC");
                    break;
                case 4:
                    Console.WriteLine("You choose to delete BC");
                    break;
                default:
                    Console.WriteLine("oops wrong choice");
                    break;
            }
            Console.WriteLine("To exit type yes");
            shouldStop = Console.ReadLine();
        }

    }

    private User ChooseToViewBankAccount()
    {
        Console.WriteLine("Please enter your name");
        var name = Console.ReadLine();

        User user = _service.GetAccountByName(name);

        return user;
    }

Service:

public class Service : IService
{
    public AccountsData _accountsRepository { get; set; }

    public ChildAccountsData _childAccountRepository { get; set; }

    public Service()
    {
        _accountsRepository = new AccountsData();
        _childAccountRepository = new ChildAccountsData();
    }

IService

public interface IService
{
    User GetAccountByName(string name);
    void CreateRegularAccount(string name, string surname);
    void CreateChildAccount(string childName, string childSurname);
    (List<Account>, List<ChildAccount>) GetAllUsers();
}

Body:
as currently written you need to do

static void Main(string[] args)
{
    var newMenu = new Menu();
    newMenu.Service = new Service();
    newMenu.Show();

}

you would need ot change

      private IService _service { get; set; }

to

      public IService _service { get; set; }

but thats probably not what you want (allow callers to change Service as you go along). SO do this

       private IService _service = new Service();

PS, dont call you service IService call it something useful like IDBAccess or somethig like that.


问:
Query to return data from SQL Server table based on date criteria
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

```<code>DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);
</code>```

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

```<code>select * rows where datevalue >= date1 and datevalue <= date2
</code>```

Thank you.

答:
I bet your Date_Requested in your table also has some time associated with it - so it probably really is 18/08/2011 14:37 or something like that.

The BETWEEN clause will be selecting anything between 18/08/2011 00:00:00 and 18/08/2011 00:00:00 - basically nothing.

What you need to take into account when working with DATETIME is the fact there's always also TIME involved!

If you want everything for today, you need to use:

```<code>BETWEEN `18/08/2011 00:00:00` AND `18/08/2011 23:59:59`
</code>```

With those two values, you should get all rows with a Date_Requested of today.

OR: in SQL Server 2008 and newer, you could also use the DATE column type which stores date only - no time portion involved. In that case, you should be fine with your query values.

ContentLicense: CC BY-SA 3.0

Body:
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

select * rows where datevalue >= date1 and datevalue <= date2

Thank you.

Body:
I bet your Date_Requested in your table also has some time associated with it - so it probably really is 18/08/2011 14:37 or something like that.

The BETWEEN clause will be selecting anything between 18/08/2011 00:00:00 and 18/08/2011 00:00:00 - basically nothing.

What you need to take into account when working with DATETIME is the fact there's always also TIME involved!

If you want everything for today, you need to use:

BETWEEN `18/08/2011 00:00:00` AND `18/08/2011 23:59:59`

With those two values, you should get all rows with a Date_Requested of today.

OR: in SQL Server 2008 and newer, you could also use the DATE column type which stores date only - no time portion involved. In that case, you should be fine with your query values.


问:
Duplicating columns whose names are suffixed with numbers and adding an offset to the new column name suffixes
I would like to duplicate a certain subset of columns whose names are suffixed by numbers. To the numerical suffixes of new columns should be added a certain offset (in the following example it's 12).

Source data frame:

Desired data frame:

Unfortunately, my code isn't working at all and on top, it seems unreasonably complicated.

```<code>library(tidyverse)

df <- data.frame(
  v_1 = c('Aira', 'Ben', 'Cat'),
  v_2 = c(23, 32, 27),
  v_3 = c(90, 98, 95)
)

# Duplicate columns using mutate + across
df2 <- df %>% mutate(
  across(
    .cols = starts_with('v'),
   .names = paste("x", toString(strtoi(strsplit({.col}, '_')[[1]][2]) + 12, sep="_"))
  )
)
</code>```

答:
this works for the given example, using dplyr::across():

```<code>df %>%
    dplyr::mutate(across(v_1:v_3,
                         .fns = ~ .x,
                         .names = "x_{as.numeric(stringr::str_sub(.col, 3, 3))+12}"))

   v_1 v_2 v_3 x_13 x_14 x_15
1 Aira  23  90 Aira   23   90
2  Ben  32  98  Ben   32   98
3  Cat  27  95  Cat   27   95
</code>```

EDIT

using regex to extract endings of strings that are one or more numbers:

```<code>df %>%
    dplyr::mutate(across(v_1:v_3,
                         .fns = ~ .x,
                         .names = "x_{as.numeric(stringr::str_extract(.col, pattern = '[0-9]+$'))+12}"))
</code>```

Body:
I would like to duplicate a certain subset of columns whose names are suffixed by numbers. To the numerical suffixes of new columns should be added a certain offset (in the following example it's 12).

Source data frame:

Desired data frame:

Unfortunately, my code isn't working at all and on top, it seems unreasonably complicated.

library(tidyverse)

df <- data.frame(
  v_1 = c('Aira', 'Ben', 'Cat'),
  v_2 = c(23, 32, 27),
  v_3 = c(90, 98, 95)
)

# Duplicate columns using mutate + across
df2 <- df %>% mutate(
  across(
    .cols = starts_with('v'),
   .names = paste("x", toString(strtoi(strsplit({.col}, '_')[[1]][2]) + 12, sep="_"))
  )
)

Body:
this works for the given example, using dplyr::across():

df %>%
    dplyr::mutate(across(v_1:v_3,
                         .fns = ~ .x,
                         .names = "x_{as.numeric(stringr::str_sub(.col, 3, 3))+12}"))

   v_1 v_2 v_3 x_13 x_14 x_15
1 Aira  23  90 Aira   23   90
2  Ben  32  98  Ben   32   98
3  Cat  27  95  Cat   27   95

EDIT

using regex to extract endings of strings that are one or more numbers:

df %>%
    dplyr::mutate(across(v_1:v_3,
                         .fns = ~ .x,
                         .names = "x_{as.numeric(stringr::str_extract(.col, pattern = '[0-9]+$'))+12}"))


问:
Git global config for specific repositories?
Meaning, having something like a per repo section [repo_url] that overrides global(not for a specific repo) options.

```<code>[core]
    filemode = false
    editor = notepad
[repo "example.com/repo1.git"]
    [core]
        filemode = true
        # editor = notepad
[repo "example.com/repo2.git"]
    [core]
        editor = vim
        # filemode = false
</code>```

Is possible in git?

Note: I'm making a lot of clones(git clone) of repos which I would specify in such a global config

答:
With Git 2.36 (Q2 2022), you will have another option than relying on a local folder: the conditional inclusion mechanism of configuration files using "[includeIf <condition>]" learns to base its decision on the URL of the remote repository the repository interacts with.

See commit 399b198, commit ed69e11 (18 Jan 2022) by Jonathan Tan (jhowtan).

(Merged by Junio C Hamano -- gitster -- in commit 13ce8f9, 09 Feb 2022)

config: include file if remote URL matches a glob

Signed-off-by: Jonathan Tan

Acked-by: Elijah Newren

This is a feature that supports config file inclusion conditional on whether the repo has a remote with a URL that matches a glob.

Similar to my previous work on remote-suggested hooks, the main motivation is to allow remote repo administrators to provide recommended configs in a way that can be consumed more easily (e.g. through a package installable by a package manager - it could, for example, contain a file to be included conditionally and a post-install script that adds the include directive to the system-wide config file).

In order to do this, Git reruns the config parsing mechanism upon noticing the first URL-conditional include in order to find all remote URLs, and these remote URLs are then used to determine if that first and all subsequent includes are executed.

Remote URLs are not allowed to be configured in any URL-conditionally-included file.

config now includes in its man page:

hasconfig:remote.*.url:

The data that follows this keyword is taken to
be a pattern with standard globbing wildcards and two
additional ones, **/ and /**, that can match multiple
components.

The first time this keyword is seen, the rest of
the config files will be scanned for remote URLs (without
applying any values).

If there exists at least one remote URL
that matches this pattern, the include condition is met.

Files included by this option (directly or indirectly) are not allowed
to contain remote URLs.

Note that unlike other includeIf conditions, resolving this condition
relies on information that is not yet known at the point of reading the
condition.

A typical use case is this option being present as a
system-level or global-level config, and the remote URL being in a
local-level config; hence the need to scan ahead when resolving this
condition.

In order to avoid the chicken-and-egg problem in which
potentially-included files can affect whether such files are potentially
included, Git breaks the cycle by prohibiting these files from affecting
the resolution of these conditions (thus, prohibiting them from
declaring remote URLs).

As for the naming of this keyword, it is for forwards compatibility with
a naming scheme that supports more variable-based include conditions,
but currently Git only supports the exact keyword described above.

config now includes in its man page:

```<code>; include only if a remote with the given URL exists (note
; that such a URL may be provided later in a file or in a
; file read after this file is read, as seen in this example)
[includeIf "hasconfig:remote.*.url:https://example.com/**"]
path = foo.inc
[remote "origin"]
url = https://example.com/git
</code>```

Body:
Meaning, having something like a per repo section [repo_url] that overrides global(not for a specific repo) options.

[core]
    filemode = false
    editor = notepad
[repo "example.com/repo1.git"]
    [core]
        filemode = true
        # editor = notepad
[repo "example.com/repo2.git"]
    [core]
        editor = vim
        # filemode = false

Is possible in git?

Note: I'm making a lot of clones(git clone) of repos which I would specify in such a global config

Body:
With Git 2.36 (Q2 2022), you will have another option than relying on a local folder: the conditional inclusion mechanism of configuration files using "[includeIf <condition>]" learns to base its decision on the URL of the remote repository the repository interacts with.

See commit 399b198, commit ed69e11 (18 Jan 2022) by Jonathan Tan (jhowtan).

(Merged by Junio C Hamano -- gitster -- in commit 13ce8f9, 09 Feb 2022)

config: include file if remote URL matches a glob

Signed-off-by: Jonathan Tan

Acked-by: Elijah Newren

This is a feature that supports config file inclusion conditional on whether the repo has a remote with a URL that matches a glob.

Similar to my previous work on remote-suggested hooks, the main motivation is to allow remote repo administrators to provide recommended configs in a way that can be consumed more easily (e.g. through a package installable by a package manager - it could, for example, contain a file to be included conditionally and a post-install script that adds the include directive to the system-wide config file).

In order to do this, Git reruns the config parsing mechanism upon noticing the first URL-conditional include in order to find all remote URLs, and these remote URLs are then used to determine if that first and all subsequent includes are executed.

Remote URLs are not allowed to be configured in any URL-conditionally-included file.

config now includes in its man page:

hasconfig:remote.*.url:

The data that follows this keyword is taken to
be a pattern with standard globbing wildcards and two
additional ones, **/ and /**, that can match multiple
components.

The first time this keyword is seen, the rest of
the config files will be scanned for remote URLs (without
applying any values).

If there exists at least one remote URL
that matches this pattern, the include condition is met.

Files included by this option (directly or indirectly) are not allowed
to contain remote URLs.

Note that unlike other includeIf conditions, resolving this condition
relies on information that is not yet known at the point of reading the
condition.

A typical use case is this option being present as a
system-level or global-level config, and the remote URL being in a
local-level config; hence the need to scan ahead when resolving this
condition.

In order to avoid the chicken-and-egg problem in which
potentially-included files can affect whether such files are potentially
included, Git breaks the cycle by prohibiting these files from affecting
the resolution of these conditions (thus, prohibiting them from
declaring remote URLs).

As for the naming of this keyword, it is for forwards compatibility with
a naming scheme that supports more variable-based include conditions,
but currently Git only supports the exact keyword described above.

config now includes in its man page:

; include only if a remote with the given URL exists (note
; that such a URL may be provided later in a file or in a
; file read after this file is read, as seen in this example)
[includeIf "hasconfig:remote.*.url:https://example.com/**"]
path = foo.inc
[remote "origin"]
url = https://example.com/git


问:
Join two 2D numpy array with one row over another
Two numpy arrays, lets say

```<code>a = np.array([[1,2], [3,4]])
b = np.array([[5,6], [7,8]])
</code>```

I would like to combine two arrays into one single array such that the results looks like below array

```<code>np.array([[1,2],
          [5,6],
          [3,4],
          [7,8]])
</code>```

I tried using concatenate, merge function, but cannot able to find pythonic way to solve this.
Is there is any in built function to solve my problem.

答:
You can column_stack + reshape:

```<code>out = np.column_stack((a,b)).reshape(4,2)
</code>```

Output:

```<code>array([[1, 2],
       [5, 6],
       [3, 4],
       [7, 8]])
</code>```

Body:
Two numpy arrays, lets say

a = np.array([[1,2], [3,4]])
b = np.array([[5,6], [7,8]])

I would like to combine two arrays into one single array such that the results looks like below array

np.array([[1,2],
          [5,6],
          [3,4],
          [7,8]])

I tried using concatenate, merge function, but cannot able to find pythonic way to solve this.
Is there is any in built function to solve my problem.

Body:
You can column_stack + reshape:

out = np.column_stack((a,b)).reshape(4,2)

Output:

array([[1, 2],
       [5, 6],
       [3, 4],
       [7, 8]])


答:
IIUC, you could stack on the first axis, and reshape:

```<code>np.stack((a,b), axis=1).reshape(-1,2)
</code>```

Or use np.c_ and reshape:

```<code>np.c_[a,b].reshape((-1,2))
</code>```

Output:

```<code>array([[1, 2],
       [5, 6],
       [3, 4],
       [7, 8]])
</code>```

Title: Join two 2D numpy array with one row over another

Body:
IIUC, you could stack on the first axis, and reshape:

np.stack((a,b), axis=1).reshape(-1,2)

Or use np.c_ and reshape:

np.c_[a,b].reshape((-1,2))

Output:

array([[1, 2],
       [5, 6],
       [3, 4],
       [7, 8]])


问:
Is possible to get the last string of an url as a param?
I cant get it with javascript URLSearchParams  function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

```<code>For ex:
mydomain.com/hello
mydomain.com/otherExample
</code>```

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

答:
In .htaccess file you can redirect to your index without change the URL.

After, you must handle the window.location.pathname as they have told in other messages.

.htaccess file

```<code>RewriteEngine On
RewriteRule ^(.*)$ index.html
</code>```

Body:
I cant get it with javascript URLSearchParams  function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

For ex:
mydomain.com/hello
mydomain.com/otherExample

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

Body:
In .htaccess file you can redirect to your index without change the URL.

After, you must handle the window.location.pathname as they have told in other messages.

.htaccess file

RewriteEngine On
RewriteRule ^(.*)$ index.html


问:
python3 get all .dart files from given directory
I would like to get all. .dart-files from a specific path.

This is what I've got so far:

```<code>import glob
import pathlib

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/*.dart", recursive=True):
    print(path)
</code>```

Now this is already giving me all the .dart files in the libPathString - directories. But inside there Ive got a couple of folders that have .dart files and these sub-directories can also have subfolders and so on.

I set recursive = true but that doesn't seem to achieve going through the sub-directories.

What am I missing here?

答:
I got it working! This is working as expected:</p>
```<code>import glob
import pathlib

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/**", recursive=True):
    if(".dart" in path):
        print(path)
</code>```

Body:
I would like to get all. .dart-files from a specific path.

This is what I've got so far:

import glob
import pathlib

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/*.dart", recursive=True):
    print(path)

Now this is already giving me all the .dart files in the libPathString - directories. But inside there Ive got a couple of folders that have .dart files and these sub-directories can also have subfolders and so on.

I set recursive = true but that doesn't seem to achieve going through the sub-directories.

What am I missing here?

Body:
I got it working! This is working as expected:

import glob
import pathlib

libPathString = str(pathlib.Path.cwd().parent.resolve())

for path in glob.glob(libPathString + "/**", recursive=True):
    if(".dart" in path):
        print(path)


问:
How to exchange form based on selected option in form select element?
Info: On the website I am programming no JavaScript or comparable criminal stuff is allowed! If code is run it is run on the server only, no visitor machine is abused.

I would like to change the form elements dynamically with CSS, based on a

<form><select></select></form>
```

element.

Means, CSS should detect the selection and exchange the opacity levels of the selectable forms as well as setting the content of other fields to None. That way it would be possible to change dynamically between different forms to be submitted.

However, if that is not possible, I would also be OK with replicating this <select> element in HTML as a lookalike, e.g. as a radio type HTML element.
But I would strongly prefer if I could just use a select field without much design work. I think it should work.

Thanks for potential help!

答:
OK, I think I just read the answer.
I was confused that there was no equivalent like :checked for options, since an option is more "selected" than "checked".

However, according to the following site, option:checked should also work.
https://developer.mozilla.org/en-US/docs/Web/CSS/:checked

Now I feel a bit silly. Apologies for asking this question :)

Body:
Info: On the website I am programming no JavaScript or comparable criminal stuff is allowed! If code is run it is run on the server only, no visitor machine is abused.

I would like to change the form elements dynamically with CSS, based on a

<form><select></select></form>

element.

Means, CSS should detect the selection and exchange the opacity levels of the selectable forms as well as setting the content of other fields to None. That way it would be possible to change dynamically between different forms to be submitted.

However, if that is not possible, I would also be OK with replicating this <select> element in HTML as a lookalike, e.g. as a radio type HTML element.
But I would strongly prefer if I could just use a select field without much design work. I think it should work.

Thanks for potential help!


问:
How to enforce implementation of nested class properties?
I'm trying to implement my own multi-language feature in Blazor WASM. Nothing fancy but I would like to make sure I don't forget to implement properties in a specific language. In TypeScript this would work with typing or interfacing objects. In C# the equivalent of such an object would be a class. I tried using interfaces and abstract classes in C# but I'm not getting the desired result.

The desired result would be for my code editor to hint when I forgot to implement a property. How should I proceed?

I could just put all properties directly into the Translation class to enforce their implementation but than I'll have one very long list of properties, I'd prefer to chop them up a bit.

```<code>    public class NavMenuProps
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";
    }

    public abstract class Translation
    {
        public abstract NavMenuProps NavMenu();
    }

    public class English : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps();
        }
    }

    public class Dutch : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps
            {
                FirstMenuHeader = "Honden",
                SecondMenuHeader = ""
            };
        }
    }

    public class French : Translation
    {
        public override NavMenuProps NavMenu()
        {
            throw new System.NotImplementedException();
        }
    }
</code>```

In TypeScript it would work like this:

```<code>
type TNavMenuProps = {
    firstMenuHeader: string;
    secondMenuHeader: string;
    thirdMenuHeader: string;
    ...
}

type TLoginPageProps = {
    firstLabel: string;
    secondLabel: string;
    ...
}

type TTranslation = {
    navMenu: TNavMenuProps;
    loginPage: TLoginPageProps;
    ...
}

const englishTranslations: TTranslation = {
    navMenu: {
        firstMenuHeader: "first";
        secondMenuHeader: "second";
        // Would complain I forgot "thirdMenuHeader".
    },
    loginPage: {
        firstLabel: "1st label";
        secondLabel: "2nd label";
    },
    ...
}

</code>```

答:
(Answer posted on behalf of the question author, to move it to the answer section).

The solution is not that much better than having just one giant interface but it does what I need, which is having manageable interfaces and the IDE telling me when I forgot to implement a field.

Solution inspired by the accepted answer:

```<code>
    public interface INavMenuProps
    {
        public string FirstMenuHeader { get; set; }
        public string SecondMenuHeader { get; set; }
        public string ThirdMenuHeader { get; set; }
    }

    public interface ILoginPageProps
    {
        public string FirstLabel { get; set; }
        public string SecondLabel { get; set; }
    }

    public interface Translation : INavMenuProps, ILoginPageProps
    {
    }

    public class English : Translation
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";

        public string FirstLabel { get; set; } = "1st label";
        public string SecondLabel { get; set; } = "2nd label";
    }

    public class Dutch : Translation
    {

    }

    public class French : Translation
    {

    }

</code>```

Body:
I'm trying to implement my own multi-language feature in Blazor WASM. Nothing fancy but I would like to make sure I don't forget to implement properties in a specific language. In TypeScript this would work with typing or interfacing objects. In C# the equivalent of such an object would be a class. I tried using interfaces and abstract classes in C# but I'm not getting the desired result.

The desired result would be for my code editor to hint when I forgot to implement a property. How should I proceed?

I could just put all properties directly into the Translation class to enforce their implementation but than I'll have one very long list of properties, I'd prefer to chop them up a bit.

    public class NavMenuProps
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";
    }

    public abstract class Translation
    {
        public abstract NavMenuProps NavMenu();
    }

    public class English : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps();
        }
    }

    public class Dutch : Translation
    {
        public override NavMenuProps NavMenu()
        {
            return new NavMenuProps
            {
                FirstMenuHeader = "Honden",
                SecondMenuHeader = ""
            };
        }
    }

    public class French : Translation
    {
        public override NavMenuProps NavMenu()
        {
            throw new System.NotImplementedException();
        }
    }

In TypeScript it would work like this:

type TNavMenuProps = {
    firstMenuHeader: string;
    secondMenuHeader: string;
    thirdMenuHeader: string;
    ...
}

type TLoginPageProps = {
    firstLabel: string;
    secondLabel: string;
    ...
}

type TTranslation = {
    navMenu: TNavMenuProps;
    loginPage: TLoginPageProps;
    ...
}

const englishTranslations: TTranslation = {
    navMenu: {
        firstMenuHeader: "first";
        secondMenuHeader: "second";
        // Would complain I forgot "thirdMenuHeader".
    },
    loginPage: {
        firstLabel: "1st label";
        secondLabel: "2nd label";
    },
    ...
}

Body:
(Answer posted on behalf of the question author, to move it to the answer section).

The solution is not that much better than having just one giant interface but it does what I need, which is having manageable interfaces and the IDE telling me when I forgot to implement a field.

Solution inspired by the accepted answer:

    public interface INavMenuProps
    {
        public string FirstMenuHeader { get; set; }
        public string SecondMenuHeader { get; set; }
        public string ThirdMenuHeader { get; set; }
    }

    public interface ILoginPageProps
    {
        public string FirstLabel { get; set; }
        public string SecondLabel { get; set; }
    }

    public interface Translation : INavMenuProps, ILoginPageProps
    {
    }

    public class English : Translation
    {
        public string FirstMenuHeader { get; set; } = "Dogs";
        public string SecondMenuHeader { get; set; } = "Facilities";
        public string ThirdMenuHeader { get; set; } = "Profile";

        public string FirstLabel { get; set; } = "1st label";
        public string SecondLabel { get; set; } = "2nd label";
    }

    public class Dutch : Translation
    {

    }

    public class French : Translation
    {

    }


问:
Enterprise applications in .NET EF 4.1 CodeFirst - Have you seen any?
EF 4.1 CodeFirst looks great. It works and sells wonderfuly with basic examples that have one or two joins, but what about larger applications? Did anybody work on a large application where domain and data access layers were implemented with EF 4.1 code first?  Did it work? Was it as easy and smooth as examples on asp.net site? I'm mainly working on MVC applications, where there is no change tracking. So far I have been using LINQ-to-SQL, which worked well with some extra mapping code.

Thank you

答:
I'm in the later stages of developing a web application that is fairly complex with EF 4.1 CodeFirst (well its more complex than most examples).  I don't pretend to be an expert on code first so others may have different opinions.

I used a domain driven approach along with the repository pattern.  The database created by code first worked well though I had to manually optimize the database and add indexes etc.  Did have an issue bolting on mvc-profiler but nothing drastic.

There was a learning curve but I reckon that was more down to my lack of knowledge about code-first than anything intrinsically difficult about it.  When we started developing the app the ability to recreate a db and seed it sped things up at the start.  Though we have disabled that now and any db changes are made manually and the code is updated.

So for me code first worked well, I like this approach for new applications and it wasnt too difficult to get up and running (lots of reading up).


问:
getting last three lines of python output assigned to 3 variables in bash
I have a python script that outputs a long list of files.

The script is ran from bash, and at the end i need to assign the last three files each to a specific variables.

I'm able to capture the output into a bash Variable, but then when I try to pipe it to 'tail' command, it seems to be one line only?

I've tried tips i've seen around, but can't seem to figure out how to work on an individual line basis with output.

it seems that any python output will be interpreted as one line?

echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(i)")

# check output
echo "$OUTPUT"

variable3=$(echo $OUTPUT | tail -1)

echo "VARIABLE CAPTURED"
echo $variable3
```
<p>here is what i get:
<img src="https://i.stack.imgur.com/giove.png" alt="enter image description here" /></p>
<p>But I actually need to capture variable1 as 3rd line from end, variable2 as 2nd line from end and variable3 as first line from the end</p>
<p>So that in the above example at the end the desired result is:</p>
```variable1 = 2
variable2 = 3
variable3 = 4
```

in order to pass these variables to next stage of the script...

答:
You have to get quoting right, this will assign 4 to variable3:

```<code>variable3="$(echo "$OUTPUT" | tail -1)"
echo "$variable3"
</code>```

Similarly, to get variable2:

```<code>variable2="$(echo "$OUTPUT" | tail -2 | head -1)"
</code>```

And variable1:

```<code>variable1="$(echo "$OUTPUT" | tail -3 | head -1)"
</code>```

To sum up, your script should be:

```<code>#!/usr/bin/env bash

echo "TESTING sample multi-line python output"
OUTPUT="$(python -c "for i in range(5): print(i)")"

# check output
echo "$OUTPUT"

variable3="$(echo "$OUTPUT" | tail -1)"
variable2="$(echo "$OUTPUT" | tail -2 | head -1)"
variable1="$(echo "$OUTPUT" | tail -3 | head -1)"

echo variable1: "$variable1"
echo variable2: "$variable2"
echo variable3: "$variable3"
</code>```

Body:
I have a python script that outputs a long list of files.

The script is ran from bash, and at the end i need to assign the last three files each to a specific variables.

I'm able to capture the output into a bash Variable, but then when I try to pipe it to 'tail' command, it seems to be one line only?

I've tried tips i've seen around, but can't seem to figure out how to work on an individual line basis with output.

it seems that any python output will be interpreted as one line?

echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(i)")

# check output
echo "$OUTPUT"

variable3=$(echo $OUTPUT | tail -1)

echo "VARIABLE CAPTURED"
echo $variable3

here is what i get:

But I actually need to capture variable1 as 3rd line from end, variable2 as 2nd line from end and variable3 as first line from the end

So that in the above example at the end the desired result is:

variable1 = 2
variable2 = 3
variable3 = 4

in order to pass these variables to next stage of the script...

Body:
You have to get quoting right, this will assign 4 to variable3:

variable3="$(echo "$OUTPUT" | tail -1)"
echo "$variable3"

Similarly, to get variable2:

variable2="$(echo "$OUTPUT" | tail -2 | head -1)"

And variable1:

variable1="$(echo "$OUTPUT" | tail -3 | head -1)"

To sum up, your script should be:

#!/usr/bin/env bash

echo "TESTING sample multi-line python output"
OUTPUT="$(python -c "for i in range(5): print(i)")"

# check output
echo "$OUTPUT"

variable3="$(echo "$OUTPUT" | tail -1)"
variable2="$(echo "$OUTPUT" | tail -2 | head -1)"
variable1="$(echo "$OUTPUT" | tail -3 | head -1)"

echo variable1: "$variable1"
echo variable2: "$variable2"
echo variable3: "$variable3"


问:
What is the substitute for getHibernateTemplate().find() as it is deprecated?
While coding we encountered a deprication warning for getHibernateTemplate().find(); can any one suggest another method or substitute code for this issue.
We are using SpringBoot and MYSQL database.</p>
```<code>String sQuery = "Select R.sPhone from Registration R where R.sPhone = " + iPhone+ "AND R.sCountry_Code= "+sCountry_Code;
        List<Object[]> resultList = (List<Object[]>) getHibernateTemplate().find(sQuery);

</code>```

答:
```<code>List<Object> list = (List<Object>) currentSession().createQuery("your query").list();
List<Object> list = (List<Object>) currentSession().createQuery("Select R.sPhone from Registration R where R.sPhone = :sPhone ").setParameter("sPhone ", sPhone ).list();
</code>```

Body:
While coding we encountered a deprication warning for getHibernateTemplate().find(); can any one suggest another method or substitute code for this issue.
We are using SpringBoot and MYSQL database.

String sQuery = "Select R.sPhone from Registration R where R.sPhone = " + iPhone+ "AND R.sCountry_Code= "+sCountry_Code;
        List<Object[]> resultList = (List<Object[]>) getHibernateTemplate().find(sQuery);


问:
CSS problem, 100% width keeps moving out of position
I'm currently working on this website,
http://no-illusions.nl
It's going fine but I found a pretty stupid thing that I can't resolve.

I have an div (wrapper) with an width of 500px and inside I have different div's containing images and text. Now the problem is that the text is dynamic in width, on some parts it could be 200px width and on some pages it could be 350px.

So I put the width on 100% but now the part just floats underneath where I want it!

This is how it should look,
![how it should look][1]

But this is how it looks,

I hope you guys can give me a push in the right direction.

答:
Remember that relative sizes are relative to the containing element. If you say width: 50%, you'll get an element that's 1/2 the width of its container. So your saying width: 100% makes the text div take 100% of the container's width, and it becomes 500px as well.

You can put the image inside the text div and float it. With appropriate margins/padding, the text will wrap around the image, and you'd get something like:

```<code>imgimgimg   text text text
imgimgimg   text text text
imgimgimg   text text text

text text text text text
text text text text text
</code>```

The basic html structure woul be:

```<code><div style="width: 500px;">
    <div style="float: left; margin: 5px;"><img src="..."></div>
    text text text text text
</div>
</code>```

otherwise you'd need to go with fixed with divs, and dynamically change the text div's width based on whether there's an image present or not. if (has image) { width: 350} else { width: 500} type of thing.

Body:
Remember that relative sizes are relative to the containing element. If you say width: 50%, you'll get an element that's 1/2 the width of its container. So your saying width: 100% makes the text div take 100% of the container's width, and it becomes 500px as well.

You can put the image inside the text div and float it. With appropriate margins/padding, the text will wrap around the image, and you'd get something like:

imgimgimg   text text text
imgimgimg   text text text
imgimgimg   text text text

text text text text text
text text text text text

The basic html structure woul be:

<div style="width: 500px;">
    <div style="float: left; margin: 5px;"><img src="..."></div>
    text text text text text
</div>

otherwise you'd need to go with fixed with divs, and dynamically change the text div's width based on whether there's an image present or not. if (has image) { width: 350} else { width: 500} type of thing.


答:
So I can't explain why this goes that way, but it seems that pythons print separates lines by '\n' and tail separates lines by \n\r. So I got this working by changing some lines

```<code>echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(str(i) + '\n\r', end='')")

# check output
echo "$OUTPUT"

variable3=$(echo $OUTPUT | tail -1)

echo "VARIABLE CAPTURED"
echo $variable3
</code>```

This will result in

```<code>TESTING sample multi-line python output
0
1
2
3
4

VARIABLE CAPTURED
4
</code>```

Title: getting last three lines of python output assigned to 3 variables in bash

Body:
So I can't explain why this goes that way, but it seems that pythons print separates lines by '\n' and tail separates lines by \n\r. So I got this working by changing some lines

echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(str(i) + '\n\r', end='')")

# check output
echo "$OUTPUT"

variable3=$(echo $OUTPUT | tail -1)

echo "VARIABLE CAPTURED"
echo $variable3

This will result in

TESTING sample multi-line python output
0
1
2
3
4

VARIABLE CAPTURED
4


问:
python json how to write data one under the other instead of side by side
```<code>        self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

        with open('data.json', 'a+') as f:
            f.seek(0)
            json.dump(str(user_id), f, indent = 4 )
</code>```

here, it writes user ID that created channel.

Output :

```<code>"332115091338297344""323516141777715202"
</code>```

it writes the ID of more than one user, but how can I make it type from one under the other instead of side by side

答:
As quamrana say, json is a specific format where you can't just add a simple string.

A good way to store id in json format shoul be to create an array of id in your json like that :

```<code>{
    "ids": [
        1,
        2,
        3
    ]
}
</code>```

To do that init your json file with the id's array empty.
Then in python, get the array, append new id and rewrites all the file.

```<code>new_id = 444
with open('data.json', 'r+') as f:
    # read json datas
    json_datas = json.load(f)
    # get ids array
    ids = json_datas["ids"]
    # add new id
    ids.append(new_id)
    # rebuild our json
    json_new_datas = json.dumps({"id":ids})
    f.seek(0)
    # write json into file
    f.write(json_new_datas)
</code>```

Body:
        self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

        with open('data.json', 'a+') as f:
            f.seek(0)
            json.dump(str(user_id), f, indent = 4 )

here, it writes user ID that created channel.

Output :

"332115091338297344""323516141777715202"

it writes the ID of more than one user, but how can I make it type from one under the other instead of side by side

Body:
As quamrana say, json is a specific format where you can't just add a simple string.

A good way to store id in json format shoul be to create an array of id in your json like that :

{
    "ids": [
        1,
        2,
        3
    ]
}

To do that init your json file with the id's array empty.
Then in python, get the array, append new id and rewrites all the file.

new_id = 444
with open('data.json', 'r+') as f:
    # read json datas
    json_datas = json.load(f)
    # get ids array
    ids = json_datas["ids"]
    # add new id
    ids.append(new_id)
    # rebuild our json
    json_new_datas = json.dumps({"id":ids})
    f.seek(0)
    # write json into file
    f.write(json_new_datas)


问:
Use Tomcat Library in Webapp project
I have a web application that uses the Tomcat library. I have not copied the jars from the Tomcat library into the web-inf/lib directory.

Now when I run an ant build / testNG class, it throws an error since the concerned jars are not present under the web-inf/lib directory.

Is there any way (configuration) that I can use the Tomcat library for the running the ant build  / testNG classes.

Thanks in advance,

Vivek

答:
In the <testng> task, just provide the tomcat libraries as additional classpath elements.

```<code><TestNG>
    <classpath>
        <pathelement path="${classpath}"/>
        <pathelement location="path/to/tomcat/lib.jar"/>
    </classpath>
</TestNG>
</code>```

Title: Use Tomcat Library in Webapp project

Body:
In the <testng> task, just provide the tomcat libraries as additional classpath elements.

<TestNG>
    <classpath>
        <pathelement path="${classpath}"/>
        <pathelement location="path/to/tomcat/lib.jar"/>
    </classpath>
</TestNG>


问:
Splitting QString on spaces and keeping the space in QList - best or 'canonical' way
As in the title, I would like to ask what is the best way to split a QString on spaces and - where relevant - keep the spaces as parts of the resulting QList elements. I'm interested in the most efficient method of doing this, considering modern C++ and Qt >= 6.0 paradigms.

For the purpose of this question I will replace normal spaces with '_' - I hope it makes the problem easier to understand.

Imagine the following code:

```<code>QString myString = "This_is_an_exemplary_text";
for (auto word : myString.split('_')) {
   qDebug() << word;
}
</code>```

The output of the code would be:

"This"
"is"
"an"
"exemplary"
"text"

Information about the spaces was lost in the splitting process. Is there a smart way to preserve it, and have the following output:

"This_"
"is_"
"an_"
"exemplary_"
"text"

Any suggestion would be welcomed.

答: Consider myString.split(QRegularExpression("(?<= )") The regular expression says "an empty substring preceded by a space", using the positive look-behind syntax.

Body:
As in the title, I would like to ask what is the best way to split a QString on spaces and - where relevant - keep the spaces as parts of the resulting QList elements. I'm interested in the most efficient method of doing this, considering modern C++ and Qt >= 6.0 paradigms.

For the purpose of this question I will replace normal spaces with '_' - I hope it makes the problem easier to understand.

Imagine the following code:

QString myString = "This_is_an_exemplary_text";
for (auto word : myString.split('_')) {
   qDebug() << word;
}

The output of the code would be:

"This"
"is"
"an"
"exemplary"
"text"

Information about the spaces was lost in the splitting process. Is there a smart way to preserve it, and have the following output:

"This_"
"is_"
"an_"
"exemplary_"
"text"

Any suggestion would be welcomed.


问:
How to modify custom.css styling on Docusaurus items
I am looking for the syntax needed to reference an item in Docusaurus allowing me to modify the background color/text color of a collapsed item.

Example image
enter image description here

How exactly can I reference docusaurus code to modify the coloring of these bubbles?

答:
it is not clear what exactly you are asking.

You can find how to add styling and layout here: https://docusaurus.io/docs/styling-layout

You can create custom react components and add them to the documentation to completely customise the html element. Alternatively you could inspect the element to find the class used by docusaurus to change the css of the elements you want.


问:
How to inject SVG icon sprites in Angular component HTML DOM?
I am building an Angular application (Angular 4/5/6) and would like to use SVG sprites in my component template.

Question:
Assuming I already have my SVG icon sprite generated (icons.svg), how can I get Angular to inject/import my SVG icon sprite into my component's template?

Is there a way to inject/import my SVG icon sprite into my component without having to use any 3rd party modules/directives and do it natively with Angular itself?

Background/Issue:

As discussed in this article, icons.svg file would contain all the SVG icons defined as <symbol>. Then I can render selected icons in my HTML using <use> assuming the icons.svg is injected in the DOM.

I generated SVG sprites using IcoMoon app, and saved the icons.svg into my Angular application. Below is my sample Angular component (app.component.ts) in which I am trying to inject/import the icons.svg file and trying to render the SVG icons in my HTML. However, Angular is not rending my SVG icons. I seems I am incorrectly injecting the SVG icon sprite file.

Updates:

I am already aware of a similar question, SVG icon system with angular-cli, where the suggested answer was to use the Node module svg-sprite to generate a SVG sprites using the CSS mode. However, this is NOT what I am asking. I am NOT trying to generate the SVG sprites. I am trying get Angular components to be aware of my SVG sprite, icons.svg, and get it to render them in the HTML whenever I make use of them.

A solution was suggested,https://stackoverflow.com/a/50460361/4988010, to generate a CSS font from the SVG sprite. I feel this is NOT a feasible solution and instead is a "workaround" to not being able to use the SVG sprite.

app.component.ts: Live example on StackBlitz: https://stackblitz.com/edit/angular-bbr2kh?file=src/app/app.component.ts

```<code>import { Component } from '@angular/core';
// import `./icons.svg`; // This import method doesn't work

@Component({
  selector: 'my-app',
  template: `

   <!-- This import method doesn't work -->
   <!-- <script src="./icons.svg"></script>  -->

  <p>
  Hello this is a sample Angular 6 component.
  </p>

  <p>Testing to see if SVG icon sprite import works. See below if icons appear. </p>
  <p>Icon (home): <svg class="icon icon-home"><use xlink:href="#icon-home"></use></svg> </p>
  <p>Icon (rocket): <svg class="icon icon-rocket"><use xlink:href="#icon-rocket"></use></svg> </p>
  <p>Icon (wifi): <svg class="icon icon-connection"><use xlink:href="#icon-connection"></use></svg>

  <!-- This import method doesn't work -->
  <!-- <p>Icon (home): <svg class="icon icon-home"><use xlink:href="./icons.svg#icon-home"></use></svg> </p>-->

   </p>
  `,
  styles: [`

  .icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  stroke-width: 0;
  stroke: currentColor;
  fill: currentColor;
  }

  `]
})
export class AppComponent {
}
</code>```

答:
I struck a similar issue and solved using a similar technique to some of the answers given. Using this as needed with optional height and width setting ...

```<code><app-icon icon="filter" width="15" height="15"></app-icon>
</code>```

or

```<code><app-icon icon="filter"></app-icon>
</code>```

The component has only two icons (all I am presently using) in icon.component.svg:

```<code><!-- https://icons.getbootstrap.com/ -->
<div [ngSwitch]="icon">
    <svg *ngSwitchCase="'filter'" xmlns="http://www.w3.org/2000/svg" [attr.width]="width" [attr.height]="height" fill="currentColor" viewBox="0 0 16 16">
        <path d="M1.5 1.5A.5.5 0 0 1 2 1h12a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.128.334L10 8.692V13.5a.5.5 0 0 1-.342.474l-3 1A.5.5 0 0 1 6 14.5V8.692L1.628 3.834A.5.5 0 0 1 1.5 3.5v-2zm1 .5v1.308l4.372 4.858A.5.5 0 0 1 7 8.5v5.306l2-.666V8.5a.5.5 0 0 1 .128-.334L13.5 3.308V2h-11z"/>
    </svg>
    <svg *ngSwitchCase="'tags'" xmlns="http://www.w3.org/2000/svg" [attr.width]="width" [attr.height]="height" fill="currentColor" viewBox="0 0 16 16">
        <path d="M3 2v4.586l7 7L14.586 9l-7-7H3zM2 2a1 1 0 0 1 1-1h4.586a1 1 0 0 1 .707.293l7 7a1 1 0 0 1 0 1.414l-4.586 4.586a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 2 6.586V2z"/>
        <path d="M5.5 5a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm0 1a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM1 7.086a1 1 0 0 0 .293.707L8.75 15.25l-.043.043a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 0 7.586V3a1 1 0 0 1 1-1v5.086z"/>
    </svg>
</div>
</code>```

and icon.component.ts:

```<code>import { Component, Input, OnInit } from '@angular/core';

@Component({
    selector: 'app-icon',
    templateUrl: './icon.component.svg',
    styleUrls: []
})
export class IconComponent implements OnInit{
    @Input() icon: any
    @Input() width?: any
    @Input() height?: any

    ngOnInit(): void {
        if (typeof this.width != 'string') {
            this.width = '20'
        }
        if (typeof this.height != 'string') {
            this.height = '20'
        }
    }
}
</code>```

No need to include an entire icon library set, with reasonably simple reuse within the application.

Body:
I am building an Angular application (Angular 4/5/6) and would like to use SVG sprites in my component template.

Question:
Assuming I already have my SVG icon sprite generated (icons.svg), how can I get Angular to inject/import my SVG icon sprite into my component's template?

Is there a way to inject/import my SVG icon sprite into my component without having to use any 3rd party modules/directives and do it natively with Angular itself?

Background/Issue:

As discussed in this article, icons.svg file would contain all the SVG icons defined as <symbol>. Then I can render selected icons in my HTML using <use> assuming the icons.svg is injected in the DOM.

I generated SVG sprites using IcoMoon app, and saved the icons.svg into my Angular application. Below is my sample Angular component (app.component.ts) in which I am trying to inject/import the icons.svg file and trying to render the SVG icons in my HTML. However, Angular is not rending my SVG icons. I seems I am incorrectly injecting the SVG icon sprite file.

Updates:

I am already aware of a similar question, SVG icon system with angular-cli, where the suggested answer was to use the Node module svg-sprite to generate a SVG sprites using the CSS mode. However, this is NOT what I am asking. I am NOT trying to generate the SVG sprites. I am trying get Angular components to be aware of my SVG sprite, icons.svg, and get it to render them in the HTML whenever I make use of them.

A solution was suggested,https://stackoverflow.com/a/50460361/4988010, to generate a CSS font from the SVG sprite. I feel this is NOT a feasible solution and instead is a "workaround" to not being able to use the SVG sprite.

app.component.ts: Live example on StackBlitz: https://stackblitz.com/edit/angular-bbr2kh?file=src/app/app.component.ts

import { Component } from '@angular/core';
// import `./icons.svg`; // This import method doesn't work

@Component({
  selector: 'my-app',
  template: `

  Hello this is a sample Angular 6 component.

Testing to see if SVG icon sprite import works. See below if icons appear.

Icon (home): <svg class="icon icon-home"><use xlink:href="#icon-home"></use></svg>

Icon (rocket): <svg class="icon icon-rocket"><use xlink:href="#icon-rocket"></use></svg>

Icon (wifi): <svg class="icon icon-connection"><use xlink:href="#icon-connection"></use></svg>

  `,
  styles: [`

  .icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  stroke-width: 0;
  stroke: currentColor;
  fill: currentColor;
  }

  `]
})
export class AppComponent {
}

Body:
I struck a similar issue and solved using a similar technique to some of the answers given. Using this as needed with optional height and width setting ...

<app-icon icon="filter" width="15" height="15"></app-icon>

or

<app-icon icon="filter"></app-icon>

The component has only two icons (all I am presently using) in icon.component.svg:

<!-- https://icons.getbootstrap.com/ -->
<div [ngSwitch]="icon">
    <svg *ngSwitchCase="'filter'" xmlns="http://www.w3.org/2000/svg" [attr.width]="width" [attr.height]="height" fill="currentColor" viewBox="0 0 16 16">
        <path d="M1.5 1.5A.5.5 0 0 1 2 1h12a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.128.334L10 8.692V13.5a.5.5 0 0 1-.342.474l-3 1A.5.5 0 0 1 6 14.5V8.692L1.628 3.834A.5.5 0 0 1 1.5 3.5v-2zm1 .5v1.308l4.372 4.858A.5.5 0 0 1 7 8.5v5.306l2-.666V8.5a.5.5 0 0 1 .128-.334L13.5 3.308V2h-11z"/>
    </svg>
    <svg *ngSwitchCase="'tags'" xmlns="http://www.w3.org/2000/svg" [attr.width]="width" [attr.height]="height" fill="currentColor" viewBox="0 0 16 16">
        <path d="M3 2v4.586l7 7L14.586 9l-7-7H3zM2 2a1 1 0 0 1 1-1h4.586a1 1 0 0 1 .707.293l7 7a1 1 0 0 1 0 1.414l-4.586 4.586a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 2 6.586V2z"/>
        <path d="M5.5 5a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm0 1a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM1 7.086a1 1 0 0 0 .293.707L8.75 15.25l-.043.043a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 0 7.586V3a1 1 0 0 1 1-1v5.086z"/>
    </svg>
</div>

and icon.component.ts:

import { Component, Input, OnInit } from '@angular/core';

@Component({
    selector: 'app-icon',
    templateUrl: './icon.component.svg',
    styleUrls: []
})
export class IconComponent implements OnInit{
    @Input() icon: any
    @Input() width?: any
    @Input() height?: any

    ngOnInit(): void {
        if (typeof this.width != 'string') {
            this.width = '20'
        }
        if (typeof this.height != 'string') {
            this.height = '20'
        }
    }
}

No need to include an entire icon library set, with reasonably simple reuse within the application.