问:
How to connect variable number of segments of heat exchanger model?
I write a code in python for ANSA modeling software, which, based on given parameters, will create a model of heat exchanger. You can see the example of the model below. The blue colored elements represent water, the grey ones represent the pipe, the brown one represent air. But there can be any number of rows and columns in the exchanger. I got this covered so far. I got some default segment, then I set it desired size based on given parameters and then I copy the segment to create x rows and y columns.

But now I need to connect these segments, so there will be continuous pipe with water flowing (with one input and one output), as seen on the second image. What you can see I created manually, but I need to be able to create these connections parametrically by script.

I have absolutely no idea how to do this. To be precise, I can´t figure out the logic of the code. The command that creates the elements is not a problem. Since there can be any number of rows and columns, the problem is not only how to connect the segments, but also in what direction should the connections lead and where should be the input and output.
I will provide more details if needed. And my code is pretty long so far and uses special commands for the modeling software, so I guess it wouldn´t be much help. But I will include it in case of need. But once again - I don´t need specific commands, but only general logic of the code.

答:
This problem is equivalent to finding a Hamiltonian path from the "input" node to the "output" node in a graph that represents the two-dimensional grid (i.e. neighboring nodes are horizontally and vertically connected). This problem is NP-complete, see this article for more information.

The constraint that each connection of two nodes in the grid reverses the flow of the water ("into the page" or "out of the page") simply puts a constraint on the total number of nodes in the grid. An odd number of connections will reverse the flow from input to output node while an even number will maintain it. Since both input and output pipe should be on the same side of the device, the flow must be reversed, i.e an odd number of connections must be made. Since the path should visit every node in the grid, this means that the grid must consist of an even number of nodes (the number of connections is one less than the number of nodes). Hence, if nrows*ncols is even then this constraint will be automatically satisfied and if nrows*nocls is odd then it cannot be satisfied.

If the size of the grid is not too large, one can try to find such a Hamiltonian path via brute force search, e.g. using the networkx library:

from typing import Tuple

import matplotlib.pyplot as plt
import networkx as nx
from networkx.algorithms.simple_paths import all_simple_paths
import numpy as np

def find_hamiltonian_paths(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    edges = []
    for r in range(nrows):
        for c in range(ncols):
            node = r*ncols + c
            if r > 0:
                edges.append((node, (r-1)*ncols + c))
            if r < nrows-1:
                edges.append((node, (r+1)*ncols + c))
            if c > 0:
                edges.append((node, r*ncols + c-1))
            if c < ncols-1:
                edges.append((node, r*ncols + c+1))
    G = nx.Graph(edges)
    for path in all_simple_paths(G, source[0]*ncols+source[1], target[0]*ncols+target[1]):
        if len(path) == nrows*ncols:
            yield path

# Example
nrows, ncols = 4, 6
source = 1, 2
target = 2, 4
path = next(find_hamiltonian_paths(nrows, ncols, source, target))

fig, ax = plt.subplots()
ax.set_xlim([-1, ncols])
ax.set_ylim([-1, nrows])
ax.set_xticks(np.arange(ncols))
ax.set_yticks(np.arange(nrows))
ax.set_yticklabels(np.arange(nrows)[::-1])
ax.grid(lw=0.3)
for pos in ('top', 'right', 'bottom', 'left'):
    ax.spines[pos].set_visible(False)
x, y = [], []
for node in path:
    r, c = divmod(node, ncols)
    x.append(c)
    y.append(nrows-1 - r)
ax.plot(x, y, '-')
ax.plot([x[0], x[-1]], [y[0], y[-1]], 'o', ms=10)
plt.show()
```
<p>Which produces the following path:</p>
<p><img src="https://i.stack.imgur.com/gUZdn.png" alt="Example" /></p>
<h1>Special cases</h1>
<h2>1) Even number of rows and input at left upper corner, output at left lower corner</h2>
<p>(This generalizes to any other corner as well, as long as input and output nodes lie on a straight line and are separated by an even number of rows or columns.)</p>
<p>We can connect the <code>(0,0)</code> node to the <code>(1,0)</code> node by connecting the entire first row left to right, then moving down into the second row and connect it right to left. By continuing this pattern, we can connect any number N of row pairs (i.e. total number of rows is 2*N even).</p>
<pre class="lang-py prettyprint-override"><code>def special_case_1(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    assert source == (0, 0) and target == (nrows-1, 0)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    for r in range(1, len(nodes), 2):
        nodes[r] = nodes[r, ::-1]
    yield nodes.ravel()

# Example
nrows, ncols = 6, 5
source = 0, 0
target = 5, 0
path = next(special_case_1(nrows, ncols, source, target))
</code>```

2) Even number of rows and input at left upper corner, output directly below input

(Similar to case (1), this generalizes to any corner.)

From case (1) we know how to fully connect a (2*M, N) grid. Now case (2) can be split into two sub-problems, namely the first column and the remainder of the grid (denoted with R). We can connect R in a similar fashion as for case (1). So all we need to do is to connect the first column to R. Connecting the input node at (0,0) to the left upper corner of R  at (0,1) is trivial. Then we can connect the left lower corner of R to the bottom node of the first column and then move all the way up to the output node at (1,0).

def special_case_2(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    assert source == (0, 0) and target == (1, 0)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    column = nodes[:, 0]
    nodes = nodes[:, 1:]
    for r in range(1, len(nodes), 2):
        nodes[r] = nodes[r, ::-1]
    yield [0, *nodes.ravel(), *column[:0:-1]]

# Example
nrows, ncols = 6, 5
source = 0, 0
target = 1, 0
path = next(special_case_2(nrows, ncols, source, target))
```
<p><img src="https://i.stack.imgur.com/N4aFj.png" alt="Special case 2" /></p>
<h2>3) Even number of rows and columns, input and output located next to each other at the center of one the edges of the grid</h2>
<p>For the sake of the example, let's assume they are located at the center of the top edge. We can split this problem into two sub-problems, left and right, and connect both input and output to their corresponding node on the bottom row in a fashion similar to case (1). Then, connecting the two problems amounts to simply connecting these two nodes.</p>
<pre class="lang-py prettyprint-override"><code>def special_case_3(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    assert source == (0, ncols//2-1) and target == (0, ncols//2)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    left = nodes[:, :ncols//2]
    right = nodes[:, ncols//2:]
    for r in range(len(nodes)):
        if r % 2 == 0:
            left[r] = left[r, ::-1]
        else:
            right[r] = right[r, ::-1]
    yield [*left.ravel(), *right.ravel()[::-1]]

# Example
nrows, ncols = 6, 8
source = 0, 3
target = 0, 4
path = next(special_case_3(nrows, ncols, source, target))
</code>```

4) Input and output next to each other in the center of the grid

For this we require only that the number of columns is even. The procedure is best explained by looking at the sketch and code and especially at the example plot below:

def special_case_4(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    r2, c2 = nrows//2, ncols//2
    assert source == (r2, c2-1) and target == (r2, c2)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    top = nodes[:r2]
    for c in range(0, top.shape[1], 2):
        top[:, c] = top[::-1, c]
    bottom = nodes[r2+1:-1, 1:-1]
    for c in range(1, bottom.shape[1], 2):
        bottom[:, c] = bottom[::-1, c]
    yield [
        *nodes[r2, c2-1::-1],    # (1)
        *top.T.ravel(),          # (2)
        *nodes[r2:, -1],         # (3)
        *nodes[-1, -2::-1],      # (4)
        *nodes[:r2:-1, 0],       # (5)
        *bottom.T.ravel(),       # (6)
        *nodes[r2, -2:c2-1:-1],  # (7)
    ]

# Example
nrows, ncols = 7, 8
source = 3, 3
target = 3, 4
path = next(special_case_4(nrows, ncols, source, target))
```

Body:
This problem is equivalent to finding a Hamiltonian path from the "input" node to the "output" node in a graph that represents the two-dimensional grid (i.e. neighboring nodes are horizontally and vertically connected). This problem is NP-complete, see this article for more information.

The constraint that each connection of two nodes in the grid reverses the flow of the water ("into the page" or "out of the page") simply puts a constraint on the total number of nodes in the grid. An odd number of connections will reverse the flow from input to output node while an even number will maintain it. Since both input and output pipe should be on the same side of the device, the flow must be reversed, i.e an odd number of connections must be made. Since the path should visit every node in the grid, this means that the grid must consist of an even number of nodes (the number of connections is one less than the number of nodes). Hence, if nrows*ncols is even then this constraint will be automatically satisfied and if nrows*nocls is odd then it cannot be satisfied.

If the size of the grid is not too large, one can try to find such a Hamiltonian path via brute force search, e.g. using the networkx library:

from typing import Tuple

import matplotlib.pyplot as plt
import networkx as nx
from networkx.algorithms.simple_paths import all_simple_paths
import numpy as np

def find_hamiltonian_paths(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    edges = []
    for r in range(nrows):
        for c in range(ncols):
            node = r*ncols + c
            if r > 0:
                edges.append((node, (r-1)*ncols + c))
            if r < nrows-1:
                edges.append((node, (r+1)*ncols + c))
            if c > 0:
                edges.append((node, r*ncols + c-1))
            if c < ncols-1:
                edges.append((node, r*ncols + c+1))
    G = nx.Graph(edges)
    for path in all_simple_paths(G, source[0]*ncols+source[1], target[0]*ncols+target[1]):
        if len(path) == nrows*ncols:
            yield path

# Example
nrows, ncols = 4, 6
source = 1, 2
target = 2, 4
path = next(find_hamiltonian_paths(nrows, ncols, source, target))

fig, ax = plt.subplots()
ax.set_xlim([-1, ncols])
ax.set_ylim([-1, nrows])
ax.set_xticks(np.arange(ncols))
ax.set_yticks(np.arange(nrows))
ax.set_yticklabels(np.arange(nrows)[::-1])
ax.grid(lw=0.3)
for pos in ('top', 'right', 'bottom', 'left'):
    ax.spines[pos].set_visible(False)
x, y = [], []
for node in path:
    r, c = divmod(node, ncols)
    x.append(c)
    y.append(nrows-1 - r)
ax.plot(x, y, '-')
ax.plot([x[0], x[-1]], [y[0], y[-1]], 'o', ms=10)
plt.show()

Which produces the following path:

Special cases

1) Even number of rows and input at left upper corner, output at left lower corner

(This generalizes to any other corner as well, as long as input and output nodes lie on a straight line and are separated by an even number of rows or columns.)

We can connect the (0,0) node to the (1,0) node by connecting the entire first row left to right, then moving down into the second row and connect it right to left. By continuing this pattern, we can connect any number N of row pairs (i.e. total number of rows is 2*N even).

def special_case_1(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    assert source == (0, 0) and target == (nrows-1, 0)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    for r in range(1, len(nodes), 2):
        nodes[r] = nodes[r, ::-1]
    yield nodes.ravel()

# Example
nrows, ncols = 6, 5
source = 0, 0
target = 5, 0
path = next(special_case_1(nrows, ncols, source, target))

2) Even number of rows and input at left upper corner, output directly below input

(Similar to case (1), this generalizes to any corner.)

From case (1) we know how to fully connect a (2*M, N) grid. Now case (2) can be split into two sub-problems, namely the first column and the remainder of the grid (denoted with R). We can connect R in a similar fashion as for case (1). So all we need to do is to connect the first column to R. Connecting the input node at (0,0) to the left upper corner of R  at (0,1) is trivial. Then we can connect the left lower corner of R to the bottom node of the first column and then move all the way up to the output node at (1,0).

def special_case_2(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    assert source == (0, 0) and target == (1, 0)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    column = nodes[:, 0]
    nodes = nodes[:, 1:]
    for r in range(1, len(nodes), 2):
        nodes[r] = nodes[r, ::-1]
    yield [0, *nodes.ravel(), *column[:0:-1]]

# Example
nrows, ncols = 6, 5
source = 0, 0
target = 1, 0
path = next(special_case_2(nrows, ncols, source, target))

3) Even number of rows and columns, input and output located next to each other at the center of one the edges of the grid

For the sake of the example, let's assume they are located at the center of the top edge. We can split this problem into two sub-problems, left and right, and connect both input and output to their corresponding node on the bottom row in a fashion similar to case (1). Then, connecting the two problems amounts to simply connecting these two nodes.

def special_case_3(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    assert source == (0, ncols//2-1) and target == (0, ncols//2)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    left = nodes[:, :ncols//2]
    right = nodes[:, ncols//2:]
    for r in range(len(nodes)):
        if r % 2 == 0:
            left[r] = left[r, ::-1]
        else:
            right[r] = right[r, ::-1]
    yield [*left.ravel(), *right.ravel()[::-1]]

# Example
nrows, ncols = 6, 8
source = 0, 3
target = 0, 4
path = next(special_case_3(nrows, ncols, source, target))

4) Input and output next to each other in the center of the grid

For this we require only that the number of columns is even. The procedure is best explained by looking at the sketch and code and especially at the example plot below:

def special_case_4(
    nrows: int,
    ncols: int,
    source: Tuple[int, int],
    target: Tuple[int, int],
):
    r2, c2 = nrows//2, ncols//2
    assert source == (r2, c2-1) and target == (r2, c2)
    nodes = np.arange(nrows*ncols).reshape(nrows, ncols)
    top = nodes[:r2]
    for c in range(0, top.shape[1], 2):
        top[:, c] = top[::-1, c]
    bottom = nodes[r2+1:-1, 1:-1]
    for c in range(1, bottom.shape[1], 2):
        bottom[:, c] = bottom[::-1, c]
    yield [
        *nodes[r2, c2-1::-1],    # (1)
        *top.T.ravel(),          # (2)
        *nodes[r2:, -1],         # (3)
        *nodes[-1, -2::-1],      # (4)
        *nodes[:r2:-1, 0],       # (5)
        *bottom.T.ravel(),       # (6)
        *nodes[r2, -2:c2-1:-1],  # (7)
    ]

# Example
nrows, ncols = 7, 8
source = 3, 3
target = 3, 4
path = next(special_case_4(nrows, ncols, source, target))


来源: stackexchange

问:
Is it possible to make a static reference to an excel sheet in AnyLogic?
I want to call an Excel with a static java function within an AnyLogic Model as shown in the picture. The function "readExcelFile" has to be static, because I want to call it from another class within my AnyLogic Project.
However, when I call the function, an error occurs: "Cannot make a static reference to the non-static field produktionssystem".
Is there a solution for this problem?

答:
The error is because the Excel element produktionssystem can only ever be a (non-static) element in whatever agent type your function is also in (Main from the screenshot). By definition a static function cannot see any elements (Java fields) inside agent instances.

But you should never need a static function unless you need to share it across runs (which can have dangerous side effects if you're not careful). Your agents that need to call it just need a reference to an agent instance that does have the function.

If the calling agent is a 'child' of the function-declaring agent, you've already got the "Link to upper level agent" main provided by AnyLogic (and this will always exist if the calling agent is anywhere in the model's hierarchy of agents). Otherwise your calling agent will need something like a parameter of type Main which is set by whoever creates it.

ContentLicense: CC BY-SA 4.0


问:
Superclass meant only to be extended, not directly instanciated
i am coding an OOP application in PHP. I want to have a Superclass from which other classes will inherit from.

Is there a way i can make sure the class itself can't be instantiated directly?

like:

```<code>class Mother {}
class Child extends Mother{}
$child = new Child();//no problemo
$mother = new Mother();//throws exception or dies
</code>```

答:
There is abstract keyword.</p>

```<code>abstract class Mother { }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am coding an OOP application in PHP. I want to have a Superclass from which other classes will inherit from.

Is there a way i can make sure the class itself can't be instantiated directly?

like:

class Mother {}
class Child extends Mother{}
$child = new Child();//no problemo
$mother = new Mother();//throws exception or dies

Body:
There is abstract keyword.

abstract class Mother { }


问:
Angular RXJS, how do I get all data in subscribe after using multiple mergeMap calls (sequentially)?
I'd like to get all data similar to how 'forkJoin' does it after making multiple HTTP calls sequentially using MergeMap.</p>
```<code>this.dataService.getData1().pipe(
      mergeMap(response1 => this.dataService.getData2()),
      mergeMap(response2 => this.dataService.getData3()),
      mergeMap(response3 => this.dataService.getData4()),
    ).subscribe(

    //How do I get response1, response2, response3 and response4 here?

 )
</code>```

答:
If no observable's parameter depend on the previous call

you can use concat, which will play the observables is a sequence, each time waiting on the previous to finish (unlike merge)

```<code>var arr = [
  this.dataService.getData1(),
  this.dataPublicationsService.getData2(),
  this.dataPublicationsService.getData3(),
  this.dataPublicationsService.getData4(),
];
concat(...arr).pipe(toArray()).subscribe((a) => console.log(a));
</code>```

If each call depends on the previous one there is no "clean" way to do it, you have to pass the data youself.

One way to achieve this is use forkJoin and the spread operator

```<code>class Foo {
  dataService: { getData1: () => Observable<number> };
  dataPublicationsService: {
    getData2: () => Observable<string>;
    getData3: () => Observable<number>;
    getData4: () => Observable<object>;
  };

  bar() {
    this.dataService
      .getData1()
      .pipe(
        mergeMap((response1) =>
          forkJoin([of(response1), this.dataPublicationsService.getData2()])
        ),
        mergeMap((rest) => // rest is [number, string]
          forkJoin([of([...rest]), this.dataPublicationsService.getData3()])
        ),
        mergeMap((rest) => rest is [number, string, number]
          forkJoin([of(...rest), this.dataPublicationsService.getData4()])
        )
      )
      .subscribe((rest) => {
         // [number, string, number, object]
      });
   }
}
</code>```

Body:
I'd like to get all data similar to how 'forkJoin' does it after making multiple HTTP calls sequentially using MergeMap.

this.dataService.getData1().pipe(
      mergeMap(response1 => this.dataService.getData2()),
      mergeMap(response2 => this.dataService.getData3()),
      mergeMap(response3 => this.dataService.getData4()),
    ).subscribe(

    //How do I get response1, response2, response3 and response4 here?

 )

Body:
If no observable's parameter depend on the previous call

you can use concat, which will play the observables is a sequence, each time waiting on the previous to finish (unlike merge)

var arr = [
  this.dataService.getData1(),
  this.dataPublicationsService.getData2(),
  this.dataPublicationsService.getData3(),
  this.dataPublicationsService.getData4(),
];
concat(...arr).pipe(toArray()).subscribe((a) => console.log(a));

If each call depends on the previous one there is no "clean" way to do it, you have to pass the data youself.

One way to achieve this is use forkJoin and the spread operator

class Foo {
  dataService: { getData1: () => Observable<number> };
  dataPublicationsService: {
    getData2: () => Observable<string>;
    getData3: () => Observable<number>;
    getData4: () => Observable<object>;
  };

  bar() {
    this.dataService
      .getData1()
      .pipe(
        mergeMap((response1) =>
          forkJoin([of(response1), this.dataPublicationsService.getData2()])
        ),
        mergeMap((rest) => // rest is [number, string]
          forkJoin([of([...rest]), this.dataPublicationsService.getData3()])
        ),
        mergeMap((rest) => rest is [number, string, number]
          forkJoin([of(...rest), this.dataPublicationsService.getData4()])
        )
      )
      .subscribe((rest) => {
         // [number, string, number, object]
      });
   }
}


问:
Heroku CLI gives "No Redis instances found" yet I have a redis cloud addon running and usable
I'm learning redis and have it working from a java app. I'm trying to use the heroku redis:cli -a myAppName command to connect with it directly but it says "No Redis instances found".

When I do heroku apps it lists myAppName so I know it's valid.

heroku redis:info -a myAppName doesn't return anything.

The heroku docs don't seem to be accurate as they all leave out the -a flag which the cli tells me is required. Outside of that I don't know what I've missed.

答:
You are looking at documentation for Heroku Redis, a hosted Redis service that Heroku itself provides. If you wish to use Heroku Redis, you can provision it for your app using like so:

```<code>heroku addons:create heroku-redis:hobby-dev -a your-app-name
</code>```

Pricing for Heroku Redis can be found here. The Hobby Dev plan used in the previous command is free.

There are also other Redis providers that can be provisioned this way, including Redis Enterprise Cloud. Or you can use existing hosted Redis server. But with these options you won't be able to interact with the service using heroku redis commands. Use whatever tooling those providers offer.

Body:
You are looking at documentation for Heroku Redis, a hosted Redis service that Heroku itself provides. If you wish to use Heroku Redis, you can provision it for your app using like so:

heroku addons:create heroku-redis:hobby-dev -a your-app-name

Pricing for Heroku Redis can be found here. The Hobby Dev plan used in the previous command is free.

There are also other Redis providers that can be provisioned this way, including Redis Enterprise Cloud. Or you can use existing hosted Redis server. But with these options you won't be able to interact with the service using heroku redis commands. Use whatever tooling those providers offer.


问:
Website title is only displayed when the mouse is moved
I have a problem: the title of my website doesn't appear until the mouse is moved. On the phone only when your finger touches the screen. Does anyone have an idea what the problem is? I use the Inspiro Theme. Do you need more information?

This is my website: https://dev-friedl-bau.pantheonsite.io/

答:
Have a look in your CSS and Class items looks like you may have a hover instance.

.site-branding

This could be your problem!


问:
Problem to check if a function is true in another function php
I use this code to check the function 1 is true. If it is true, function 2 assigns a CSS class, otherwise another one :

```<code>function first() {
  return TRUE;
}

function second() {
  if (first() == TRUE) {
  }
}
</code>```

The result works but I have a problem. It shows me the boolean value at the front end site, which is "1" (the value is in the html code, without any tag around it). Do you have any idea how to not display this value?

Here is the front-end rendering:

The HTML code looks like this :

```<code><a>
    <span class="onsale">-50%</span>
    1
    <img>
</code>```

And here is my full code:

```<code>// Sales badge
add_action( 'woocommerce_sale_flash', 'sale_badge_percentage', 25 );

function sale_badge_percentage() {
   global $product;
   if ( ! $product->is_on_sale() ) return;
   if ( $product->is_type( 'simple' ) ) {
      $max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
   } elseif ( $product->is_type( 'variable' ) ) {
      $max_percentage = 0;
      foreach ( $product->get_children() as $child_id ) {
         $variation = wc_get_product( $child_id );
         $price = $variation->get_regular_price();
         $sale = $variation->get_sale_price();
         if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
         if ( $percentage > $max_percentage ) {
            $max_percentage = $percentage;
         }
      }
   }
   if ( $max_percentage > 0 ) {
        echo "<span class='onsale'>-" . round($max_percentage) . "%</span>";
        return TRUE;
   }
}

// New badge for recent products
add_action( 'woocommerce_before_shop_loop_item_title', 'new_badge', 3 );

function new_badge() {
   if (sale_badge_percentage() == TRUE) {
    /* la variable existe */
       global $product;
   $newness_days = 30; // Number of days the badge is shown
   $created = strtotime( $product->get_date_created() );
   if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
      echo '<span class="ct-woo-card-extra new-badge">' . esc_html__( 'NEW', 'woocommerce' ) . '</span>';
   }
}
else {
    /* la variable n'existe pas */
    global $product;
   $newness_days = 30; // Number of days the badge is shown
   $created = strtotime( $product->get_date_created() );
   if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
      echo '<span class="ct-woo-card-extra new-badge solobadge">' . esc_html__( 'NEW', 'woocommerce' ) . '</span>';
   }
}
}
</code>```

答: Resolved!! i only changed echo in return above the return TRUE;

Body:
I use this code to check the function 1 is true. If it is true, function 2 assigns a CSS class, otherwise another one :

function first() {
  return TRUE;
}

function second() {
  if (first() == TRUE) {
  }
}

The result works but I have a problem. It shows me the boolean value at the front end site, which is "1" (the value is in the html code, without any tag around it). Do you have any idea how to not display this value?

Here is the front-end rendering:

The HTML code looks like this :

    -50%
    1

And here is my full code:

// Sales badge
add_action( 'woocommerce_sale_flash', 'sale_badge_percentage', 25 );

function sale_badge_percentage() {
   global $product;
   if ( ! $product->is_on_sale() ) return;
   if ( $product->is_type( 'simple' ) ) {
      $max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
   } elseif ( $product->is_type( 'variable' ) ) {
      $max_percentage = 0;
      foreach ( $product->get_children() as $child_id ) {
         $variation = wc_get_product( $child_id );
         $price = $variation->get_regular_price();
         $sale = $variation->get_sale_price();
         if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
         if ( $percentage > $max_percentage ) {
            $max_percentage = $percentage;
         }
      }
   }
   if ( $max_percentage > 0 ) {
        echo "-" . round($max_percentage) . "%";
        return TRUE;
   }
}

// New badge for recent products
add_action( 'woocommerce_before_shop_loop_item_title', 'new_badge', 3 );

function new_badge() {
   if (sale_badge_percentage() == TRUE) {
    /* la variable existe */
       global $product;
   $newness_days = 30; // Number of days the badge is shown
   $created = strtotime( $product->get_date_created() );
   if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
      echo '' . esc_html__( 'NEW', 'woocommerce' ) . '';
   }
}
else {
    /* la variable n'existe pas */
    global $product;
   $newness_days = 30; // Number of days the badge is shown
   $created = strtotime( $product->get_date_created() );
   if ( ( time() - ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
      echo '' . esc_html__( 'NEW', 'woocommerce' ) . '';
   }
}
}


问:
BLOCKER - Change this code to not construct SQL queries directly from user-controlled data
Sonarqube is giving me this error:

[BLOCKER] Change this code to not construct SQL queries directly from user-controlled data

Here is my code:

String countSQL;

countSQL = (String.format("SELECT count(*) as total FROM ltid_owner.enty %s",additionalWhereClauses));

jdbcTemplateTMI.queryForObject(countSQL, Integer.class);
```
<p>In the above code <code>additionalWhereClauses</code> could be something like this shown below which I am building on the fly when the user clicks on the grid to perform filtering on different columns:</p>
<pre class="lang-java prettyprint-override"><code>additionalWhereClauses = where UPPER(enty_num) like '003%'
</code>```

Can you please let me know how to resolve this issue?

答:
Your code combines strings into SQL statements. If any of these strings contains user provided input, an attacker can sneak in code to trigger an SQL injection attack and possibly run arbitrary code on your computer (obligatory Bobby Tables reference).

Simple example:

String sql = "SELECT * FROM users WHERE name = '" + name + "' AND password = '" + password + "'";
```
<p>If I enter <code>' OR 1=1 --</code> for the name (and "..." for the password, but that doesn't really matter anymore) the code becomes a valid SQL statement:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM users
WHERE name = '' OR 1=1 -- ' AND password = '...'
</code>```

but the user name / password check is completely disabled.

To avoid this, use prepared statements. They build the SQL command in a way that SQL injection is impossible.

Maybe this never happens in your code as you don't accept user input, but Sonar doesn't know this (and human reviewers won't either). I'd always use prepared statements. Just because your code only passed column headers from a frontend, doesn't mean an attacker cannot manually call your web service endpoints and pass whatever they want, it your code runs as an HTTP endpoint.

Body:
Sonarqube is giving me this error:

[BLOCKER] Change this code to not construct SQL queries directly from user-controlled data

Here is my code:

String countSQL;

countSQL = (String.format("SELECT count(*) as total FROM ltid_owner.enty %s",additionalWhereClauses));

jdbcTemplateTMI.queryForObject(countSQL, Integer.class);

In the above code additionalWhereClauses could be something like this shown below which I am building on the fly when the user clicks on the grid to perform filtering on different columns:

additionalWhereClauses = where UPPER(enty_num) like '003%'

Can you please let me know how to resolve this issue?

Body:
Your code combines strings into SQL statements. If any of these strings contains user provided input, an attacker can sneak in code to trigger an SQL injection attack and possibly run arbitrary code on your computer (obligatory Bobby Tables reference).

Simple example:

String sql = "SELECT * FROM users WHERE name = '" + name + "' AND password = '" + password + "'";

If I enter ' OR 1=1 -- for the name (and "..." for the password, but that doesn't really matter anymore) the code becomes a valid SQL statement:

SELECT *
FROM users
WHERE name = '' OR 1=1 -- ' AND password = '...'

but the user name / password check is completely disabled.

To avoid this, use prepared statements. They build the SQL command in a way that SQL injection is impossible.

Maybe this never happens in your code as you don't accept user input, but Sonar doesn't know this (and human reviewers won't either). I'd always use prepared statements. Just because your code only passed column headers from a frontend, doesn't mean an attacker cannot manually call your web service endpoints and pass whatever they want, it your code runs as an HTTP endpoint.


问:
Filtering Data out of 2 CSVs and Getting Objects within Object
So what I am attemping to do is filter some data through a csv from a csv and when it goes through it searches the column and give me all the values that have a matching value in the 2nd CSV from the 1st one. However the values its giving are the groups when in fact I need the devices that are in the groups. So kinda like a group of object inside of an object.

```<code>$Date = $(Get-Date -f MM_dd_yyyy)
$azuregroupdata = import-csv -Path "\\iPadIntuneMDM\CSV\$Date-AzureGroupsdata.csv"

$resultdata = import-csv -Path "\\iPadIntuneMDM\CSV\$Date-MatchinDevices.csv"
$groupsinboth = (Compare-Object -ReferenceObject ($resultdata.NewGroup) -DifferenceObject ($azuregroupdata.DisplayName) -IncludeEqual | `
        Where-Object { $_.SideIndicator -eq "==" } | `
        Select-Object -ExpandProperty InputObject)

$results2 = ForEach ($Group in $groupsinboth) {

    $A2 = $resultdata | Where-Object { $_.NewGroup -eq $Group }
    $I2 = $azuregroupdata | Where-Object { $_.DisplayName -eq $Group }
    New-Object -TypeName psobject -Property @{
        "Serial"          = $A2.Serial
        "ObjectID"        = $A2.ObjectID
        "AzureADGroupID" = $I2.ObjectId
    }
}
Write-Host $results2
$results2 | Export-CSV -NoTypeInformation -Path \\iPadIntuneMDM\CSV\$(Get-Date -f MM_dd_yyyy)-DevicesandgroupIDs.csv
</code>```

In the CSVs I have the following data

AzureGroupsData

#TYPE Microsoft.Open.AzureAD.Model.Group

DeletionTimestamp
ObjectId
Description
DisplayName
SecurityEnabled

4e29b8b7-bdc7-4d21-a13b-5517514a791e
iPad-EDC-PreDeploy
iPad-EDC-PreDeploy
TRUE

9737a1de-79f3-4e0c-8b47-0933bd5613e4
iPad-SAE-Students-ML01
iPad-SAE-Students-ML01
TRUE

d7166f43-4562-4bff-8e92-e420df9b2e9c
iPad-PER-Students-ML03
iPad-PER-Students-ML03
TRUE

1952810e-88da-49cd-bb8c-0edb26f61cd5
iPad-SAE-Staff-ML01
iPad-SAE-Staff-ML01
TRUE

39d2bc70-7ed8-4b9a-b4b4-b3843df7e20b
iPad-SAE-Students-ML04
iPad-SAE-Students-ML04
TRUE

53b24a28-ee91-4c14-8020-21ab431c89de
iPad-RLE-Staff-ML01
iPad-RLE-Staff-ML01
TRUE

c40bb857-4388-4c26-9b68-b7ffa688a5d4
iPad-GAE-Staff-ML04
iPad-GAE-Staff-ML04
TRUE

a4764233-3b7d-4420-838c-806d1db8ca05
iPad-SAE-Students-ML02
iPad-SAE-Students-ML02
TRUE

705d5fd0-b788-4158-b684-6f225783484a
iPad-EDC-Staff-IT
iPad-EDC-Staff-IT
TRUE

da75d1f7-7945-4cb1-9618-51f914651ea6
iPad-SRC-Staff
iPad-SRC-Staff
TRUE

ResultData

ObjectID
Serial
NewGroup
DeviceID
OldGroup

0fb06be4-13c3-4040-af68-85fae174895a
DLXNL73AG5YP
iPad-EDC-PreDeploy
5f54d29a-aad6-4f41-98a0-ddf7a8c85250
4521

01c1628e-45d3-42d8-abd9-29f7f10ea321
DMPNP6W0G5VW
iPad-SAE-Students-ML01
14c4cbcd-4be7-498d-8fdd-be376a2b3a7a
4597

0be2d71a-34cb-4f0a-a5dd-9b88d105c47a
DMPNP5SQG5VW
iPad-PER-Students-ML03
7e7b0c62-2f74-4000-aafb-1cc725d10ddd
4633

1a4393bf-c89d-478c-aa86-ff23c3eedd66
DMPNP65YG5VW
iPad-EDC-PreDeploy
55d6ae86-e07a-4be5-ab0c-c3d8e9e5b4f4
4521

1d2afa19-ceb9-4e7c-8638-4e86607249d2
DMPPX0RDG5YP
iPad-EDC-PreDeploy
0995fd79-cdd3-4186-93ef-237356401aa4
4521

1d884772-645c-4044-bec7-24240af0a52a
DMPNP70WG5VW
iPad-EDC-PreDeploy
da20b47a-658e-4a2e-a02d-9c49aa585739
4521

1ddee2c6-9326-47d1-a6a2-8b4fa410a1e4
DMPNP6GNG5VW
iPad-SAE-Students-ML01
dab324ed-68c6-43e4-8b66-25dc204b0705
4597

31c4d5f8-14a6-468d-806c-e4848b98d08c
DMPNNW7SG5VW
iPad-SAE-Staff-ML01
e1e15427-dd65-4174-a9c2-62bf63ed28cf
4611

36e66c40-dfcd-41ff-b038-96d66fa07ffb
DMPNP685G5VW
iPad-PER-Students-ML03
a1be4983-24e8-4063-ad4e-132c9efecffd
4633

3e1d76b5-e633-4372-a9f7-13aa8c6364ad
DMPNP4U2G5VW
iPad-SAE-Students-ML04
c6414402-ccb1-45ad-b756-fa8a987ff473
4600

3f5d7f96-a394-4c75-99c8-0a588437a6da
DMPNP51EG5VW
iPad-PER-Students-ML03
3c0d9145-a499-443e-a6a5-87deefe0d117
4633

4165c5f4-d57e-4cce-82ce-5b8a87ccecd5
DMPNP5HQG5VW
iPad-EDC-PreDeploy
d650e345-d978-482f-a418-543fede68299
4521

49ad55f2-dd4a-4598-80e8-c33d05afc3eb
DMPNP67RG5VW
iPad-PER-Students-ML03
4426c45f-bb12-4f70-9c8f-ab3db3aa2a7e
4633

53bfa152-80f8-451f-9086-3c37d3d61d13
DMPNP6Z3G5VW
iPad-RLE-Staff-ML01
f75f767a-bac8-4a29-a57a-8362caeff759
4568

53d25bcc-f124-4ca9-afb1-cbf450a5116f
DMPNPPSVG5VW
iPad-EDC-PreDeploy
2c100fbc-0d17-4209-9f8a-18253878a465
4521

57436992-5749-431e-8cca-a2476b8f656c
DMPPW3WFG5YP
iPad-EDC-PreDeploy
212949c6-a49d-4d8a-89d1-fcc6939c7629
4521

599c5285-0b54-48cb-8d6a-8c79c3d3d7ca
DMPNP61JG5VW
iPad-GAE-Staff-ML04
491a581c-ef20-456e-8657-08cc63901603
4610

5a0bb215-059b-421e-9446-f6aed9cd62c4
DMPNP6EUG5VW
iPad-SAE-Students-ML01
3b23aa12-4f3b-44f7-944b-c3b69f74c9ff
4597

6f096b30-6bc2-4289-a46e-7d91a08d5309
DMPNPB9MG5VW
iPad-EDC-PreDeploy
662a15bf-c2a9-48ce-922c-688377030c3f
4521

74a84b5a-cdbb-4bd6-ae31-c0f785702ea2
DMPNP6DRG5VW
iPad-SAE-Students-ML02
b175a280-a3eb-4b25-ae2b-06b4b586e235
4598

766a1907-31cd-41f9-bfac-4a0fa3e2f514
DMPPX0S2G5YP
iPad-EDC-PreDeploy
25faf41f-5a52-4bfd-983e-5fe735530ee7
4521

7ab6b17b-08f3-45d7-afea-58ef01701d78
DMPNP6D9G5VW
iPad-EDC-PreDeploy
7a6a2552-d683-4202-9b10-3d4af7bbbae5
4521

7c30ec0e-d754-4035-9762-b891f36bbc74
DMPNP6ETG5VW
iPad-SAE-Students-ML02
3b254910-74ef-44c8-8d35-b63f7cad0cff
4598

7ff51330-9687-48b3-bdca-82b539ac64bc
DMPN5PSYFK11
iPad-EDC-PreDeploy
009b60e4-d3ba-4df7-9bc9-71929963513e
4521

8cdab7fe-bd1f-4a8b-8bb0-a4b4e15cf921
DMPNP6WNG5VW
iPad-EDC-PreDeploy
807635ac-5f55-4582-936a-7fb376e95003
4521

930d2407-074d-43c4-93c5-1724cd2e31d8
DMPNP6JRG5VW
iPad-SAE-Students-ML01
469bfe61-02f4-485e-93c3-bad2e63028ee
4597

961b4b75-783f-4aa1-b012-7b4de13ab437
DMPNP6FSG5VW
iPad-SAE-Students-ML02
b5a96974-05ad-44be-9d9b-d66ee9b64252
4598

96300aec-5e6b-4ddb-90a3-d1aec58d4934
DMPNP6VNG5VW
iPad-EDC-PreDeploy
99114f99-b6de-4d0c-adda-125df8ee116b
4521

9e4a9329-35d2-40c7-9e09-de0c9a809ced
DMPNP756G5VW
iPad-EDC-PreDeploy
c79bb992-7363-47b8-bcdf-b84e2312cf0c
4521

9ee5d6a4-2ffc-46ae-9c65-4a50208d035d
DMPPX0PMG5YP
iPad-EDC-PreDeploy
87f2149a-f853-4f4d-a1b4-89236b2c02b5
4521

ac1daa36-6382-493c-914f-a55d934c3a06
F9GDNNC8Q1GC
iPad-SRC-Staff
ebec06e9-2c12-49c1-806e-cc86d94053dd
4677

ad19d31e-11f2-450a-abee-1af1c9e4a7d4
DMPNP65UG5VW
iPad-EDC-PreDeploy
7a6e73ad-31cb-4ae5-9fb1-e63f64fad914
4521

bd978541-6254-4ad1-bb4e-e7640dea083b
DMPNP6DBG5VW
iPad-EDC-PreDeploy
0f12fb3b-4cd8-4b2a-91d2-3bf824d4fdfb
4521

da8eb01e-2f5a-41d6-8ee3-a18c95a09256
DMPNP6KSG5VW
iPad-EDC-PreDeploy
dc81d237-a6ad-497d-9109-08999a01209f
4521

e434527b-4371-48d6-8396-dc8d085c5a04
DMPNP6D6G5VW
iPad-EDC-Staff-IT
51a05fef-0161-41c6-a1ee-1955083ec8c6
4588

e6d8ad88-6971-4169-ae49-c2616eedb523
DMPNP6Q6G5VW
iPad-SAE-Students-ML01
368ac2e0-2e08-440d-9c10-812087bfe855
4597

Output $results2

ObjectID
Serial
AzureADGroupID

31c4d5f8-14a6-468d-806c-e4848b98d08c
DMPNNW7SG5VW
1952810e-88da-49cd-bb8c-0edb26f61cd5

3e1d76b5-e633-4372-a9f7-13aa8c6364ad
DMPNP4U2G5VW
39d2bc70-7ed8-4b9a-b4b4-b3843df7e20b

System.Object[]
System.Object[]
4e29b8b7-bdc7-4d21-a13b-5517514a791e

53bfa152-80f8-451f-9086-3c37d3d61d13
DMPNP6Z3G5VW
53b24a28-ee91-4c14-8020-21ab431c89de

e434527b-4371-48d6-8396-dc8d085c5a04
DMPNP6D6G5VW
705d5fd0-b788-4158-b684-6f225783484a

System.Object[]
System.Object[]
9737a1de-79f3-4e0c-8b47-0933bd5613e4

System.Object[]
System.Object[]
a4764233-3b7d-4420-838c-806d1db8ca05

599c5285-0b54-48cb-8d6a-8c79c3d3d7ca
DMPNP61JG5VW
c40bb857-4388-4c26-9b68-b7ffa688a5d4

System.Object[]
System.Object[]
d7166f43-4562-4bff-8e92-e420df9b2e9c

ac1daa36-6382-493c-914f-a55d934c3a06
F9GDNNC8Q1GC
da75d1f7-7945-4cb1-9618-51f914651ea6

答:
The Object[] in the result CSV means that there are multiple values found per DisplayName (i.e.: iPad-PER-Students-ML03 has multiple appearances in the big CSV) hence why there are multiple serials and multiple objectIDs. This would require 2 nested loops to unroll all the data:

An outer loop to enumerate all rows of the Azure Groups CSV.

And, an inner loop to enumerate all rows of the Big CSV per appearance of DisplayName / NewGroup.

```<code>$azureGroups = Import-Csv 'this\is\theAZUREGROUPS.csv'
$bigCsvHash = Import-Csv 'this\is\theBIGcsv.csv' |
    Group-Object NewGroup -AsHashTable -AsString

$result = foreach($i in $azureGroups) {
    foreach($z in $bigCsvHash[$i.DisplayName]) {
        [pscustomobject]@{
            Serial         = $z.Serial
            ObjectID       = $z.ObjectId
            AzureADGroupID = $i.ObjectId
        }
    }
}

$result | Export-Csv ....
</code>```

Body:
So what I am attemping to do is filter some data through a csv from a csv and when it goes through it searches the column and give me all the values that have a matching value in the 2nd CSV from the 1st one. However the values its giving are the groups when in fact I need the devices that are in the groups. So kinda like a group of object inside of an object.

$Date = $(Get-Date -f MM_dd_yyyy)
$azuregroupdata = import-csv -Path "\\iPadIntuneMDM\CSV\$Date-AzureGroupsdata.csv"

$resultdata = import-csv -Path "\\iPadIntuneMDM\CSV\$Date-MatchinDevices.csv"
$groupsinboth = (Compare-Object -ReferenceObject ($resultdata.NewGroup) -DifferenceObject ($azuregroupdata.DisplayName) -IncludeEqual | `
        Where-Object { $_.SideIndicator -eq "==" } | `
        Select-Object -ExpandProperty InputObject)

$results2 = ForEach ($Group in $groupsinboth) {

    $A2 = $resultdata | Where-Object { $_.NewGroup -eq $Group }
    $I2 = $azuregroupdata | Where-Object { $_.DisplayName -eq $Group }
    New-Object -TypeName psobject -Property @{
        "Serial"          = $A2.Serial
        "ObjectID"        = $A2.ObjectID
        "AzureADGroupID" = $I2.ObjectId
    }
}
Write-Host $results2
$results2 | Export-CSV -NoTypeInformation -Path \\iPadIntuneMDM\CSV\$(Get-Date -f MM_dd_yyyy)-DevicesandgroupIDs.csv

In the CSVs I have the following data

AzureGroupsData

#TYPE Microsoft.Open.AzureAD.Model.Group

DeletionTimestamp
ObjectId
Description
DisplayName
SecurityEnabled

4e29b8b7-bdc7-4d21-a13b-5517514a791e
iPad-EDC-PreDeploy
iPad-EDC-PreDeploy
TRUE

9737a1de-79f3-4e0c-8b47-0933bd5613e4
iPad-SAE-Students-ML01
iPad-SAE-Students-ML01
TRUE

d7166f43-4562-4bff-8e92-e420df9b2e9c
iPad-PER-Students-ML03
iPad-PER-Students-ML03
TRUE

1952810e-88da-49cd-bb8c-0edb26f61cd5
iPad-SAE-Staff-ML01
iPad-SAE-Staff-ML01
TRUE

39d2bc70-7ed8-4b9a-b4b4-b3843df7e20b
iPad-SAE-Students-ML04
iPad-SAE-Students-ML04
TRUE

53b24a28-ee91-4c14-8020-21ab431c89de
iPad-RLE-Staff-ML01
iPad-RLE-Staff-ML01
TRUE

c40bb857-4388-4c26-9b68-b7ffa688a5d4
iPad-GAE-Staff-ML04
iPad-GAE-Staff-ML04
TRUE

a4764233-3b7d-4420-838c-806d1db8ca05
iPad-SAE-Students-ML02
iPad-SAE-Students-ML02
TRUE

705d5fd0-b788-4158-b684-6f225783484a
iPad-EDC-Staff-IT
iPad-EDC-Staff-IT
TRUE

da75d1f7-7945-4cb1-9618-51f914651ea6
iPad-SRC-Staff
iPad-SRC-Staff
TRUE

ResultData

ObjectID
Serial
NewGroup
DeviceID
OldGroup

0fb06be4-13c3-4040-af68-85fae174895a
DLXNL73AG5YP
iPad-EDC-PreDeploy
5f54d29a-aad6-4f41-98a0-ddf7a8c85250
4521

01c1628e-45d3-42d8-abd9-29f7f10ea321
DMPNP6W0G5VW
iPad-SAE-Students-ML01
14c4cbcd-4be7-498d-8fdd-be376a2b3a7a
4597

0be2d71a-34cb-4f0a-a5dd-9b88d105c47a
DMPNP5SQG5VW
iPad-PER-Students-ML03
7e7b0c62-2f74-4000-aafb-1cc725d10ddd
4633

1a4393bf-c89d-478c-aa86-ff23c3eedd66
DMPNP65YG5VW
iPad-EDC-PreDeploy
55d6ae86-e07a-4be5-ab0c-c3d8e9e5b4f4
4521

1d2afa19-ceb9-4e7c-8638-4e86607249d2
DMPPX0RDG5YP
iPad-EDC-PreDeploy
0995fd79-cdd3-4186-93ef-237356401aa4
4521

1d884772-645c-4044-bec7-24240af0a52a
DMPNP70WG5VW
iPad-EDC-PreDeploy
da20b47a-658e-4a2e-a02d-9c49aa585739
4521

1ddee2c6-9326-47d1-a6a2-8b4fa410a1e4
DMPNP6GNG5VW
iPad-SAE-Students-ML01
dab324ed-68c6-43e4-8b66-25dc204b0705
4597

31c4d5f8-14a6-468d-806c-e4848b98d08c
DMPNNW7SG5VW
iPad-SAE-Staff-ML01
e1e15427-dd65-4174-a9c2-62bf63ed28cf
4611

36e66c40-dfcd-41ff-b038-96d66fa07ffb
DMPNP685G5VW
iPad-PER-Students-ML03
a1be4983-24e8-4063-ad4e-132c9efecffd
4633

3e1d76b5-e633-4372-a9f7-13aa8c6364ad
DMPNP4U2G5VW
iPad-SAE-Students-ML04
c6414402-ccb1-45ad-b756-fa8a987ff473
4600

3f5d7f96-a394-4c75-99c8-0a588437a6da
DMPNP51EG5VW
iPad-PER-Students-ML03
3c0d9145-a499-443e-a6a5-87deefe0d117
4633

4165c5f4-d57e-4cce-82ce-5b8a87ccecd5
DMPNP5HQG5VW
iPad-EDC-PreDeploy
d650e345-d978-482f-a418-543fede68299
4521

49ad55f2-dd4a-4598-80e8-c33d05afc3eb
DMPNP67RG5VW
iPad-PER-Students-ML03
4426c45f-bb12-4f70-9c8f-ab3db3aa2a7e
4633

53bfa152-80f8-451f-9086-3c37d3d61d13
DMPNP6Z3G5VW
iPad-RLE-Staff-ML01
f75f767a-bac8-4a29-a57a-8362caeff759
4568

53d25bcc-f124-4ca9-afb1-cbf450a5116f
DMPNPPSVG5VW
iPad-EDC-PreDeploy
2c100fbc-0d17-4209-9f8a-18253878a465
4521

57436992-5749-431e-8cca-a2476b8f656c
DMPPW3WFG5YP
iPad-EDC-PreDeploy
212949c6-a49d-4d8a-89d1-fcc6939c7629
4521

599c5285-0b54-48cb-8d6a-8c79c3d3d7ca
DMPNP61JG5VW
iPad-GAE-Staff-ML04
491a581c-ef20-456e-8657-08cc63901603
4610

5a0bb215-059b-421e-9446-f6aed9cd62c4
DMPNP6EUG5VW
iPad-SAE-Students-ML01
3b23aa12-4f3b-44f7-944b-c3b69f74c9ff
4597

6f096b30-6bc2-4289-a46e-7d91a08d5309
DMPNPB9MG5VW
iPad-EDC-PreDeploy
662a15bf-c2a9-48ce-922c-688377030c3f
4521

74a84b5a-cdbb-4bd6-ae31-c0f785702ea2
DMPNP6DRG5VW
iPad-SAE-Students-ML02
b175a280-a3eb-4b25-ae2b-06b4b586e235
4598

766a1907-31cd-41f9-bfac-4a0fa3e2f514
DMPPX0S2G5YP
iPad-EDC-PreDeploy
25faf41f-5a52-4bfd-983e-5fe735530ee7
4521

7ab6b17b-08f3-45d7-afea-58ef01701d78
DMPNP6D9G5VW
iPad-EDC-PreDeploy
7a6a2552-d683-4202-9b10-3d4af7bbbae5
4521

7c30ec0e-d754-4035-9762-b891f36bbc74
DMPNP6ETG5VW
iPad-SAE-Students-ML02
3b254910-74ef-44c8-8d35-b63f7cad0cff
4598

7ff51330-9687-48b3-bdca-82b539ac64bc
DMPN5PSYFK11
iPad-EDC-PreDeploy
009b60e4-d3ba-4df7-9bc9-71929963513e
4521

8cdab7fe-bd1f-4a8b-8bb0-a4b4e15cf921
DMPNP6WNG5VW
iPad-EDC-PreDeploy
807635ac-5f55-4582-936a-7fb376e95003
4521

930d2407-074d-43c4-93c5-1724cd2e31d8
DMPNP6JRG5VW
iPad-SAE-Students-ML01
469bfe61-02f4-485e-93c3-bad2e63028ee
4597

961b4b75-783f-4aa1-b012-7b4de13ab437
DMPNP6FSG5VW
iPad-SAE-Students-ML02
b5a96974-05ad-44be-9d9b-d66ee9b64252
4598

96300aec-5e6b-4ddb-90a3-d1aec58d4934
DMPNP6VNG5VW
iPad-EDC-PreDeploy
99114f99-b6de-4d0c-adda-125df8ee116b
4521

9e4a9329-35d2-40c7-9e09-de0c9a809ced
DMPNP756G5VW
iPad-EDC-PreDeploy
c79bb992-7363-47b8-bcdf-b84e2312cf0c
4521

9ee5d6a4-2ffc-46ae-9c65-4a50208d035d
DMPPX0PMG5YP
iPad-EDC-PreDeploy
87f2149a-f853-4f4d-a1b4-89236b2c02b5
4521

ac1daa36-6382-493c-914f-a55d934c3a06
F9GDNNC8Q1GC
iPad-SRC-Staff
ebec06e9-2c12-49c1-806e-cc86d94053dd
4677

ad19d31e-11f2-450a-abee-1af1c9e4a7d4
DMPNP65UG5VW
iPad-EDC-PreDeploy
7a6e73ad-31cb-4ae5-9fb1-e63f64fad914
4521

bd978541-6254-4ad1-bb4e-e7640dea083b
DMPNP6DBG5VW
iPad-EDC-PreDeploy
0f12fb3b-4cd8-4b2a-91d2-3bf824d4fdfb
4521

da8eb01e-2f5a-41d6-8ee3-a18c95a09256
DMPNP6KSG5VW
iPad-EDC-PreDeploy
dc81d237-a6ad-497d-9109-08999a01209f
4521

e434527b-4371-48d6-8396-dc8d085c5a04
DMPNP6D6G5VW
iPad-EDC-Staff-IT
51a05fef-0161-41c6-a1ee-1955083ec8c6
4588

e6d8ad88-6971-4169-ae49-c2616eedb523
DMPNP6Q6G5VW
iPad-SAE-Students-ML01
368ac2e0-2e08-440d-9c10-812087bfe855
4597

Output $results2

ObjectID
Serial
AzureADGroupID

31c4d5f8-14a6-468d-806c-e4848b98d08c
DMPNNW7SG5VW
1952810e-88da-49cd-bb8c-0edb26f61cd5

3e1d76b5-e633-4372-a9f7-13aa8c6364ad
DMPNP4U2G5VW
39d2bc70-7ed8-4b9a-b4b4-b3843df7e20b

System.Object[]
System.Object[]
4e29b8b7-bdc7-4d21-a13b-5517514a791e

53bfa152-80f8-451f-9086-3c37d3d61d13
DMPNP6Z3G5VW
53b24a28-ee91-4c14-8020-21ab431c89de

e434527b-4371-48d6-8396-dc8d085c5a04
DMPNP6D6G5VW
705d5fd0-b788-4158-b684-6f225783484a

System.Object[]
System.Object[]
9737a1de-79f3-4e0c-8b47-0933bd5613e4

System.Object[]
System.Object[]
a4764233-3b7d-4420-838c-806d1db8ca05

599c5285-0b54-48cb-8d6a-8c79c3d3d7ca
DMPNP61JG5VW
c40bb857-4388-4c26-9b68-b7ffa688a5d4

System.Object[]
System.Object[]
d7166f43-4562-4bff-8e92-e420df9b2e9c

ac1daa36-6382-493c-914f-a55d934c3a06
F9GDNNC8Q1GC
da75d1f7-7945-4cb1-9618-51f914651ea6

Body:
The Object[] in the result CSV means that there are multiple values found per DisplayName (i.e.: iPad-PER-Students-ML03 has multiple appearances in the big CSV) hence why there are multiple serials and multiple objectIDs. This would require 2 nested loops to unroll all the data:

An outer loop to enumerate all rows of the Azure Groups CSV.

And, an inner loop to enumerate all rows of the Big CSV per appearance of DisplayName / NewGroup.

$azureGroups = Import-Csv 'this\is\theAZUREGROUPS.csv'
$bigCsvHash = Import-Csv 'this\is\theBIGcsv.csv' |
    Group-Object NewGroup -AsHashTable -AsString

$result = foreach($i in $azureGroups) {
    foreach($z in $bigCsvHash[$i.DisplayName]) {
        [pscustomobject]@{
            Serial         = $z.Serial
            ObjectID       = $z.ObjectId
            AzureADGroupID = $i.ObjectId
        }
    }
}

$result | Export-Csv ....


问:
ServerScriptService.MainScript:88: Expected 'end' (to close 'do' at line 15), got <eof>; did you forget to close 'then' at line 82?
Help me with this please.</p>
```<code>-- variebles define

local ReplicatedStorage = game: GetService("ReplicatedStorage")

local ServerStorage = game:GetService("ServerStorage")

local MapsFolder = ServerStorage:WaitForChild("Maps")

local Status = ReplicatedStorage:WaitForChild("Status")

local GameLength = 50

-- loop of the game

while true do

    Status.Value = "Waiting for players (This may take a bit)"

    repeat wait(1)  until game.Players.NumPlayers >= 2

        Status.Value = "Intermission"

        wait(15)

        local plrs = {}

        for i, player in pairs(game.Players:GetPlayers()) do
            if player then
                table.insert(plrs, player) -- add de playr to de plrs table
            end
        end

        wait(2)

        local AvailableMaps = MapsFolder:GetChildren()

        ["Grass,Snow"]

        local AvailableMaps = MapsFolder:GetChildren()

        local ChosenMap = AvailableMaps[math.random(1,2)]

        Status.Value = ChosenMap.Name.." Chosen"

        local ClonedMap = ChosenMap:Clone()
        ClonedMap.Parent = workspace

        --teleport de playr

        local grasstelepors = ClonedMap:FindFirstChild("grasstelepors")

        if not grasstelepors then
            print("no spawn m8")
        end

        local Availablegrasstelepors = grasstelepors:GetChildren()

        ["telepor"]"telepor","telepor","telepor"

        for i, player in pairs(plrs) do
            if player then
                character = player.Character

                if character then
                    --telepor em
                    character:FindFirstChild("HumanoidRootPart").CFrame = Availablegrasstelepors[1]
                    table.remove(Availablegrasstelepors,1)

                    --give them swords so they can violence

                    local Sword = ServerStorage.Sword:Clone()
                    Sword.Parent = player.Backpack

                    local GameTag = Instance.new("BoolValue")
                    GameTag.Name = "GameTag"
                    GameTag.Parent = player.Character

                else
                    --no charecter m8
                    if not player then
                        table.remove(plrs,i)
                    end
                end
        end

    end
</code>```

答:
The error is telling you everything.

The code expected there to be an end to close your while true do on line 15, but instead of finding it, it hit the end of the file.

It is even suggesting where you made the mistake, "did you forget to close your if player then statement on line 82?"

Add an end at the end of the code block to fix it.

Body:
Help me with this please.

-- variebles define

local ReplicatedStorage = game: GetService("ReplicatedStorage")

local ServerStorage = game:GetService("ServerStorage")

local MapsFolder = ServerStorage:WaitForChild("Maps")

local Status = ReplicatedStorage:WaitForChild("Status")

local GameLength = 50

-- loop of the game

while true do

    Status.Value = "Waiting for players (This may take a bit)"

    repeat wait(1)  until game.Players.NumPlayers >= 2

        Status.Value = "Intermission"

        wait(15)

        local plrs = {}

        for i, player in pairs(game.Players:GetPlayers()) do
            if player then
                table.insert(plrs, player) -- add de playr to de plrs table
            end
        end

        wait(2)

        local AvailableMaps = MapsFolder:GetChildren()

        ["Grass,Snow"]

        local AvailableMaps = MapsFolder:GetChildren()

        local ChosenMap = AvailableMaps[math.random(1,2)]

        Status.Value = ChosenMap.Name.." Chosen"

        local ClonedMap = ChosenMap:Clone()
        ClonedMap.Parent = workspace

        --teleport de playr

        local grasstelepors = ClonedMap:FindFirstChild("grasstelepors")

        if not grasstelepors then
            print("no spawn m8")
        end

        local Availablegrasstelepors = grasstelepors:GetChildren()

        ["telepor"]"telepor","telepor","telepor"

        for i, player in pairs(plrs) do
            if player then
                character = player.Character

                if character then
                    --telepor em
                    character:FindFirstChild("HumanoidRootPart").CFrame = Availablegrasstelepors[1]
                    table.remove(Availablegrasstelepors,1)

                    --give them swords so they can violence

                    local Sword = ServerStorage.Sword:Clone()
                    Sword.Parent = player.Backpack

                    local GameTag = Instance.new("BoolValue")
                    GameTag.Name = "GameTag"
                    GameTag.Parent = player.Character

                else
                    --no charecter m8
                    if not player then
                        table.remove(plrs,i)
                    end
                end
        end

    end


问:
How can I get a random item from multiple arrays based on a checkbox?
I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "

" + test[Math.floor(Math.random() * test.length)] + "

" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox"> txt<br>
<input type="checkbox"> test<br>
<input type="checkbox"> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p></code>```

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

答:
To get the values of your checkboxes, you need to give them actual values - and to reference the arrays without a bunch of IF statements, they need to be referencable in something like an object.

This will get random values from each array as it loops the forEach, but the final output needs to be shuffled (per your spec). There are many ways of doing this - I grabbed one of the more concise versions, but there are many to choose from here: How to randomize (shuffle) a JavaScript array?

function shuffle(a, b, c, d) { //array,placeholder,placeholder,placeholder
  c = a.length;
  while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d;
  return a
}

function myFunc() {
  let vars = {
    txt: ["txt1", "txt2", "txt3"],
    test: ["test1", "test2", "test3"],
    ran: ["ran1", "ran2", "ran3"]
  }

  // get the checked values into an array
  let flatArr = [];
  document.querySelectorAll('[type=checkbox]:checked').forEach(el => {
      flatArr = [...flatArr, vars[el.value][Math.floor(Math.random() * vars[el.value].length)]]
      });
    document.getElementById("tst").innerHTML = shuffle(flatArr).join(" ");
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" value='txt'> txt<br>
<input type="checkbox" value='test'> test<br>
<input type="checkbox" value='ran'> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p></code>```

Body:
I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "

" + test[Math.floor(Math.random() * test.length)] + "

" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}

<input type="checkbox"> txt

<input type="checkbox"> test

<input type="checkbox"> ran

<button onclick="myFunc()">One Character</button>

  sum text lol

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

Body:
To get the values of your checkboxes, you need to give them actual values - and to reference the arrays without a bunch of IF statements, they need to be referencable in something like an object.

This will get random values from each array as it loops the forEach, but the final output needs to be shuffled (per your spec). There are many ways of doing this - I grabbed one of the more concise versions, but there are many to choose from here: How to randomize (shuffle) a JavaScript array?

function shuffle(a, b, c, d) { //array,placeholder,placeholder,placeholder
  c = a.length;
  while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d;
  return a
}

function myFunc() {
  let vars = {
    txt: ["txt1", "txt2", "txt3"],
    test: ["test1", "test2", "test3"],
    ran: ["ran1", "ran2", "ran3"]
  }

  // get the checked values into an array
  let flatArr = [];
  document.querySelectorAll('[type=checkbox]:checked').forEach(el => {
      flatArr = [...flatArr, vars[el.value][Math.floor(Math.random() * vars[el.value].length)]]
      });
    document.getElementById("tst").innerHTML = shuffle(flatArr).join(" ");
  }

<input type="checkbox" value='txt'> txt<br>
<input type="checkbox" value='test'> test<br>
<input type="checkbox" value='ran'> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p>


问:
Github upload project - large files - venv
I am facing an issue: a Github's message saying the files are too big. What should I do?

Context: I am using python and venv in Windows. When I want to upload the project the files that are part of the venv (libraries, etc) become part of the uploading process (I never see this before. I used to use Linux), therefore the total files that should be in Github are a lot (and heavy).

I am considering to put all these folders (related to venv) into a .gitignore folder so I can avoid this issue, but I wonder what would be the impact of the project if I decide to run it locally.

Do any face a similar issue before? how can I deal with this?

答:
It's happening because you are trying to push all the dependency and library you installed locally on  your computer to github and it's like it very large.

By right you only need to push your source code and requirement.txt file to GitHub. You don't need to push all those library you installed locally to github

create a .gitignore file and place your venv file path in it.

Example

```<code>.gitignore file

/venv

</code>```

Body:
It's happening because you are trying to push all the dependency and library you installed locally on  your computer to github and it's like it very large.

By right you only need to push your source code and requirement.txt file to GitHub. You don't need to push all those library you installed locally to github

create a .gitignore file and place your venv file path in it.

Example

.gitignore file

/venv


问:
Extracting Data from a DICOMDIR file using Pydicom
I'm unable to read in a DICOM file as I usually would, citing the error:

```<code>AttributeError: 'DicomDir' object has no attribute 'DirectoryRecordSequence'
</code>```

I've tried:

pydicom.fileset.FileSet

using specific tags with dcmread

pydicom.filereader.read_dicomdir

pydicom.filereader.read_partial

using force=True in dcmread

pydicom.filereader.read_file_meta_info is about the only thing that's not returned an error and yields;

```<code>(0002, 0000) File Meta Information Group Length  UL: 172
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: Media Storage Directory Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 2.25.330614241706723499239981063503184149269
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.3.6.1.4.1.30071.8
(0002, 0013) Implementation Version Name         SH: 'fo-dicom 4.0.7'
</code>```

Moreover, the image is supposed to be a regular DICOM file, not a DICOMDIR. I can open the file in ImageJ and view header information there so I know the data is recoverable.
Is there a way for me to read in this file in Python or alternatively force it to ignore looking for DirectoryRecordSequence?

Edit:
Code and stacktrace from using FileSet:

```<code>from pydicom.fileset import FileSet
fs = FileSet("unprocessed.dcm")

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-2b6ba2e435fe> in <module>
      1 from pydicom.fileset import FileSet
----> 2 fs = FileSet("unprocessed.dcm")

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\fileset.py in __init__(self, ds)
    998         # Check the DICOMDIR dataset and create the record tree
    999         if ds:
-> 1000             self.load(ds)
   1001         else:
   1002             # New File-set

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\fileset.py in load(self, ds_or_path, include_orphans, raise_orphans)
   1641             ds = ds_or_path
   1642         else:
-> 1643             ds = dcmread(ds_or_path)
   1644
   1645         sop_class = ds.file_meta.get("MediaStorageSOPClassUID", None)

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\filereader.py in dcmread(fp, defer_size, stop_before_pixels, force, specific_tags)
   1027         stop_when = _at_pixel_data
   1028     try:
-> 1029         dataset = read_partial(
   1030             fp,
   1031             stop_when,

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\filereader.py in read_partial(fileobj, stop_when, defer_size, force, specific_tags)
    879             DeprecationWarning
    880         )
--> 881         ds = DicomDir(
    882             fileobj,
    883             dataset,

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\dicomdir.py in __init__(self, filename_or_obj, dataset, preamble, file_meta, is_implicit_VR, is_little_endian)
     94
     95         self.patient_records: List[Dataset] = []
---> 96         self.parse_records()
     97
     98     def parse_records(self) -> None:

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\dicomdir.py in parse_records(self)
    125
    126         # Build the mapping from file offsets to records
--> 127         records = self.DirectoryRecordSequence
    128         if not records:
    129             return

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\dataset.py in __getattr__(self, name)
    834             return {}
    835         # Try the base class attribute getter (fix for issue 332)
--> 836         return object.__getattribute__(self, name)
    837
    838     @property

AttributeError: 'DicomDir' object has no attribute 'DirectoryRecordSequence'
</code>```

答:
pydicom reads the dataset correctly, but because it identifies as Media Storage Directory it gets processed by the deprecated DicomDir class, even when passed directly to the FileSet class. Because the dataset isn't a valid Media Storage Directory instance this fails, producing the exception seen.

You should be able to fix this by changing the file meta information's (0002,0002) Media Storage SOP Class UID during read:

from pydicom import dcmread
from pydicom import config

def fix_sop_class(elem, **kwargs):
    if elem.tag == 0x00020002:
        # DigitalXRayImageStorageForProcessing
        elem = elem._replace(value=b"1.2.840.10008.5.1.4.1.1.1.1.1")

    return elem

config.data_element_callback = fix_sop_class

ds = dcmread('path/to/file')
```

By changing the SOP Class UID, that processing is skipped and the dataset returned.

Body:
I'm unable to read in a DICOM file as I usually would, citing the error:

AttributeError: 'DicomDir' object has no attribute 'DirectoryRecordSequence'

I've tried:

pydicom.fileset.FileSet

using specific tags with dcmread

pydicom.filereader.read_dicomdir

pydicom.filereader.read_partial

using force=True in dcmread

pydicom.filereader.read_file_meta_info is about the only thing that's not returned an error and yields;

(0002, 0000) File Meta Information Group Length  UL: 172
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: Media Storage Directory Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 2.25.330614241706723499239981063503184149269
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.3.6.1.4.1.30071.8
(0002, 0013) Implementation Version Name         SH: 'fo-dicom 4.0.7'

Moreover, the image is supposed to be a regular DICOM file, not a DICOMDIR. I can open the file in ImageJ and view header information there so I know the data is recoverable.
Is there a way for me to read in this file in Python or alternatively force it to ignore looking for DirectoryRecordSequence?

Edit:
Code and stacktrace from using FileSet:

from pydicom.fileset import FileSet
fs = FileSet("unprocessed.dcm")

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-2b6ba2e435fe> in <module>
      1 from pydicom.fileset import FileSet
----> 2 fs = FileSet("unprocessed.dcm")

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\fileset.py in __init__(self, ds)
    998         # Check the DICOMDIR dataset and create the record tree
    999         if ds:
-> 1000             self.load(ds)
   1001         else:
   1002             # New File-set

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\fileset.py in load(self, ds_or_path, include_orphans, raise_orphans)
   1641             ds = ds_or_path
   1642         else:
-> 1643             ds = dcmread(ds_or_path)
   1644
   1645         sop_class = ds.file_meta.get("MediaStorageSOPClassUID", None)

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\filereader.py in dcmread(fp, defer_size, stop_before_pixels, force, specific_tags)
   1027         stop_when = _at_pixel_data
   1028     try:
-> 1029         dataset = read_partial(
   1030             fp,
   1031             stop_when,

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\filereader.py in read_partial(fileobj, stop_when, defer_size, force, specific_tags)
    879             DeprecationWarning
    880         )
--> 881         ds = DicomDir(
    882             fileobj,
    883             dataset,

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\dicomdir.py in __init__(self, filename_or_obj, dataset, preamble, file_meta, is_implicit_VR, is_little_endian)
     94
     95         self.patient_records: List[Dataset] = []
---> 96         self.parse_records()
     97
     98     def parse_records(self) -> None:

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\dicomdir.py in parse_records(self)
    125
    126         # Build the mapping from file offsets to records
--> 127         records = self.DirectoryRecordSequence
    128         if not records:
    129             return

c:\****\appdata\local\programs\python\python38-32\lib\site-packages\pydicom\dataset.py in __getattr__(self, name)
    834             return {}
    835         # Try the base class attribute getter (fix for issue 332)
--> 836         return object.__getattribute__(self, name)
    837
    838     @property

AttributeError: 'DicomDir' object has no attribute 'DirectoryRecordSequence'

Body:
pydicom reads the dataset correctly, but because it identifies as Media Storage Directory it gets processed by the deprecated DicomDir class, even when passed directly to the FileSet class. Because the dataset isn't a valid Media Storage Directory instance this fails, producing the exception seen.

You should be able to fix this by changing the file meta information's (0002,0002) Media Storage SOP Class UID during read:

from pydicom import dcmread
from pydicom import config

def fix_sop_class(elem, **kwargs):
    if elem.tag == 0x00020002:
        # DigitalXRayImageStorageForProcessing
        elem = elem._replace(value=b"1.2.840.10008.5.1.4.1.1.1.1.1")

    return elem

config.data_element_callback = fix_sop_class

ds = dcmread('path/to/file')

By changing the SOP Class UID, that processing is skipped and the dataset returned.


问:
convert echo expression to ?> <?php
What would be the right syntax to convert this expression

```<code>echo '<input type="text" class="regular-text" name="first_name_title" value="'.$value5.'" placeholder="Write your First Name">';
</code>```

in the format

```<code>?>

    <input type="text" class="regular-text" name="first_name_title" value= ?????????????

<?php
</code>```

On the second format I can not find a way to set the value = $value5

答:
You can do this:</p>
```<code><?php
$var1="Xxx"
?>

<input type="text" class="regular-text" name="first_name_title" value= "<?php echo $var1; ?>"/>
</code>```

Title: convert echo expression to ?> <?php

Body:
What would be the right syntax to convert this expression

echo '<input type="text" class="regular-text" name="first_name_title" value="'.$value5.'" placeholder="Write your First Name">';

in the format

?>

    <input type="text" class="regular-text" name="first_name_title" value= ?????????????

<?php

On the second format I can not find a way to set the value = $value5

Body:
You can do this:

<?php
$var1="Xxx"
?>

<input type="text" class="regular-text" name="first_name_title" value= "<?php echo $var1; ?>"/>


问:
How to silently send a synchronous Lisp command to Autocad from c# code?
I am trying to silently send a synchronous Lisp command to autocad from c# code.

Here's how we send a Synchronous command to autocad.

```<code>string textToSend = $"(command-s \"_.-layout\" \"_t\" {filePath} {layoutName})";
object acadDoc = Application.DocumentManager.MdiActiveDocument.GetAcadDocument();
acadDoc.GetType().InvokeMember("SendCommand", BindingFlags.InvokeMethod, null, acadDoc, new[] { textToSend + "\n" });
</code>```

The command works but the problem is that the command ends up in autocad's command line and clogs up the history of the drafters using our extensions.

We tried modifying system variables CMDECHO, CMDDIA, and NOMUTT without success

Directly in autocad's command line manually

With the c# method SetSystemVariable()

The same way we called our InvokeMember("SendCommand")

In the same Lisp command where we do our action

I looked at the InvokeMember parameters but didn't see anything that might affect the display of the command like there exists for the ActiveDocument.SendTextToExecute() asynchronous command.

How do we send synchronous Lisp commands to autocad from c# code silently?

Ps: The reason why I am not using WBlockCloneObjects() is because it makes our apps extremely unstable. I am not really interested in opening that whole can of worms in this issue, I'm only stating this to explain why I ended up with the solution from my question.

答:
The title of my question was misleading. I didn't need to run lisp code silently, I needed to run commands in acad's command line silently. It just happened to be that acad's command line accepts lisp code so that's what I was using.

Instead of running lisp code, I used the method ActiveDocument.Editor.Command() to send my command to autocad. This method is synchronous and is affected by the system variable cmdecho.

I encountered a subsequent problem; because I was calling this method from a button in the banner with RelayCommand, Editor.Command was throwing the exception eInvalidInput because I was in the Application context instead of the Document context.

The best way to handle this was to split my first method in two and call the second method with ActiveDocument.SendStringToExecute() which uses the command line so I end up in the Document context. But because SendstringToExecute() is async, I had to rework my method's logic a bit.

Here is the final result (simplified)

```<code>private Layout Layout;

private RelayCommand _Command_Test;
public RelayCommand Command_Test
{
    get
    {
        if (_Command_Test == null)
        {
            _Command_Test = new RelayCommand(
                (param) =>
                {
                    FirstMethod();
                },
                (param) =>
                {
                    return true;
                }
            );
        }
        return _Command_Test;
    }
}

[CommandMethod("FirstMethod")]
public void FirstMethod()
{
    // Many actions and processing
    Layout = new Layout(/*With stuff*/);
    Application.DocumentManager.MdiActiveDocument.SendStringToExecute("SecondMethod ", true, false, false);
}

[CommandMethod("SecondMethod")]
public void SecondMethod()
{
    short cmdecho = (short)Application.GetSystemVariable("cmdecho");
    Application.SetSystemVariable("cmdecho", 0);

    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
    ed.Command("_.-layout", "_t", Layout.FilePath, Layout.Name);

    Application.SetSystemVariable("cmdecho", cmdecho);

    // Actions that need to be ran after the command
}
</code>```

I had to split my first method differently to have two sets of synchronous actions.

Because CommandMethod can't receive parameters, I had to store information in the fields of the class.

I skipped it in the code shown here but I, of course, used try-catches and transactions to handle potential issues.

Body:
I am trying to silently send a synchronous Lisp command to autocad from c# code.

Here's how we send a Synchronous command to autocad.

string textToSend = $"(command-s \"_.-layout\" \"_t\" {filePath} {layoutName})";
object acadDoc = Application.DocumentManager.MdiActiveDocument.GetAcadDocument();
acadDoc.GetType().InvokeMember("SendCommand", BindingFlags.InvokeMethod, null, acadDoc, new[] { textToSend + "\n" });

The command works but the problem is that the command ends up in autocad's command line and clogs up the history of the drafters using our extensions.

We tried modifying system variables CMDECHO, CMDDIA, and NOMUTT without success

Directly in autocad's command line manually

With the c# method SetSystemVariable()

The same way we called our InvokeMember("SendCommand")

In the same Lisp command where we do our action

I looked at the InvokeMember parameters but didn't see anything that might affect the display of the command like there exists for the ActiveDocument.SendTextToExecute() asynchronous command.

How do we send synchronous Lisp commands to autocad from c# code silently?

Ps: The reason why I am not using WBlockCloneObjects() is because it makes our apps extremely unstable. I am not really interested in opening that whole can of worms in this issue, I'm only stating this to explain why I ended up with the solution from my question.

Body:
The title of my question was misleading. I didn't need to run lisp code silently, I needed to run commands in acad's command line silently. It just happened to be that acad's command line accepts lisp code so that's what I was using.

Instead of running lisp code, I used the method ActiveDocument.Editor.Command() to send my command to autocad. This method is synchronous and is affected by the system variable cmdecho.

I encountered a subsequent problem; because I was calling this method from a button in the banner with RelayCommand, Editor.Command was throwing the exception eInvalidInput because I was in the Application context instead of the Document context.

The best way to handle this was to split my first method in two and call the second method with ActiveDocument.SendStringToExecute() which uses the command line so I end up in the Document context. But because SendstringToExecute() is async, I had to rework my method's logic a bit.

Here is the final result (simplified)

private Layout Layout;

private RelayCommand _Command_Test;
public RelayCommand Command_Test
{
    get
    {
        if (_Command_Test == null)
        {
            _Command_Test = new RelayCommand(
                (param) =>
                {
                    FirstMethod();
                },
                (param) =>
                {
                    return true;
                }
            );
        }
        return _Command_Test;
    }
}

[CommandMethod("FirstMethod")]
public void FirstMethod()
{
    // Many actions and processing
    Layout = new Layout(/*With stuff*/);
    Application.DocumentManager.MdiActiveDocument.SendStringToExecute("SecondMethod ", true, false, false);
}

[CommandMethod("SecondMethod")]
public void SecondMethod()
{
    short cmdecho = (short)Application.GetSystemVariable("cmdecho");
    Application.SetSystemVariable("cmdecho", 0);

    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
    ed.Command("_.-layout", "_t", Layout.FilePath, Layout.Name);

    Application.SetSystemVariable("cmdecho", cmdecho);

    // Actions that need to be ran after the command
}

I had to split my first method differently to have two sets of synchronous actions.

Because CommandMethod can't receive parameters, I had to store information in the fields of the class.

I skipped it in the code shown here but I, of course, used try-catches and transactions to handle potential issues.


问:
Bootstrap Drop down button not dropping down
So I added a drop down button at the end of my table, and for some reason when I click on it, nothing drops down. I see no errors on my console either. Is there something in my CSS that could be preventing it from working?

HTML Code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="public/stylesheets/grayscale.css">
  <title>tech</title>
</head>

<body>
<div id="Tech" class="header">
  <center><img src="public/images/test.png" id='Logo' alt="Logo">
  </center>
</div>

<form id="upload" action="index.html" method="POST" enctype="multipart/form-data">
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<div>
    <div id="filedrag">
        <img src="public/images/upload3.png" alt="draganddrop">
    </div>
    <input type="file" id="fileselect" name="fileselect[]" multiple="multiple"/>
</div>
</fieldset>
</form>

<div id="messages">
</div>

<table id="data-table" class="container">
  <thead>
    <tr>
      <th>
        <h3>Video</h3>
      </th>
      <th>
        <h3>Original Size</h3>
      </th>
      <th>
        <h3>Compressed Size</h3>
      </th>
      <th>
        <h3>Compressed rate</h3>
      </th>
      <th>
        <h3>Savings</h3>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Video1 File Name</td>
      <td>Original File Size</td>
      <td>6369</td>
      <td>01:32:50</td>
      <td>450</td>
      <td>
        <div class="container">
          <div class="dropdown">
            <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Compress
            <span class="caret"></span></button>
            <ul class="dropdown-menu">
              <li><a href="#">Compress</a></li>
              <li class="disabled"><a href="#">Download</a></li>
              <li class="active"><a href="#">Delete</a></li>
            </ul>
          </div>
        </div>
      </td>
    </tr>
    <tr>
      <td>Video 2 File Name</td>
      <td>Original File Size</td>
      <td>10437</td>
      <td>00:51:22</td>
      <td>450</td>
      <td>
        <div class="container">
          <div class="dropdown">
            <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Compress
            <span class="caret"></span></button>
            <ul class="dropdown-menu">
              <li><a href="#">Compress</a></li>
              <li class="disabled"><a href="#">Download</a></li>
              <li class="active"><a href="#">Delete</a></li>
            </ul>
          </div>
        </div>
      </td>
    </tr>
    <tr>
      <td>Video 3 File Name</td>
      <td>Original File Size</td>
      <td>5327</td>
      <td>00:24:34</td>
      <td>450</td>
      <td>
        <div class="container">
          <div class="dropdown">
            <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Compress
            <span class="caret"></span></button>
            <ul class="dropdown-menu">
              <li><a href="#">Compress</a></li>
              <li class="disabled"><a href="#">Download</a></li>
              <li class="active"><a href="#">Delete</a></li>
            </ul>
          </div>
        </div>
      </td>
    </tr>
  </tbody>
</table>

</body>
<script src="public/js/filedrag.js"></script>
</html>
</code>```

CSS Code:

```<code>@charset "UTF-8";
@import url(http://fonts.googleapis.com/css?family=Open+Sans:300,400,700);

body {
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
  line-height: 1.42em;
  color:#A7A1AE;
  background-color:#1F2739;
}

.data-table{
    margin-top: 250px;
}

#filedrag{
    text-align: center;
    border-radius: 7px;
    cursor: default;
}

#filedrag.hover{
    color: #f00;
    border-color: #f00;
    border-style: solid;
    box-shadow: inset 0 3px 4px #888;
}

#title{
    text-align: center;
}

#logo{
    float: right;
}

.header img {
    float:left;
    border: 5px;
    padding:5px;
    width: 4em;
    height: 4em;
    border-radius: 10px;
}

.header h1 {
  position:relative;
  font-size:3em;
  font-weight: 300;
  line-height:1em;
  text-align: left;
  color: #FFFFFF;
}

h1 {
  font-size:3em;
  font-weight: 300;
  line-height:1em;
  text-align: center;
  color: #FFFFFF;
}

h2 {
  font-size:1em;
  font-weight: 300;
  text-align: center;
  display: block;
  line-height:1em;
  padding-bottom: 2em;
  color: #FB667A;
}

h2 a {
  font-weight: 700;
  text-transform: uppercase;
  color: #FB667A;
  text-decoration: none;
}

h3{
    color: white;
}

h4{
    text-align: center;
    font-size: 2em;
}

#Register
{
    margin-left: 750px;
    margin-top: 27px;
}
.btn-update{
    position: absolute;
    bottom: 0;
    margin-bottom: 300px;
    margin-left: -65px;
}

.hideshow{
    position: absolute;
    bottom: 0;
    margin-bottom: 300px;
    margin-left: -65px;
}

.blue { color: #185875; }
.yellow { color: #FFF842; }

.container th h1 {
      font-weight: bold;
      font-size: 1em;
  text-align: left;
  color: #185875;
}

.container td {
      font-weight: normal;
      font-size: 1em;
  -webkit-box-shadow: 0 2px 2px -2px #0E1119;
       -moz-box-shadow: 0 2px 2px -2px #0E1119;
            box-shadow: 0 2px 2px -2px #0E1119;
}

.container {
      text-align: left;
      overflow: hidden;
      width: 80%;
      margin: 0 auto;
  display: table;
  padding: 0 0 8em 0;
}

.container td, .container th {
    padding-bottom: 2%;
    padding-top: 2%;
    padding-left:2%;
}

/* Background-color of the odd rows */
.container tr:nth-child(odd) {
      background-color: #323C50;
}

/* Background-color of the even rows */
.container tr:nth-child(even) {
      background-color: #2C3446;
}

.container th {
      background-color: #1F2739;
}

.container_graph {
  width: 80%;
  margin: 15px auto;
  margin-top: 175px;
}

.container td:first-child { color: #FB667A; }

.container tr:hover {
   background-color: #464A52;
-webkit-box-shadow: 0 6px 6px -6px #0E1119;
       -moz-box-shadow: 0 6px 6px -6px #0E1119;
            box-shadow: 0 6px 6px -6px #0E1119;
}

.container td:hover {
  /*background-color: #FFF842;*/
  /*color: #403E10;*/

  transition-delay: 0s;
      transition-duration: 0.4s;
      transition-property: all;
  transition-timing-function: line;
}

@media (max-width: 800px) {
.container td:nth-child(4),
.container th:nth-child(4) { display: none; }
}
</code>```

答:
Add these dependencies, right before the ending  tag,

```<code><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</code>```

Body:
So I added a drop down button at the end of my table, and for some reason when I click on it, nothing drops down. I see no errors on my console either. Is there something in my CSS that could be preventing it from working?

HTML Code:

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">

  <link rel="stylesheet" type="text/css" href="public/stylesheets/grayscale.css">
  <title>tech</title>

<form id="upload" action="index.html" method="POST" enctype="multipart/form-data">
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />

    <input type="file" id="fileselect" name="fileselect[]" multiple="multiple"/>

</fieldset>
</form>

Video

Original Size

Compressed Size

Compressed rate

Savings

      Video1 File Name
      Original File Size
      6369
      01:32:50
      450

            <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Compress
            </button>

Compress

Download

Delete

      Video 2 File Name
      Original File Size
      10437
      00:51:22
      450

            <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Compress
            </button>

Compress

Download

Delete

      Video 3 File Name
      Original File Size
      5327
      00:24:34
      450

            <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Compress
            </button>

Compress

Download

Delete

CSS Code:

@charset "UTF-8";
@import url(http://fonts.googleapis.com/css?family=Open+Sans:300,400,700);

body {
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
  line-height: 1.42em;
  color:#A7A1AE;
  background-color:#1F2739;
}

.data-table{
    margin-top: 250px;
}

#filedrag{
    text-align: center;
    border-radius: 7px;
    cursor: default;
}

#filedrag.hover{
    color: #f00;
    border-color: #f00;
    border-style: solid;
    box-shadow: inset 0 3px 4px #888;
}

#title{
    text-align: center;
}

#logo{
    float: right;
}

.header img {
    float:left;
    border: 5px;
    padding:5px;
    width: 4em;
    height: 4em;
    border-radius: 10px;
}

.header h1 {
  position:relative;
  font-size:3em;
  font-weight: 300;
  line-height:1em;
  text-align: left;
  color: #FFFFFF;
}

h1 {
  font-size:3em;
  font-weight: 300;
  line-height:1em;
  text-align: center;
  color: #FFFFFF;
}

h2 {
  font-size:1em;
  font-weight: 300;
  text-align: center;
  display: block;
  line-height:1em;
  padding-bottom: 2em;
  color: #FB667A;
}

h2 a {
  font-weight: 700;
  text-transform: uppercase;
  color: #FB667A;
  text-decoration: none;
}

h3{
    color: white;
}

h4{
    text-align: center;
    font-size: 2em;
}

#Register
{
    margin-left: 750px;
    margin-top: 27px;
}
.btn-update{
    position: absolute;
    bottom: 0;
    margin-bottom: 300px;
    margin-left: -65px;
}

.hideshow{
    position: absolute;
    bottom: 0;
    margin-bottom: 300px;
    margin-left: -65px;
}

.blue { color: #185875; }
.yellow { color: #FFF842; }

.container th h1 {
      font-weight: bold;
      font-size: 1em;
  text-align: left;
  color: #185875;
}

.container td {
      font-weight: normal;
      font-size: 1em;
  -webkit-box-shadow: 0 2px 2px -2px #0E1119;
       -moz-box-shadow: 0 2px 2px -2px #0E1119;
            box-shadow: 0 2px 2px -2px #0E1119;
}

.container {
      text-align: left;
      overflow: hidden;
      width: 80%;
      margin: 0 auto;
  display: table;
  padding: 0 0 8em 0;
}

.container td, .container th {
    padding-bottom: 2%;
    padding-top: 2%;
    padding-left:2%;
}

/* Background-color of the odd rows */
.container tr:nth-child(odd) {
      background-color: #323C50;
}

/* Background-color of the even rows */
.container tr:nth-child(even) {
      background-color: #2C3446;
}

.container th {
      background-color: #1F2739;
}

.container_graph {
  width: 80%;
  margin: 15px auto;
  margin-top: 175px;
}

.container td:first-child { color: #FB667A; }

.container tr:hover {
   background-color: #464A52;
-webkit-box-shadow: 0 6px 6px -6px #0E1119;
       -moz-box-shadow: 0 6px 6px -6px #0E1119;
            box-shadow: 0 6px 6px -6px #0E1119;
}

.container td:hover {
  /*background-color: #FFF842;*/
  /*color: #403E10;*/

  transition-delay: 0s;
      transition-duration: 0.4s;
      transition-property: all;
  transition-timing-function: line;
}

@media (max-width: 800px) {
.container td:nth-child(4),
.container th:nth-child(4) { display: none; }
}

Body:
Add these dependencies, right before the ending </body> tag,

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


问:
Is there a way I could get a email when someone submits my contact form using JavaScript?
I made a contact form using HTML and JavaScript. The text editor I am using right now only supports HTML and JavaScript CSS and markdown files. I made contact form using HTML and JavaScript but I don’t know how to make the users content go into my mailbox. Like I don’t know how the email could come to my mailbox so I could see their issue. Here’s my code for the contact form.
HTML:

```<code>
<!DOCTYPE html>
<html>
<head>
<title>Contact Form using JavaScript</title> <!-- Include CSS file here -->
<link href="css/form.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>Contact Form using JavaScript</h1>
<div id="form_sample"></div> <!-- Include JS file here -->
<script src="form.js"></script>
</div>
</body>
</html>
</code>```

Here’s the JavaScript.

```<code>// Fetching HTML Elements in Variables by ID.
var x = document.getElementById("form_sample");
var createform = document.createElement('form'); // Create New Element Form
createform.setAttribute("action", ""); // Setting Action Attribute on Form
createform.setAttribute("method", "post"); // Setting Method Attribute on Form
x.appendChild(createform);

var heading = document.createElement('h2'); // Heading of Form
heading.innerHTML = "Contact Form ";
createform.appendChild(heading);

var line = document.createElement('hr'); // Giving Horizontal Row After Heading
createform.appendChild(line);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var namelabel = document.createElement('label'); // Create Label for Name Field
namelabel.innerHTML = "Your Name : "; // Set Field Labels
createform.appendChild(namelabel);

var inputelement = document.createElement('input'); // Create Input Field for Name
inputelement.setAttribute("type", "text"); inputelement.setAttribute("name", "dname");
createform.appendChild(inputelement);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var emaillabel = document.createElement('label'); // Create Label for E-mail Field
emaillabel.innerHTML = "Your Email : ";
createform.appendChild(emaillabel);

var emailelement = document.createElement('input'); // Create Input Field for E-mail
emailelement.setAttribute("type", "text");
emailelement.setAttribute("name", "demail");
createform.appendChild(emailelement);

var emailbreak = document.createElement('br');
createform.appendChild(emailbreak);

var messagelabel = document.createElement('label'); // Append Textarea
messagelabel.innerHTML = "Your Message : ";
createform.appendChild(messagelabel);

var texareaelement = document.createElement('textarea');
texareaelement.setAttribute("name", "dmessage");
createform.appendChild(texareaelement);

var messagebreak = document.createElement('br'); createform.appendChild(messagebreak);

var submitelement = document.createElement('input'); // Append Submit Button
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
createform.appendChild(submitelement); ```

Any help is appreciated.
```

答:
To continue on Barmar's comments:

Yes you will need a to use a server-side language like PHP to send mails.
There is an excellent library, that I personally use all the time that makes this pretty simple: PHPMailer.

Or if you prefer to not use a library, there are plenty of tutorials that give a step-by-step guide on how this can be done:

W3Schools.com

Tutorialspoint.com

TutorialRepublic.com

Once you've gone through some of these tutorials (and you don't have a server/hosting service) you can use a localserver to do some testing. There are specific steps you will need to take to accomplish this with localhost, but it is do-able. Some examples of how this can be done:

Guide by CodexWorld

Guide by PHPFlow

Body:
I made a contact form using HTML and JavaScript. The text editor I am using right now only supports HTML and JavaScript CSS and markdown files. I made contact form using HTML and JavaScript but I don’t know how to make the users content go into my mailbox. Like I don’t know how the email could come to my mailbox so I could see their issue. Here’s my code for the contact form.
HTML:

<!DOCTYPE html>

<title>Contact Form using JavaScript</title>
<link href="css/form.css" rel="stylesheet">

Contact Form using JavaScript

Here’s the JavaScript.

// Fetching HTML Elements in Variables by ID.
var x = document.getElementById("form_sample");
var createform = document.createElement('form'); // Create New Element Form
createform.setAttribute("action", ""); // Setting Action Attribute on Form
createform.setAttribute("method", "post"); // Setting Method Attribute on Form
x.appendChild(createform);

var heading = document.createElement('h2'); // Heading of Form
heading.innerHTML = "Contact Form ";
createform.appendChild(heading);

var line = document.createElement('hr'); // Giving Horizontal Row After Heading
createform.appendChild(line);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var namelabel = document.createElement('label'); // Create Label for Name Field
namelabel.innerHTML = "Your Name : "; // Set Field Labels
createform.appendChild(namelabel);

var inputelement = document.createElement('input'); // Create Input Field for Name
inputelement.setAttribute("type", "text"); inputelement.setAttribute("name", "dname");
createform.appendChild(inputelement);

var linebreak = document.createElement('br');
createform.appendChild(linebreak);

var emaillabel = document.createElement('label'); // Create Label for E-mail Field
emaillabel.innerHTML = "Your Email : ";
createform.appendChild(emaillabel);

var emailelement = document.createElement('input'); // Create Input Field for E-mail
emailelement.setAttribute("type", "text");
emailelement.setAttribute("name", "demail");
createform.appendChild(emailelement);

var emailbreak = document.createElement('br');
createform.appendChild(emailbreak);

var messagelabel = document.createElement('label'); // Append Textarea
messagelabel.innerHTML = "Your Message : ";
createform.appendChild(messagelabel);

var texareaelement = document.createElement('textarea');
texareaelement.setAttribute("name", "dmessage");
createform.appendChild(texareaelement);

var messagebreak = document.createElement('br'); createform.appendChild(messagebreak);

var submitelement = document.createElement('input'); // Append Submit Button
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
createform.appendChild(submitelement); ```

Any help is appreciated.