问:
Decrease the size of the background of a text box using bootstrap carousel
I am using Bootstrap 4.0 and the carousel class. I have a caption for each image that is part of the carousel, and would like to decrease the width of the background of the caption since it is wider than the text. (see yellow arrows below) I have used different bootstrap classes such as d-md-flex, but it moves the entire text box to the left.

How can I decrease the width of the background?  The text is not dynamic, so although it would be preferable to have a flex option, I can use a fixed or maximum width. It needs to be centered though.

Thanks!

```<code><div class="carousel-item">
  <img class="d-block w-100" src="img/t/flowers.svg" alt="Creativity">
  <div class="carousel-caption d-none d-md-block text-dark">
    <h1 style="background-color: rgba(250, 250, 250,0.5);">Everyday Creativity</h1>
  </div>
</div>
</code>```

答:
you can decrease the width of h1 to its content via max-content or display:table; for older browsers :

body {background:tomato;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><code>max-content</code><h1 style="background-color: rgba(250, 250, 250,0.5);margin:1em auto;width:max-content;">Everyday Creativity</h1>
<code>display:table;</code><h1 style="background-color: rgba(250, 250, 250,0.5);margin:1em auto;display:table;">Everyday Creativity</h1></code>```

infos :

https://developer.mozilla.org/en-US/docs/Web/CSS/width#max-content

https://developer.mozilla.org/en-US/docs/Web/CSS/display

Body:
I am using Bootstrap 4.0 and the carousel class. I have a caption for each image that is part of the carousel, and would like to decrease the width of the background of the caption since it is wider than the text. (see yellow arrows below) I have used different bootstrap classes such as d-md-flex, but it moves the entire text box to the left.

How can I decrease the width of the background?  The text is not dynamic, so although it would be preferable to have a flex option, I can use a fixed or maximum width. It needs to be centered though.

Thanks!

Everyday Creativity

Body:
you can decrease the width of h1 to its content via max-content or display:table; for older browsers :

body {background:tomato;}

<code>max-content</code><h1 style="background-color: rgba(250, 250, 250,0.5);margin:1em auto;width:max-content;">Everyday Creativity</h1>
<code>display:table;</code><h1 style="background-color: rgba(250, 250, 250,0.5);margin:1em auto;display:table;">Everyday Creativity</h1>

infos :

https://developer.mozilla.org/en-US/docs/Web/CSS/width#max-content

https://developer.mozilla.org/en-US/docs/Web/CSS/display


来源: stackexchange

问:
how do I save samples in an array or matrix in R?
I am okay with Python, Numpy but trying R and this seemingly simple operation has me stuck in R.

This is what I have but I get a number of items to replace is not a multiple of replacement length error.

```<code># find sample variance with n
samples <- matrix(0, nrow=num_samples, ncol=samp_size)
for(i in 1:10000){
  temp <- sample(population, samp_size, replace=TRUE)
  samples[i] = temp
}
samples[0]
</code>```

I am not hung up on using matrices, can be an array or vector or list or anything but just some standard ways of doing this because searching online did not give me a quick answer for this basic operation.

答:
Have you tried replicate?

```<code>samples <- t(replicate(n = num_samples, sample(population, samp_size, replace=TRUE),simplify = "array"))
</code>```

This will return a matrix of the dimensions samp_size x num_samples.

ContentLicense: CC BY-SA 4.0

Body:
I am okay with Python, Numpy but trying R and this seemingly simple operation has me stuck in R.

This is what I have but I get a number of items to replace is not a multiple of replacement length error.

# find sample variance with n
samples <- matrix(0, nrow=num_samples, ncol=samp_size)
for(i in 1:10000){
  temp <- sample(population, samp_size, replace=TRUE)
  samples[i] = temp
}
samples[0]

I am not hung up on using matrices, can be an array or vector or list or anything but just some standard ways of doing this because searching online did not give me a quick answer for this basic operation.

Body:
Have you tried replicate?

samples <- t(replicate(n = num_samples, sample(population, samp_size, replace=TRUE),simplify = "array"))

This will return a matrix of the dimensions samp_size x num_samples.


问:
JavaScript Dropdown Box Issue - Array Map not working
I'm new to JavaScript and I am having a massive problem trying to populate a dropdown box with values that are getting queried from a SQL database and returned as a JSON file. My server code seems to work well querying the DB and if I hit the server directly it gives me the following JSON data:

```<code>[{
    "key": "1AEFF22E-7A2C-4920-B72A-255119E785A8",
    "value": "ExampleSSRSProject"
}, {
    "key": "5A8AE6D3-4A96-4048-9207-6DDDA5B7D19E",
    "value": "MyReportPackage"
}, {
    "key": "EA2CD590-FA01-4094-86EE-414C860E597A",
    "value": "CoverSheet"
}]
</code>```

However, when I run the client page code I just get the error:

"Warning: Each child in a list should have a unique "key" prop".

Below I have listed my code from the server.js, client componentDidMount(), and the render.

```<code>    app.get('/api/reportList', (req,res) => {
connection.connect(err=>{
    if(err){
      console.log(err);
      res.statusCode = 200;
      res.setHeader('content','text/plain');
      res.end(err);
    }
    else{
        var sqlrequest = new sql.Request(connection);
        sqlrequest.query("select ItemId as 'key',Name as 'value' FROM
         ReportServer$SQL2014.dbo.Catalog where Name <> ''",(err,result)=>{
          if(err){
              console.log(`SQL Error`);
              res.statusCode = 200;
              res.setHeader('content','text/plain');
              res.end("SQL Error");
            }
            else{
              console.log(result);
              res.statusCode = 200;
              res.setHeader('content','text/plain');
              res.json(result.recordset);
              connection.close();
            }
        })

    }
})
});

    componentDidMount() {
fetch("api/reportList")
.then((response) => {
  return response.json();
})
.then(data => {
  let reportsFromApi = data.map((report,index) => {
    return {key: {index}, display: report}
  });
  this.setState({
    reports: reportsFromApi
  });
}).catch(error => {
  console.log(error);
});

      render() {
    return (
      <div>
  <select>
    {this.state.reports.map((report) => <option key={report.ItemId} value={report.Name}
  >{report.Name}</option>)}
  </select>
      </div>
    )
  }

 import React, {Component} from 'react';
 import logo from './logo.svg';
 import './App.css';

 import ReportList from './components/reportList/reportList';

 class App extends Component {
   render() {
     return (
     <div className="App">
       <ReportList/>
       </div>
     );
   }
 }

 export default App;
</code>```

答:
I think that is because in your React component, you use the ItemId attribute as the "key" prop.

```<code>{this.state.reports.map((report) => <option key={report.ItemId} value={report.Name}>...</option>)}
</code>```

The problem is that your "report" objects that are passed from your server code to your client code don't seem to have an "ItemId" property. That means all of your option elements are passed a "key" property that is equal to undefined and therefore, that is not unique.

You could use the "key" attribute of your "report" objects though, like this:

```<code>{this.state.reports.map((report) => <option key={report.key} value={report.Name}>...</option>)}
</code>```

Body:
I'm new to JavaScript and I am having a massive problem trying to populate a dropdown box with values that are getting queried from a SQL database and returned as a JSON file. My server code seems to work well querying the DB and if I hit the server directly it gives me the following JSON data:

[{
    "key": "1AEFF22E-7A2C-4920-B72A-255119E785A8",
    "value": "ExampleSSRSProject"
}, {
    "key": "5A8AE6D3-4A96-4048-9207-6DDDA5B7D19E",
    "value": "MyReportPackage"
}, {
    "key": "EA2CD590-FA01-4094-86EE-414C860E597A",
    "value": "CoverSheet"
}]

However, when I run the client page code I just get the error:

"Warning: Each child in a list should have a unique "key" prop".

Below I have listed my code from the server.js, client componentDidMount(), and the render.

    app.get('/api/reportList', (req,res) => {
connection.connect(err=>{
    if(err){
      console.log(err);
      res.statusCode = 200;
      res.setHeader('content','text/plain');
      res.end(err);
    }
    else{
        var sqlrequest = new sql.Request(connection);
        sqlrequest.query("select ItemId as 'key',Name as 'value' FROM
         ReportServer$SQL2014.dbo.Catalog where Name <> ''",(err,result)=>{
          if(err){
              console.log(`SQL Error`);
              res.statusCode = 200;
              res.setHeader('content','text/plain');
              res.end("SQL Error");
            }
            else{
              console.log(result);
              res.statusCode = 200;
              res.setHeader('content','text/plain');
              res.json(result.recordset);
              connection.close();
            }
        })

    }
})
});

    componentDidMount() {
fetch("api/reportList")
.then((response) => {
  return response.json();
})
.then(data => {
  let reportsFromApi = data.map((report,index) => {
    return {key: {index}, display: report}
  });
  this.setState({
    reports: reportsFromApi
  });
}).catch(error => {
  console.log(error);
});

      render() {
    return (

  <select>
    {this.state.reports.map((report) => <option key={report.ItemId} value={report.Name}
  >{report.Name}</option>)}
  </select>

    )
  }

 import React, {Component} from 'react';
 import logo from './logo.svg';
 import './App.css';

 import ReportList from './components/reportList/reportList';

 class App extends Component {
   render() {
     return (

       <ReportList/>

     );
   }
 }

 export default App;

Body:
I think that is because in your React component, you use the ItemId attribute as the "key" prop.

{this.state.reports.map((report) => <option key={report.ItemId} value={report.Name}>...</option>)}

The problem is that your "report" objects that are passed from your server code to your client code don't seem to have an "ItemId" property. That means all of your option elements are passed a "key" property that is equal to undefined and therefore, that is not unique.

You could use the "key" attribute of your "report" objects though, like this:

{this.state.reports.map((report) => <option key={report.key} value={report.Name}>...</option>)}


问:
which is a better approach for fibonacci series generation
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

```<code>#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}
</code>```

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

答:
As was said before, the advantage of the static variables is, in principle, that it's cheaper to calculate the n -th Element of a sequence where the n - 1 -th has already been evaluated.

The big drawback, apart from the problems inherent to static variables, is that you don't have any way to get back to an earlier point in the sequence, nor do you really have a good control over where in the sequence you are at a given time.

Using a class, as recommended by Sevis, is certainly the better way of implementing such a static-like approach: this makes everything safer, gives you an easy way to get back to the sequence start (by simply reinitializing the object) and also makes it possible to implement further functionality, like going back k steps, looking up the present position, etc..

ContentLicense: CC BY-SA 3.0

Body:
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?


问:
ag-grid column menu reset columns event?
Does ag-grid have a grid event that corresponds to to the "Reset Columns" item that is at the bottom of each column menu?

I need to do some special processing on "Reset Columns", and different handling of column "move", "resize", (etc.).  I setup an event handler for the "columnEverythingChanged" event and a different event handler for "columnMoved" (etc.).  I found that:

1) When no changes have been made to any column and I press "Reset Columns", "columnEverythingChanged" gets called.  Fine.
2) When one or more columns have been changed and I press "Reset Columns", both "columnEverythingChanged" AND "columnMoved" (or other) get called.

My problem: in case (2), my "columnMoved" logic should not run.

A secondary problem: "columnEverythingChanged" also gets called at application startup.  Not a big deal, but I had to hack around it.

答: This was so long ago, I don't remember the details.  But in my code, I see that I use the columnMoved, columnResized, columnVisible, filterChanged, and sortChanged events. I run the same function on all of these events. That function debounces the event before doing my special processing.</p>


问:
Compressing vertical extent in 3-D MatPlotLib figures
I'm working with 2-D matrices, where the entries are elevation, and am trying to plot them with MatPlotLib mplot3d. How can I adjust the vertical height of the resulting figure? To give an example, pulling from code in the mplot3d tutorial:

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Configure z-axis.
ax.set_zlim(-1.01, 1.01)

plt.show()

</code>```

This gives:

I'd like to compress the picture vertically so that the 1.00 mark on the z-axis gets pushed down to present position of -0.75.

Changing the z-limit with ax.set_zlim(-1.01, 10.01) flattens the data but keeps the figure the same height. I've also experimented with statements like plt.figure(figsize=(20,5)), but that changes the figure size and interferes with rotating the resulting plot in 3-D.

How do I compress down just the z-axis?

答:
Thanks to @sheldore—this answer does the trick.

Adding:

```<code>scale_x = 1
scale_y = 1
scale_z = 0.25

ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([scale_x, scale_y, scale_z, 1]))
</code>```

Gives the following plot, which will do exactly what I want after tinkering with axis numbering.

Body:
I'm working with 2-D matrices, where the entries are elevation, and am trying to plot them with MatPlotLib mplot3d. How can I adjust the vertical height of the resulting figure? To give an example, pulling from code in the mplot3d tutorial:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Configure z-axis.
ax.set_zlim(-1.01, 1.01)

plt.show()

This gives:

I'd like to compress the picture vertically so that the 1.00 mark on the z-axis gets pushed down to present position of -0.75.

Changing the z-limit with ax.set_zlim(-1.01, 10.01) flattens the data but keeps the figure the same height. I've also experimented with statements like plt.figure(figsize=(20,5)), but that changes the figure size and interferes with rotating the resulting plot in 3-D.

How do I compress down just the z-axis?

Body:
Thanks to @sheldore—this answer does the trick.

Adding:

scale_x = 1
scale_y = 1
scale_z = 0.25

ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([scale_x, scale_y, scale_z, 1]))

Gives the following plot, which will do exactly what I want after tinkering with axis numbering.


问:
Find and Replace text in Eclipse
I am using eclipse IDE.I need to modify thousands of hbm.xml file by replacing the text generate="always" to generate="never". Please tell  me the easiest way.

答: The eclipse search dialogs offer a global find and replace in text files.

Title: Find and Replace text in Eclipse


问:
Why the newtype syntax creates a function
I look at this declaration:

```<code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
</code>```

Here is what I understand:

1) Parser  is declared as a type with a type parameter a

2) You can instantiate Parser by providing a parser function for example p = Parser  (\s -> Nothing)

What I observed is that suddenly I have a function name parse defined and it is capable of running Parsers.

For example, I can run:

```<code>parse (Parser  (\s -> Nothing)) "my input"
</code>```

and get Nothing as output.

How was this parse function got defined with this specific signature? How does this function "know" to execute the Parser given to it? Hope that someone can clear my confusion.

Thanks!

答:
When you write newtype Parser a = Parser { parse :: String -> Maybe (a,String) } you introduce three things:

A type named  Parser.

A term level constructor of Parsers named Parser. The type of this function is

Parser :: (String -> Maybe (a, String)) -> Parser a
```

<p>You give it a function and it wraps it inside a <code>Parser</code></p>

<ol start="3">
<li>A function named <code>parse</code> to remove the <code>Parser</code> wrapper and get your function back. The type of this function is:</li>
</ol>

<pre class="lang-hs prettyprint-override"><code>parse :: Parser a -> String -> Maybe (a, String)
</code>```

Check yourself in ghci:

```<code>Prelude> newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
Prelude> :t Parser
Parser :: (String -> Maybe (a, String)) -> Parser a
Prelude> :t parse
parse :: Parser a -> String -> Maybe (a, String)
Prelude>
</code>```

It's worth nothing that the term level constructor (Parser) and the function to remove the wrapper (parse) are both arbitrary names and don't need to match the type name. It's common for instance to write:

```<code>newtype Parser a = Parser { unParser :: String -> Maybe (a,String) }
</code>```

this makes it clear unParse removes the wrapper around the parsing function. However, I recommend your type and constructor have the same name when using newtypes.

How does this function "know" to execute the Parser given to it

You are unwrapping the function using parse and then calling the unwrapped function with "myInput".

Body:
I look at this declaration:

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

Here is what I understand:

1) Parser  is declared as a type with a type parameter a

2) You can instantiate Parser by providing a parser function for example p = Parser  (\s -> Nothing)

What I observed is that suddenly I have a function name parse defined and it is capable of running Parsers.

For example, I can run:

parse (Parser  (\s -> Nothing)) "my input"

and get Nothing as output.

How was this parse function got defined with this specific signature? How does this function "know" to execute the Parser given to it? Hope that someone can clear my confusion.

Thanks!

Body:
When you write newtype Parser a = Parser { parse :: String -> Maybe (a,String) } you introduce three things:

A type named  Parser.

A term level constructor of Parsers named Parser. The type of this function is

Parser :: (String -> Maybe (a, String)) -> Parser a

You give it a function and it wraps it inside a Parser

A function named parse to remove the Parser wrapper and get your function back. The type of this function is:

parse :: Parser a -> String -> Maybe (a, String)

Check yourself in ghci:

Prelude> newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
Prelude> :t Parser
Parser :: (String -> Maybe (a, String)) -> Parser a
Prelude> :t parse
parse :: Parser a -> String -> Maybe (a, String)
Prelude>

It's worth nothing that the term level constructor (Parser) and the function to remove the wrapper (parse) are both arbitrary names and don't need to match the type name. It's common for instance to write:

newtype Parser a = Parser { unParser :: String -> Maybe (a,String) }

this makes it clear unParse removes the wrapper around the parsing function. However, I recommend your type and constructor have the same name when using newtypes.

How does this function "know" to execute the Parser given to it

You are unwrapping the function using parse and then calling the unwrapped function with "myInput".


问:
Is it possible to reuse a double quoted string with variables?
The application I'm writing generates some HTML server side though it could be applied to just any string.

```<code>$badges = [
    "<span class='badge badge--brand badge--inline'>$target</span>",
    "<span class='badge badge--dark badge--inline'>$target</span>",
    "<span class='badge badge--primary badge--inline'>$target</span>",
    "<span class='badge badge--success badge--inline'>$target</span>",
    "<span class='badge badge--info badge--inline'>$target</span>",
    "<span class='badge badge--warning badge--inline'>$target</span>",
    "<span class='badge badge--danger badge--inline'>$target</span>",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= $badges[$index % count($badges)];
}
echo $Badges;
</code>```

The desired output would be:

```<code><span class='badge badge--brand badge--inline'>one</span><span class='badge badge--dark badge--inline'>two</span><span class='badge badge--primary badge--inline'>three</span>
</code>```

I realize the $target variables are being evaluated inside the array, before it reaches the loop. With error reporting, this fails and without it, there is nothing in place of $target.

I can certainly just leverage str_replace and achieve desired results but this seemed like an interesting solution if I could get it to work.

Is it possible to achieve this? I haven't tried using eval and I would prefer not to as the $TargetStr is user supplied.

答:
You can set these spans as format strings instead.

```<code>$badges = [
    "<span class='badge badge--brand badge--inline'>%s</span>",
    "<span class='badge badge--dark badge--inline'>%s</span>",
    "<span class='badge badge--primary badge--inline'>%s</span>",
    "<span class='badge badge--success badge--inline'>%s</span>",
    "<span class='badge badge--info badge--inline'>%s</span>",
    "<span class='badge badge--warning badge--inline'>%s</span>",
    "<span class='badge badge--danger badge--inline'>%s</span>",
];
</code>```

Then use sprintf to print the spans with your variables.

```<code>$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= sprintf($badges[$index % count($badges)], $target);
}
echo $Badges;
</code>```

If you like, you could also use sprintf() to insert the different badge types to eliminate the repeated markup.

```<code>$badges = ['brand', 'dark', 'primary', 'success', 'info', 'warning', 'danger'];
$span = "<span class='badge badge--%s badge--inline'>%s</span>";

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= sprintf($span, $badges[$index % count($badges)], $target);
}
echo $Badges;
</code>```

Body:
The application I'm writing generates some HTML server side though it could be applied to just any string.

$badges = [
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= $badges[$index % count($badges)];
}
echo $Badges;

The desired output would be:

onetwothree

I realize the $target variables are being evaluated inside the array, before it reaches the loop. With error reporting, this fails and without it, there is nothing in place of $target.

I can certainly just leverage str_replace and achieve desired results but this seemed like an interesting solution if I could get it to work.

Is it possible to achieve this? I haven't tried using eval and I would prefer not to as the $TargetStr is user supplied.

Body:
You can set these spans as format strings instead.

$badges = [
    "<span class='badge badge--brand badge--inline'>%s</span>",
    "<span class='badge badge--dark badge--inline'>%s</span>",
    "<span class='badge badge--primary badge--inline'>%s</span>",
    "<span class='badge badge--success badge--inline'>%s</span>",
    "<span class='badge badge--info badge--inline'>%s</span>",
    "<span class='badge badge--warning badge--inline'>%s</span>",
    "<span class='badge badge--danger badge--inline'>%s</span>",
];

Then use sprintf to print the spans with your variables.

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= sprintf($badges[$index % count($badges)], $target);
}
echo $Badges;

If you like, you could also use sprintf() to insert the different badge types to eliminate the repeated markup.

$badges = ['brand', 'dark', 'primary', 'success', 'info', 'warning', 'danger'];
$span = "<span class='badge badge--%s badge--inline'>%s</span>";

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= sprintf($span, $badges[$index % count($badges)], $target);
}
echo $Badges;


问:
Retrieve and cache a result set into my Application
I have a byte[] column in a table that has fingerprint data stored in it. I wish to query the rows from a table only once and store the record set in a variable or somewhere in my code, so that I don't have to query the database each and every time. The query will return thousands of rows.

This will fetch all the records for me:

```<code>var table = (from a in context.tblFingerprints
                              select new {a} ).ToList();
</code>```

I tried declaring a variable in AppData class: public List<object> TableData;
Then tried to store the variable 'table' values to it.

```<code>Data.TableData = table;
</code>```

The error remains:

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: FingerprintTEST.tblFingerprint a>>' to 'System.Collections.Generic.List<object>'

This is how I wish to query the rows returned from the result for matching fingerprint:

```<code>foreach (var row in Data.TableData)
{
    Template tem = new Template();
    tem.DeSerialize(row.a.fingerTemplate);

    if (tem != null)
    {
        // Compare feature set with particular template.
        Verificator.Verify(features, tem, ref res);

        if (res.Verified)
        {...}
    }
}
</code>```

Any ideas please?

答:
You are returning these as new objects with select new {a}. If context.tblFingerprints is of type TableData you just need to select a

```<code>var table = (from a in context.tblFingerprints
                          select a).ToList();
</code>```

Body:
I have a byte[] column in a table that has fingerprint data stored in it. I wish to query the rows from a table only once and store the record set in a variable or somewhere in my code, so that I don't have to query the database each and every time. The query will return thousands of rows.

This will fetch all the records for me:

var table = (from a in context.tblFingerprints
                              select new {a} ).ToList();

I tried declaring a variable in AppData class: public List<object> TableData;
Then tried to store the variable 'table' values to it.

Data.TableData = table;

The error remains:

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: FingerprintTEST.tblFingerprint a>>' to 'System.Collections.Generic.List<object>'

This is how I wish to query the rows returned from the result for matching fingerprint:

foreach (var row in Data.TableData)
{
    Template tem = new Template();
    tem.DeSerialize(row.a.fingerTemplate);

    if (tem != null)
    {
        // Compare feature set with particular template.
        Verificator.Verify(features, tem, ref res);

        if (res.Verified)
        {...}
    }
}

Any ideas please?

Body:
You are returning these as new objects with select new {a}. If context.tblFingerprints is of type TableData you just need to select a

var table = (from a in context.tblFingerprints
                          select a).ToList();


答:
You don't need the select new { a } (this is creating a new anonymous-type, with a single member for a whole record, which is silly.

You also don't need any Linq expression at all, just use ToList() on the DbSet directly.

Store the result in a static variable.

```<code>class Something
{
    private static List<tblFingerprint> _fingerprints;

    public void Do()
    {
        DbContext context = ...

        if( _fingerprints is null )
        {
            _fingerprints = context.tblFingerprints.ToList();
        }

        // do stuff with `_fingerprints`
    }
}
</code>```

Title: Retrieve and cache a result set into my Application

Body:
You don't need the select new { a } (this is creating a new anonymous-type, with a single member for a whole record, which is silly.

You also don't need any Linq expression at all, just use ToList() on the DbSet directly.

Store the result in a static variable.

class Something
{
    private static List<tblFingerprint> _fingerprints;

    public void Do()
    {
        DbContext context = ...

        if( _fingerprints is null )
        {
            _fingerprints = context.tblFingerprints.ToList();
        }

        // do stuff with `_fingerprints`
    }
}


问:
finding angles 0-360
Need help with a math issue:
i need to get the true angle from 0 degrees using x and y cordinates
im using this at the moment:

```<code>Math.atan((x2-x1)/(y1-y2))/(Math.PI/180)
</code>```

but /(Math.PI/180) limits results from -90 to 90
i need 0-360

note: I'm using the angle to indicate direction:

0=up

90=right

135=45 degree right+down

180=down

270=left

etc

答:
Here's two solutions, one with Math.atan (which takes a FRACTION opposite/adjacent) and one with Math.atan2 (which takes TWO ARGUMENTS)

solutions are written in ES6 (ES2015+) syntax, ironically, because the question predates this javascript.

note that 'to the right' is 0° (=0 Radians); up is 90° (= PI/2); left is 180° (PI), and down is 270° (PI*1.5)

```<code>angleGivenCoords(coord1,coord2) {
    // given two coords {x,y}, calculate the angle in radians with
    // right being 0° (0 radians)

    if (coord1.x === coord2.x) return (coord1.y > coord2.y ? Math.PI * 0.5 : Math.PI * 1.5)
    if (coord1.y === coord2.y) return (coord1.x > coord2.x ? Math.PI : 0 )

    let opposite = coord2.x - coord1.x
    let adjacent = coord1.y - coord2.y
    let adjustor = ((coord2.x < coord1.x && coord2.y < coord1.y) || (coord2.x < coord1.x && coord2.y > coord1.y)) ?  Math.PI : 0

    let res = Math.atan(opposite/adjacent) + adjustor

    if (res < 0) { res = res + Math.PI*2  }
    return res ;
  }
</code>```

now with Math.atan2. notice that with this solution the guard clauses at the top (coord1.x === coord2.x, (coord1.y === coord2.y)) are unneeded

```<code>  angleGivenCoords(coord1,coord2) {
    // given two coords {x,y}, calculate the angle in radians with
    // left being 0° (0 radians)
    let opposite = coord2.x - coord1.x
    let adjacent = coord1.y - coord2.y
    let res = Math.atan2(adjacent, opposite)
    if (res < 0) { res = res + Math.PI*2  }
    return res ;
  }
</code>```

(I tried to keep the 'opposite' and 'adjacent' variable names in deference to the Trigonometry)

please note that here is my test suite written in Jest. Also note my function above returns radians and my code (not shown here) has a simple Trig.degreesToRadians() as you would expect

```<code> it('for right 0°', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 600, y: 500}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(0))
  })

  it('for up-right 45°', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 600, y: 400}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(45))
  })

  it('for 90° up', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 500, y: 400}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(90))
  })

  it('for 135° up to left', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 400, y: 400}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(135))
  })

  it('for 180° to left', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 400, y: 500}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(180))
  })

  it('for 225° to to bottom left', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 400, y: 600}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(225))
  })

  it('for 270° to the bottom', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 500, y: 600}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(270))
  })

  it('for 315° to the bottom', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 600, y: 600}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(315))
  })
</code>```

Title: finding angles 0-360

Body:
Need help with a math issue:
i need to get the true angle from 0 degrees using x and y cordinates
im using this at the moment:

Math.atan((x2-x1)/(y1-y2))/(Math.PI/180)

but /(Math.PI/180) limits results from -90 to 90
i need 0-360

note: I'm using the angle to indicate direction:

0=up

90=right

135=45 degree right+down

180=down

270=left

etc

Body:
Here's two solutions, one with Math.atan (which takes a FRACTION opposite/adjacent) and one with Math.atan2 (which takes TWO ARGUMENTS)

solutions are written in ES6 (ES2015+) syntax, ironically, because the question predates this javascript.

note that 'to the right' is 0° (=0 Radians); up is 90° (= PI/2); left is 180° (PI), and down is 270° (PI*1.5)

angleGivenCoords(coord1,coord2) {
    // given two coords {x,y}, calculate the angle in radians with
    // right being 0° (0 radians)

    if (coord1.x === coord2.x) return (coord1.y > coord2.y ? Math.PI * 0.5 : Math.PI * 1.5)
    if (coord1.y === coord2.y) return (coord1.x > coord2.x ? Math.PI : 0 )

    let opposite = coord2.x - coord1.x
    let adjacent = coord1.y - coord2.y
    let adjustor = ((coord2.x < coord1.x && coord2.y < coord1.y) || (coord2.x < coord1.x && coord2.y > coord1.y)) ?  Math.PI : 0

    let res = Math.atan(opposite/adjacent) + adjustor

    if (res < 0) { res = res + Math.PI*2  }
    return res ;
  }

now with Math.atan2. notice that with this solution the guard clauses at the top (coord1.x === coord2.x, (coord1.y === coord2.y)) are unneeded

  angleGivenCoords(coord1,coord2) {
    // given two coords {x,y}, calculate the angle in radians with
    // left being 0° (0 radians)
    let opposite = coord2.x - coord1.x
    let adjacent = coord1.y - coord2.y
    let res = Math.atan2(adjacent, opposite)
    if (res < 0) { res = res + Math.PI*2  }
    return res ;
  }

(I tried to keep the 'opposite' and 'adjacent' variable names in deference to the Trigonometry)

please note that here is my test suite written in Jest. Also note my function above returns radians and my code (not shown here) has a simple Trig.degreesToRadians() as you would expect

 it('for right 0°', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 600, y: 500}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(0))
  })

  it('for up-right 45°', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 600, y: 400}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(45))
  })

  it('for 90° up', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 500, y: 400}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(90))
  })

  it('for 135° up to left', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 400, y: 400}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(135))
  })

  it('for 180° to left', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 400, y: 500}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(180))
  })

  it('for 225° to to bottom left', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 400, y: 600}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(225))
  })

  it('for 270° to the bottom', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 500, y: 600}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(270))
  })

  it('for 315° to the bottom', () => {
    let coord1 = {x: 500, y: 500},
      coord2 = {x: 600, y: 600}
    expect(Trig.angleGivenCoords(coord1,coord2)).toEqual(Trig.degreesToRadians(315))
  })


问:
Write a list of Complex Numbers as Binary Data
I'm trying to output some data from a python script to a binary file.

If I have a list of floats I've been using this

```<code>out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()
</code>```

This seems to work fine, at least it's resulting in a file with the correct number of bytes.

How can I do the same thing but using a list of complex numbers?

Thanks

答:
Don't invent your own serialization methods when Python offers so many good ones out of the box! I suggest you use pickle - it works with complex numbers as well (*):

```<code>>>> import pickle
>>> s = pickle.dumps([1+2j, 5-1j])
>>> pickle.loads(s)
[(1+2j), (5-1j)]
</code>```

I'm using dumps for demonstration here, you can also use dump which writes to a binary file.

(*) From the doc of pickle:

The following types can be pickled:

None, True, and False

integers, long integers, floating point numbers, complex numbers

normal and Unicode strings

tuples, lists, sets, and dictionaries containing only picklable
  objects

functions defined at the top level of a module

built-in functions defined at the top level of a module

classes that are defined at the top level of a module

instances of such classes whose __dict__ or __setstate__() is picklable (see section The pickle *
  protocol for details)

Body:
I'm trying to output some data from a python script to a binary file.

If I have a list of floats I've been using this

out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()

This seems to work fine, at least it's resulting in a file with the correct number of bytes.

How can I do the same thing but using a list of complex numbers?

Thanks

Body:
Don't invent your own serialization methods when Python offers so many good ones out of the box! I suggest you use pickle - it works with complex numbers as well (*):

>>> import pickle
>>> s = pickle.dumps([1+2j, 5-1j])
>>> pickle.loads(s)
[(1+2j), (5-1j)]

I'm using dumps for demonstration here, you can also use dump which writes to a binary file.

(*) From the doc of pickle:

The following types can be pickled:

None, True, and False

integers, long integers, floating point numbers, complex numbers

normal and Unicode strings

tuples, lists, sets, and dictionaries containing only picklable
  objects

functions defined at the top level of a module

built-in functions defined at the top level of a module

classes that are defined at the top level of a module

instances of such classes whose __dict__ or __setstate__() is picklable (see section The pickle *
  protocol for details)


答:
Remove the "new {a}" and replace with just "a", and tell ToList that it's a list of objects.</p>

```<code>var table = (from a in context.tblFingerprints
             select a).ToList<object>();
</code>```

Body:
Remove the "new {a}" and replace with just "a", and tell ToList that it's a list of objects.

var table = (from a in context.tblFingerprints
             select a).ToList<object>();


问:
How to delete dynamic feature module after uninstall?
My application has 2 features: "base" and "extend".

manifest extend feature:

```<code><dist:module
    dist:onDemand="true"
    dist:title="@string/title_extend">
    <dist:fusing dist:include="true" />
</dist:module>
</code>```

download feature with SplitInstallManager -> startInstall

unintsalling with SplitInstallManager -> deferredUninstall

Check installed modules with SplitInstallManager -> getInstalledModules

Extend feature is loading from play store success and work as expected. When this feature has become unnecessary - uninstall it.

more, SplitInstallManager has callbacks: SuccessListener, FailureListener, CompleteListener. Install and Uninstall completely with success (no errors).

But, after uninstalling Extend feature (and after restart application) it is stay installed.

How to delete uninstalled feature from the application (need remove no used code and resources) ?

答:
Here is what I noticed.

1) Uninstalling the app removes the downloaded modules, so the next time you run the app, the app will download the modules again.

2) Clearing the app data (e.g. adb shell pm clear APP_PACKAGE_NAME) makes the module not available to the app immediately, but if the module is already downloaded before clearing the app data, it won't be downloaded again. In other words, you won't see SplitInstallSessionStatus.DOWNLOADING.

3) Once the downloadable module becomes available to the app, clearing the app data of "Google Play services" (i.e. adb shell pm clear com.google.android.gms) doesn't make a difference. But occasionally, the downloadable module sticks around even after uninstalling the app, especially when the module's name changes. Then 3) becomes handy to clear the stale modules.

I think what's happening here is when the app requests a downloadable module, Google Play services downloads the module, hands it over to the app, and caches a copy of it, just in case the app requests it again. If the app is uninstalled, Google Play services removes the cached module. deferredUninstall() is just asking Google Play services to uninstall the modules if necessary, but we have no control on when that would happen, if ever.

Body:
My application has 2 features: "base" and "extend".

manifest extend feature:

<dist:module
    dist:onDemand="true"
    dist:title="@string/title_extend">
    <dist:fusing dist:include="true" />
</dist:module>

download feature with SplitInstallManager -> startInstall

unintsalling with SplitInstallManager -> deferredUninstall

Check installed modules with SplitInstallManager -> getInstalledModules

Extend feature is loading from play store success and work as expected. When this feature has become unnecessary - uninstall it.

more, SplitInstallManager has callbacks: SuccessListener, FailureListener, CompleteListener. Install and Uninstall completely with success (no errors).

But, after uninstalling Extend feature (and after restart application) it is stay installed.

How to delete uninstalled feature from the application (need remove no used code and resources) ?


问:
Using xcodebuild to create .app file for simulator
I am trying to use xcodebuild -workspace '/path/to/Awesome.xcworkspace' -scheme 'Awesome-Production' -arch i386  -sdk iphonesimulator8.2 to build a .app file to point Appium to. I am running into the error error: iOS 11 does not support 32-bit programs. This is the only iphonesimulator SDK available when running xcodebuild -showsdks: iphonesimulator12.4. I can't figure out how to get past this error.

答: derivedDataPath did it for me without the -arch flag. For example: - xcodebuild -workspace project.xcworkspace/ -scheme project  -sdk $sdk -derivedDataPath "./build" will dump things in the build folder


问:
How to stop EF Core from indexing all foreign keys
As documented in questions like Entity Framework Indexing ALL foreign key columns, EF Core seems to automatically generate an index for every foreign key.  This is a sound default for me (let's not get into an opinion war here...), but there are cases where it is just a waste of space and slowing down inserts and updates.  How do I prevent it on a case-by-case basis?

I don't want to wholly turn it off, as it does more good than harm; I don't want to have to manually configure it for all those indices I do want.  I just want to prevent it on specific FKs.

Related side question: is the fact that these index are automatically created mentioned anywhere in the EF documentation?  I can't find it anywhere, which is probably why I can't find how to disable it?

Someone is bound to question why I would want to do this... so in the interest of saving time, the OPer of the linked question gave a great example in a comment:

We have a People table and an Addresses table, for example. The
  People.AddressID FK was Indexed by EF but I only ever start from a
  People row and search for the Addresses record; I never find an
  Addresses row and then search the People.AddressID column for a
  matching record.

答:
Entity Framework core 2.0 (the latest version available when the question was asked) doesn't have such a mechanism, but EF Core 2.2 just might - in the form of Owned Entity Types.

Namely, since you said:

" I only ever start from a People row and search for the Addresses record; I never find an Addresses row"

Then you may want to make the Address an Owned Entity Type (and especially the variant with 'Storing owned types in separate tables', to match your choice of storing the address information in a separate Addresses table).
The docs of the feature seem to say a matching:

"Owned entities are essentially a part of the owner and cannot exist without it"

By the way, now that the feature is in EF, this may justify why EF always creates the indexes for HasMany/HasOne. It's likely because the Has* relations are meant to be used towards other entities (as opposed to 'value objects') and these, since they have their own identity, are meant to be queried independently and allow accessing other entities they relate to using navigational properties. For such a use case, it would be simply dangerous use such navigation properties without indexes (a few queries could make the database slow down hugely).

There are few caveats here though:

Turning an entity into an owned one doesn't instruct EF only about the index, but rather it instructs to map the model to database in a way that is a bit different (more on this below) but the end effect is in fact free of that extra index on People.

But chances are, this actually might be the better solution for you: this way you also say that no one should query the Address (by not allowing to create a DbSet<T> of that type), minimizing the chance of someone using it to reach the other entities with these costly indexless queries.

As to what the difference is, you'll note that if you make the Address owned  by Person, EF will create a PersonId column in the Address table, which is different to your AddressId in the People table (in a sense, lack of the foreign key is a bit of a cheat: an index for querying Person from Address is there, it's just that it's the primary key index of the People table, which was there anyways). But take note that this design is actually rather good - it not only needs one column less (no AddressId in People), but it also guarantees that there's no way to make orphaned Address record that your code will never be able to access.

If you would still like to keep the AddressId column in the Addresses, then there's still one option:

Just choose a name of AddressId for the foreign key in the Addresses table and just "pretend" you don't know that it happens to have the same values as the PersonId :)

If that option isn't funny (e.g. because you can't change your database schema), then you're somewhat out of luck. But do take note that among the Current shortcomings of EF they still list "Instances of owned entity types cannot be shared by multiple owners", while some shortcomings of the previous versions are already listed as addressed. Might be worth watching that space as, it seems to me, resolving that one will probably involve introducing the ability to have your AddressId in the People, because in such a model, for the owned objects to be shared among many entities the foreign keys would need to be sitting with the owning entities to create an association to the same value for each.


问:
Can anyone tell me how to hide the contents of a text box
I have a drop down button named bank.
I have 3 text boxes named t1, t2 and t3
if i am not selecting any of the banks all the three text boxes should be enabled..

am getting it..
but my problem is..

first i have selected any one from the drop down button, and after some time i have changed it to choose bank(i.e; the 0th index).. but even then the data in text boxes are still there itself.. how to hide it..

答:
Before you hide the textbox, you have a couple of options:

You could copy the contents of the textbox into a Javascript variable so you can repopulate the box later if you need to, or

You could hide the textbox and replace it with a new textbox that is empty


问:
How can I find out which procedures a particular turtle (Netlogo) is calling at every tick?
I am trying to debug the movements of three particular turtles. All but three turtles, out of the set number of turtles (150) are moving as expected. Three of them however behave, irrationally, going through walls (which they are not programmed to do) or stopping to move for few ticks near the walls and then starting to move again.
I understand that there is no debugging in Netlogo and that one needs to get creative. I am using inspect and print, to get an idea what those three particular turtles are doing (or are about to do) at every tick.

```<code>ask turtles [ if [who] of self = 124 [ inspect self] ]
ask turtle 124 [ print heading]
</code>```

What would really help, is after this to add command to tell/report which procedures and in which order the specific turtle is calling at every tick. I have been looking at forums but without success.

答:
Put a print statement at the beginning of all the relevant procedures along the lines of type self print "I am at procedure-name". The  self identifies which turtle is doing the procedure. Note that this assumes you are already in the turtle context so self makes sense.

As an aside, instead of ask turtles [ if [who] of self = 124 [ inspect self] you can simply say inspect turtle 124

Body:
I am trying to debug the movements of three particular turtles. All but three turtles, out of the set number of turtles (150) are moving as expected. Three of them however behave, irrationally, going through walls (which they are not programmed to do) or stopping to move for few ticks near the walls and then starting to move again.
I understand that there is no debugging in Netlogo and that one needs to get creative. I am using inspect and print, to get an idea what those three particular turtles are doing (or are about to do) at every tick.

ask turtles [ if [who] of self = 124 [ inspect self] ]
ask turtle 124 [ print heading]

What would really help, is after this to add command to tell/report which procedures and in which order the specific turtle is calling at every tick. I have been looking at forums but without success.


问:
Saving SP output into a variable in powershell
```<code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=TSG-ADLT014;Integrated Security=true;Initial Catalog =GenExAll"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "exec usp_GetAccountForRemoteMailbox"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

$name = "test"
$LoginId = "jsmith"
$Userid = "14"

write-host "Enable-RemoteMailbox ""$name"" -RemoteRoutingAddress ""$LoginId@wkhs.mail.onmicrosoft.com"""
</code>```

Right now I am just passing the value in the parameter, $name, $loginid, $userID. I need to store the output from the sp to a variable and then use that variable.

This image is the output of the sp, sp is outputting Userid, Loginid, Name

TO RUN THE CODE ON:

```<code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=TSG-ADLT014;Integrated Security=true;Initial Catalog =GenExAll"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "CREATE TABLE [dbo].[Ident_TESTTABLE](
    [UserId] [int] NOT NULL,
    [LoginId] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](2000) NULL
    ) INSERT INTO Ident_TESTTABLE VALUES(12,'ATEST','AMSAL TEST') SELECT  top 1 *  FROM [Ident_TESTTABLE] "
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

$name = "test"
$LoginId = "jsmith"
$Userid = "14"

write-host "Enable-RemoteMailbox ""$name"" -RemoteRoutingAddress ""$LoginId@wkhs.mail.onmicrosoft.com"""

write-host $name
write-host $LoginId
write-host $Userid
</code>```

答:
This...

```<code>write-host "Enable-RemoteMailbox ""$name"" -RemoteRoutingAddress ""$LoginId@wkhs.mail.onmicrosoft.com"""
</code>```

... will not do anything but write to the screen.

Is this what you are trying to do...

```<code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=TSG-ADLT014;Integrated Security=true;Initial Catalog =GenExAll"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "CREATE TABLE [dbo].[Ident_TESTTABLE](
    [UserId] [int] NOT NULL,
    [LoginId] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](2000) NULL
    ) INSERT INTO Ident_TESTTABLE VALUES(12,'ATEST','AMSAL TEST') SELECT  top 1 *  FROM [Ident_TESTTABLE] "
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]|
ForEach {Enable-RemoteMailbox $PSItem.name -RemoteRoutingAddress $PSitem.LoginId@wkhs.mail.onmicrosoft.com}
</code>```

Meaning, take the output from the SP, as it happens to enable O35 mailboxes?
No reason to output it in order to use it. Well, unless you wanted to and even that should just have you doing $PSItem.name, etc. No real reason for the extra variables, IMHO.

Oh, so you mean stuff like this...

```<code>$SqlQuery = "select Server from ALLdevices where SerialNumber = '$($item.SerialNumber)'"
</code>```

or this...

```<code>$SerialNumber='234978'
$SqlQuery=@"
SELECT Server
FROM ALLdevices
WHERE SerialNumber = '$SerialNumber'
"@
$SqlQuery
</code>```

There are examples like this all over the web. The above is just stuff I have saved in my OneNote files. Search for say this...

'pass PowerShell variable to a sql query'

Or this...

'pass PowerShell variable to a SQL stored procedure'

... will give example(s) like this...:

Using Powershell Variables in a File-Stored Query with SQL Server

SQL Server - Trouble passing variable to a stored procedure

Pass a powershell variable into a SQL value during out-datatable
  (invoke-sqlcmd2)

Body:
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=TSG-ADLT014;Integrated Security=true;Initial Catalog =GenExAll"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "exec usp_GetAccountForRemoteMailbox"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

$name = "test"
$LoginId = "jsmith"
$Userid = "14"

write-host "Enable-RemoteMailbox ""$name"" -RemoteRoutingAddress ""$LoginId@wkhs.mail.onmicrosoft.com"""

Right now I am just passing the value in the parameter, $name, $loginid, $userID. I need to store the output from the sp to a variable and then use that variable.

This image is the output of the sp, sp is outputting Userid, Loginid, Name

TO RUN THE CODE ON:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=TSG-ADLT014;Integrated Security=true;Initial Catalog =GenExAll"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "CREATE TABLE [dbo].[Ident_TESTTABLE](
    [UserId] [int] NOT NULL,
    [LoginId] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](2000) NULL
    ) INSERT INTO Ident_TESTTABLE VALUES(12,'ATEST','AMSAL TEST') SELECT  top 1 *  FROM [Ident_TESTTABLE] "
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

$name = "test"
$LoginId = "jsmith"
$Userid = "14"

write-host "Enable-RemoteMailbox ""$name"" -RemoteRoutingAddress ""$LoginId@wkhs.mail.onmicrosoft.com"""

write-host $name
write-host $LoginId
write-host $Userid

Body:
This...

write-host "Enable-RemoteMailbox ""$name"" -RemoteRoutingAddress ""$LoginId@wkhs.mail.onmicrosoft.com"""

... will not do anything but write to the screen.

Is this what you are trying to do...

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=TSG-ADLT014;Integrated Security=true;Initial Catalog =GenExAll"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "CREATE TABLE [dbo].[Ident_TESTTABLE](
    [UserId] [int] NOT NULL,
    [LoginId] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](2000) NULL
    ) INSERT INTO Ident_TESTTABLE VALUES(12,'ATEST','AMSAL TEST') SELECT  top 1 *  FROM [Ident_TESTTABLE] "
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]|
ForEach {Enable-RemoteMailbox $PSItem.name -RemoteRoutingAddress $PSitem.LoginId@wkhs.mail.onmicrosoft.com}

Meaning, take the output from the SP, as it happens to enable O35 mailboxes?
No reason to output it in order to use it. Well, unless you wanted to and even that should just have you doing $PSItem.name, etc. No real reason for the extra variables, IMHO.

Oh, so you mean stuff like this...

$SqlQuery = "select Server from ALLdevices where SerialNumber = '$($item.SerialNumber)'"

or this...

$SerialNumber='234978'
$SqlQuery=@"
SELECT Server
FROM ALLdevices
WHERE SerialNumber = '$SerialNumber'
"@
$SqlQuery

There are examples like this all over the web. The above is just stuff I have saved in my OneNote files. Search for say this...

'pass PowerShell variable to a sql query'

Or this...

'pass PowerShell variable to a SQL stored procedure'

... will give example(s) like this...:

Using Powershell Variables in a File-Stored Query with SQL Server

SQL Server - Trouble passing variable to a stored procedure

Pass a powershell variable into a SQL value during out-datatable
  (invoke-sqlcmd2)


问:
Scroll bar slider behavior
I am implementing a scrolled window control.
I need to draw simple scrollbar sliders for this purpose.

Usually, sliders shrink as the content grows, but I am unable to understand how.
What is the relation/ratio formula? I've made several google tries to find out, but I didn't.

Does it have a minimum size it can go or it is just really hard to shrink it that far due to exponential shrinking behavior? We are talking simple generic scrollbars. What would be the proper way to implement the proper slider dynamic sizing?

答:
Obviously this question is so dumb that nobody would bother answering.
I used to make complex hacks but now the simplest logic just slipped away across my mind.

The horizontal scroll bar slider width is the portion of the content (child) width.

```<code>(width / content) * width

width * width / content
</code>```

Title: Scroll bar slider behavior

Body:
Obviously this question is so dumb that nobody would bother answering.
I used to make complex hacks but now the simplest logic just slipped away across my mind.

The horizontal scroll bar slider width is the portion of the content (child) width.

(width / content) * width

width * width / content


问:
Elevated privileges in javascript
In SharePoint, when I need to execute an action when the user doesn't have privileges to do so, I use:

```<code>SPSecurity.RunWithElevatedPrivileges(delegate()
 {
// DO SOMETHING WITH PRIVILEGES
});
</code>```

But now I need to execute JavaScript with elevated privileges:

```<code>var context = new SP.ClientContext.get_current();
context.executeQueryAsync(); // NEED PRIVILEGES TO WORK
</code>```

Is this possible?

答:
No, that isn't possible.

The user would be able to manipulate the JavaScript which would open a huge security gap. You just can do this on the server-side. If you need something like this it must all take place at the server.

Title: Elevated privileges in javascript

Body:
In SharePoint, when I need to execute an action when the user doesn't have privileges to do so, I use:

SPSecurity.RunWithElevatedPrivileges(delegate()
 {
// DO SOMETHING WITH PRIVILEGES
});

But now I need to execute JavaScript with elevated privileges:

var context = new SP.ClientContext.get_current();
context.executeQueryAsync(); // NEED PRIVILEGES TO WORK

Is this possible?


问:
Prevent Jupyter from switching between normal mathematical notation and scientific notation
I want to ask a question about turning off scientific notation of numbers in Jupyter notebook.

I have an array named my_array that shows the following when called:

```<code>my_array
---------
array([[1.63276953e+02, 1.41858314e-01],
   [1.64042353e+02, 5.13131094e-01]])
</code>```

and I would like to display this in normal form i.e.

```<code>array([[163.27... , 0.141... ],
   [164.04... , 0.513...]])
</code>```

I am using pylab (otherwise also known as matplotlib) and numpy and have imported it as such:

```<code>%pylab inline
import numpy as np
</code>```

I have tried to solve this solution using such a method given here in another question but this involves panda and not either of the modules mentioned above.

How can I suppress scientific notation here?

Body:
I want to ask a question about turning off scientific notation of numbers in Jupyter notebook.

I have an array named my_array that shows the following when called:

my_array
---------
array([[1.63276953e+02, 1.41858314e-01],
   [1.64042353e+02, 5.13131094e-01]])

and I would like to display this in normal form i.e.

array([[163.27... , 0.141... ],
   [164.04... , 0.513...]])

I am using pylab (otherwise also known as matplotlib) and numpy and have imported it as such:

%pylab inline
import numpy as np

I have tried to solve this solution using such a method given here in another question but this involves panda and not either of the modules mentioned above.

How can I suppress scientific notation here?

Body:
This is a numpy print issue:

In [544]: with np.printoptions(suppress=True):
     ...:     np.array([[1.63276953e+02, 1.41858314e-01],
     ...:    [1.64042353e+02, 5.13131094e-01]])
     ...:
In [545]: with np.printoptions(suppress=True):
     ...:    print( np.array([[1.63276953e+02, 1.41858314e-01],
     ...:    [1.64042353e+02, 5.13131094e-01]]))
     ...:
     ...:
[[163.276953     0.14185831]
 [164.042353     0.51313109]]

In [546]: with np.printoptions(suppress=False):
     ...:    print( np.array([[1.63276953e+02, 1.41858314e-01],
     ...:    [1.64042353e+02, 5.13131094e-01]]))
     ...:
     ...:
[[1.63276953e+02 1.41858314e-01]
 [1.64042353e+02 5.13131094e-01]]

np.set_printoptions can be used to change this (and other) options for the session/script.


问:
How to re-render a react-native components when its prop changes?
Sorry if this is a bit of a noob question. I'm trying to set up a react-native multiplayer game with a lobby which shows who your opponents are. The problem is that even when the prop representing the opponents updates, the component does not re-render, even though a console log shows me the prop has changed (and that render() was called?). Some snippets from my code are below:

In Lobby.js:

```<code>export default class Lobby extends Component {
  render() {
    console.log('In Lobby, opponents = ' + this.props.opponents);
    return(
      <View style={{ flex: 1, justifyContent: "center", alignItems: 'center' }}>
        <Text>Welcome to the lobby { this.props.username }!</Text>
        <Text>Opponents: { this.props.opponents }</Text>
        ... more text and buttons ...
      </View>
    );
  }
}
</code>```

As I said, I can see in the console that this.props.opponents does change but the screen doesn't seem to re-render that <Text> component. I initially thought this may be because this.props.opponents is set to the opponents value of my Main component's state, but the console log seems to debunk this.

I've looked here on SO and found suggestions to add shouldComponentUpdate() and componentDidUpdate() to my component but the nextProps parameter would always actually be the same as this.props. I.e. if I add:

```<code>shouldComponentUpdate(nextProps) {
  console.log('this.props.opponents=' + this.props.opponents + '; ' + 'nextProps.opponents=' + nextProps.opponents);
  return this.props.opponents != nextProps.opponents;
}
</code>```

This never actually returns True for me, even though the prop is definitely changing. (I also don't know what code I would actually want in componentDidUpdate() either, since I just want it to re-render). It just shows that, yes the prop is different but that both nextProps.opponents and this.props.opponents have changed to that same new value (i.e. 'TestUser').

I'm really at a loss here. Thanks in advance.

EDIT: Added simplified version of my code.

App.js:

```<code>import React, { Component } from 'react';

import Main from './components/Main';

export default function App() {
  return (
    <Main/>
  )
}
</code>```

In Main.js:

```<code>import React, { Component } from 'react';
import { View } from 'react-native';

import Lobby from './Lobby';

export default class Main extends Component {
  constructor(props) {
    super(props);

    this.state = {
      opponents: [], // array of strings of other users' usernames
      in_lobby: true // whether user is in lobby or not
    };

    this.testClientJoin = this.testClientJoin.bind(this);
  }

  testClientJoin() {
    console.log('Called testClientJoin().');
    let currentOpponents = this.state.opponents;
    currentOpponents.push('TestUser');
    this.setState({
      opponents: currentOpponents
    });
  }

  render() {
    return(
      <View style={{ flex: 1}}>
        {
          this.state.in_lobby &&
          <Lobby
            opponents={this.state.opponents}
            testClientJoin={this.testClientJoin}
          />
        }
      </View>
    );
  }
}
</code>```

In Lobby.js:

```<code>import React, { Component } from 'react';
import { View, Button, Text } from 'react-native';

export default class Lobby extends Component {
  render() {
    console.log('Opponents prop = ' + this.props.opponents);
    return(
      <View style={{ flex: 1, justifyContent: "center", alignItems: 'center' }}>
        <Text>Welcome to the lobby!</Text>
        <Text>Your opponents are {this.props.opponents}.</Text>
        <Button
          title='Add test opponent'
          onPress={this.props.testClientJoin}
        />
      </View>
    );
  }
}
</code>```

So. When I tap the button to Add test opponent, the console logs

```<code>Called testClientJoin().
Opponents prop = TestUser
</code>```

which shows the prop has indeed updated. However, the  doesn't actually reflect this change, until I force some update (i.e. since I'm using expo, I just save the file again, and I finally see the text appear on my phone. I'm sure I'm just being an idiot but would love to know how to get the desired behavior of the text component updating.

答:
Well I found an answer to my question which I'll leave here if anyone finds this. What I had to do was the following:

Main.js:
Instead of passing this.state.opponents directly as a prop to <Lobby>, pass a copy of this array instead.

```<code>render() {
  <Lobby
    testClientJoin={this.testClientJoin}
    opponents={ [...this.state.opponents] }
  />
</code>```

And this has the desired result. So the moral of the story is, don't try to directly pass an array state from a parent to a child component.

Body:
Sorry if this is a bit of a noob question. I'm trying to set up a react-native multiplayer game with a lobby which shows who your opponents are. The problem is that even when the prop representing the opponents updates, the component does not re-render, even though a console log shows me the prop has changed (and that render() was called?). Some snippets from my code are below:

In Lobby.js:

export default class Lobby extends Component {
  render() {
    console.log('In Lobby, opponents = ' + this.props.opponents);
    return(
      <View style={{ flex: 1, justifyContent: "center", alignItems: 'center' }}>
        <Text>Welcome to the lobby { this.props.username }!</Text>
        <Text>Opponents: { this.props.opponents }</Text>
        ... more text and buttons ...
      </View>
    );
  }
}

As I said, I can see in the console that this.props.opponents does change but the screen doesn't seem to re-render that <Text> component. I initially thought this may be because this.props.opponents is set to the opponents value of my Main component's state, but the console log seems to debunk this.

I've looked here on SO and found suggestions to add shouldComponentUpdate() and componentDidUpdate() to my component but the nextProps parameter would always actually be the same as this.props. I.e. if I add:

shouldComponentUpdate(nextProps) {
  console.log('this.props.opponents=' + this.props.opponents + '; ' + 'nextProps.opponents=' + nextProps.opponents);
  return this.props.opponents != nextProps.opponents;
}

This never actually returns True for me, even though the prop is definitely changing. (I also don't know what code I would actually want in componentDidUpdate() either, since I just want it to re-render). It just shows that, yes the prop is different but that both nextProps.opponents and this.props.opponents have changed to that same new value (i.e. 'TestUser').

I'm really at a loss here. Thanks in advance.

EDIT: Added simplified version of my code.

App.js:

import React, { Component } from 'react';

import Main from './components/Main';

export default function App() {
  return (

  )
}

In Main.js:

import React, { Component } from 'react';
import { View } from 'react-native';

import Lobby from './Lobby';

export default class Main extends Component {
  constructor(props) {
    super(props);

    this.state = {
      opponents: [], // array of strings of other users' usernames
      in_lobby: true // whether user is in lobby or not
    };

    this.testClientJoin = this.testClientJoin.bind(this);
  }

  testClientJoin() {
    console.log('Called testClientJoin().');
    let currentOpponents = this.state.opponents;
    currentOpponents.push('TestUser');
    this.setState({
      opponents: currentOpponents
    });
  }

  render() {
    return(
      <View style={{ flex: 1}}>
        {
          this.state.in_lobby &&
          <Lobby
            opponents={this.state.opponents}
            testClientJoin={this.testClientJoin}
          />
        }
      </View>
    );
  }
}

In Lobby.js:

import React, { Component } from 'react';
import { View, Button, Text } from 'react-native';

export default class Lobby extends Component {
  render() {
    console.log('Opponents prop = ' + this.props.opponents);
    return(
      <View style={{ flex: 1, justifyContent: "center", alignItems: 'center' }}>
        <Text>Welcome to the lobby!</Text>
        <Text>Your opponents are {this.props.opponents}.</Text>
        <Button
          title='Add test opponent'
          onPress={this.props.testClientJoin}
        />
      </View>
    );
  }
}

So. When I tap the button to Add test opponent, the console logs

Called testClientJoin().
Opponents prop = TestUser

which shows the prop has indeed updated. However, the  doesn't actually reflect this change, until I force some update (i.e. since I'm using expo, I just save the file again, and I finally see the text appear on my phone. I'm sure I'm just being an idiot but would love to know how to get the desired behavior of the text component updating.

Body:
Well I found an answer to my question which I'll leave here if anyone finds this. What I had to do was the following:

Main.js:
Instead of passing this.state.opponents directly as a prop to <Lobby>, pass a copy of this array instead.

render() {
  <Lobby
    testClientJoin={this.testClientJoin}
    opponents={ [...this.state.opponents] }
  />

And this has the desired result. So the moral of the story is, don't try to directly pass an array state from a parent to a child component.


问:
Python regex to findall across multiple lines
I've tried solving this problem over the past week without making any progress. Any help from y'all is much appreciated.

I've got 1000s of files with the following text:

```<code>,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
</code>```

But a few files also have it in this manner

```<code>,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
</code>```

I need to extract the uppercase address using regex in Python.

It's technically a CSV file that's been exported by a very old system. It is effectively unusable as a CSV and hence I've opted to extract the string assuming it is a plain-text file.

My current code is this, but I've tried quite a few other combinations without arriving at a working solution.

```<code>location = re.findall(r'^Location:,,,(.*),,,,,,,,,,,,,\n$|^Location:,,,(.*)[\n.*]{1,2,3,4,5,6},,,,,,,,,,,,,', CSV, flags=re.DOTALL | re.MULTILINE)
</code>```

Am I even close? Or is there a better way to solve this?

I'm grateful for any help here.

答:
Given your provided dummy data:

s = ''',,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,'''
```

<p>You could use the following regex:</p>

<pre class="lang-py prettyprint-override"><code>matches = re.findall(r'Location:((?:[^,]*,){16})', s, flags=re.MULTILINE)
</code>```

This is what the matches look like:

>>> print('\n\n'.join(matches))
,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,

,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,
```

<p>What to do next depends on the meaning of the commas in the original file. For example, you might want to replace them with spaces:</p>

<pre class="lang-py prettyprint-override"><code>addrs = [match.replace(',', ' ').strip() for match in matches]
</code>```

Which looks like this:

>>> print('\n\n'.join(addrs))
ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS
MULTIPLE LINES  BUT NOT A SPECIFIC SET OF LINES
AND IT ENDS AS ABRUPTLY

ADDRESS IS IN ONE LINE
```

Body:
I've tried solving this problem over the past week without making any progress. Any help from y'all is much appreciated.

I've got 1000s of files with the following text:

,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,

But a few files also have it in this manner

,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,

I need to extract the uppercase address using regex in Python.

It's technically a CSV file that's been exported by a very old system. It is effectively unusable as a CSV and hence I've opted to extract the string assuming it is a plain-text file.

My current code is this, but I've tried quite a few other combinations without arriving at a working solution.

location = re.findall(r'^Location:,,,(.*),,,,,,,,,,,,,\n$|^Location:,,,(.*)[\n.*]{1,2,3,4,5,6},,,,,,,,,,,,,', CSV, flags=re.DOTALL | re.MULTILINE)

Am I even close? Or is there a better way to solve this?

I'm grateful for any help here.

Body:
Given your provided dummy data:

s = ''',,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
Location:,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,'''

You could use the following regex:

matches = re.findall(r'Location:((?:[^,]*,){16})', s, flags=re.MULTILINE)

This is what the matches look like:

>>> print('\n\n'.join(matches))
,,,ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS,
MULTIPLE LINES, BUT NOT A SPECIFIC SET OF LINES,
AND IT ENDS AS ABRUPTLY,,,,,,,,,,

,,,ADDRESS,IS,IN,ONE,LINE,,,,,,,,,

What to do next depends on the meaning of the commas in the original file. For example, you might want to replace them with spaces:

addrs = [match.replace(',', ' ').strip() for match in matches]

Which looks like this:

>>> print('\n\n'.join(addrs))
ADDRESS_HERE_THAT I WANT
BUT IT CAN ALSO BE ACROSS
MULTIPLE LINES  BUT NOT A SPECIFIC SET OF LINES
AND IT ENDS AS ABRUPTLY

ADDRESS IS IN ONE LINE


问:
Tampermonkey in Chrome - How to use jquery without affecting the website at all
With Tampermonkey in Google Chrome, I want to be able to use jquery to set/get values but I need to make sure nothing is changed/added to the dom.

In simple words, I want userscript to be absolutely invisible to the affecting website.

Is the jquery that I added invisible to the website scope?

Another concern is, what if jquery is already present?

Did I do the @grants right?

Here is my try

```<code>// ==UserScript==
// @name         test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_setClipboard
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// ==/UserScript==

(function() {
    'use strict';

    //var $ = unsafeWindow.jQuery;
    var $ = window.jQuery;
    $(document).ready(Greasemonkey_main);

    function Greasemonkey_main ()
    {
    //$("#elem").val()
    }

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

答:
If you have at least one @grant directive other than none, that will activate Tampermonkey's sandbox. This sandbox will result in @required libraries assigning themselves to the sandbox's window, rather than on the native page's window, and referencing the window variable inside the userscript code will refer to the userscript's sandboxed window rather than the page's original window.

If you have @grant none, this will indicate not to use the sandbox, and @requires will result in properties being assigned to the original window (and referencing window inside the userscript will be referring to the original window).

Since you have a @grant which is enabling the sandbox, and you're referencing window.jQuery, that will reference the sandbox's version of jQuery, without doing anything to the page, so it should work as desired, regardless of whether jQuery is already on the native page or not. (Because you're in the sandbox, there shouldn't be any conflicts)

Body:
With Tampermonkey in Google Chrome, I want to be able to use jquery to set/get values but I need to make sure nothing is changed/added to the dom.

In simple words, I want userscript to be absolutely invisible to the affecting website.

Is the jquery that I added invisible to the website scope?

Another concern is, what if jquery is already present?

Did I do the @grants right?

Here is my try

// ==UserScript==
// @name         test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_setClipboard
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// ==/UserScript==

(function() {
    'use strict';

    //var $ = unsafeWindow.jQuery;
    var $ = window.jQuery;
    $(document).ready(Greasemonkey_main);

    function Greasemonkey_main ()
    {
    //$("#elem").val()
    }

})();


问:
Segmentation fault core dumped error in c
Each time I run this c code I get a segmentation fault (core dumped)...so the array gets printed and everything and in the end of the printing it fives me this segmentation fault...I tried putting a break after the if, the error code does not appear but it only now reads one line and doesn't read multiple</p>

```<code>int main(int argc, char* arg[]){
    if (argc != 2){
        puts("Error: Usage is caesarcipher <offset>");
        exit(1);
    }
    int i = 0;
    int input;
    char array[100];
    while ((input = getchar())!= '\0'){
        if (input == '\n'){
            array[i] = '\0';
            printf("%s\n", array);
            i = 0;
        }else{
            array[i] = input;
            i += 1;}}
        return 0;
    }
}
</code>```

答: You should check the documentation for getchar(), particularly the return value which indicates an error.

Body:
Each time I run this c code I get a segmentation fault (core dumped)...so the array gets printed and everything and in the end of the printing it fives me this segmentation fault...I tried putting a break after the if, the error code does not appear but it only now reads one line and doesn't read multiple

int main(int argc, char* arg[]){
    if (argc != 2){
        puts("Error: Usage is caesarcipher <offset>");
        exit(1);
    }
    int i = 0;
    int input;
    char array[100];
    while ((input = getchar())!= '\0'){
        if (input == '\n'){
            array[i] = '\0';
            printf("%s\n", array);
            i = 0;
        }else{
            array[i] = input;
            i += 1;}}
        return 0;
    }
}


问:
How are STA COM components handled when used in a WCF service hosted in IIS (7+)?
From what I understand, when a COM component marked as using STA is used from an MTA thread, the calls are supposed to be marshalled to an STA thread and executed from that dedicated thread. In the case of a Windows client application, this would mean that it would execute on the UI thread (if marked as STA), and that callbacks from the COM component to me would be handled by Windows messages sent to a hidden window and processed on the Windows message loop.

What happens though if I use a STA COM component in a WCF service hosted in IIS? Will the worker process have a Windows message loop on a STA thread? Can I fire up my own STA thread with its own message loop?

答:
I've found that you need to pump messages on your STA thread in a WCF service or you miss callbacks from the COM object.

The following code works, but it requires you call the COM object via a Dispatcher.

```<code>ComWrapper comWrapper;
Thread localThread;
Dispatcher localThreadDispatcher;

public Constructor()
{
   localThread = new Thread(ThreadProc)
   {
       Name = "test"
   };
   localThread.SetApartmentState(ApartmentState.STA);

   AutoResetEvent init = new AutoResetEvent(false);

   localThread.Start(init);

   init.WaitOne();
}

private void ThreadProc(object o)
{
    localThreadDispatcher = Dispatcher.CurrentDispatcher;
    ((AutoResetEvent)o).Set();

    comWrapper = new ComWrapper()

    Dispatcher.Run();

    localThreadFinished.Set();
 }
</code>```

And then make calls as follows.

```<code>public void UsefulComOperation()
{
    localThreadDispatcher.Invoke(new Action( () => comWrapper.UsefulOperation);
}
</code>```

Body:
I've found that you need to pump messages on your STA thread in a WCF service or you miss callbacks from the COM object.

The following code works, but it requires you call the COM object via a Dispatcher.

ComWrapper comWrapper;
Thread localThread;
Dispatcher localThreadDispatcher;

public Constructor()
{
   localThread = new Thread(ThreadProc)
   {
       Name = "test"
   };
   localThread.SetApartmentState(ApartmentState.STA);

   AutoResetEvent init = new AutoResetEvent(false);

   localThread.Start(init);

   init.WaitOne();
}

private void ThreadProc(object o)
{
    localThreadDispatcher = Dispatcher.CurrentDispatcher;
    ((AutoResetEvent)o).Set();

    comWrapper = new ComWrapper()

    Dispatcher.Run();

    localThreadFinished.Set();
 }

And then make calls as follows.

public void UsefulComOperation()
{
    localThreadDispatcher.Invoke(new Action( () => comWrapper.UsefulOperation);
}


问:
150 years ago today in PHP
I am looking to have a one line return function to get the date 150 years ago from today.

I currently have,

```<code>return date('Y-m-d', strtotime('-150 year'));
</code>```

The problem is this returns 1970-01-01 instead of 150 years ago.

Why is this?

答:
Your issue is that strtotime returns a unix timestamp (seconds since 1970-01-01 00:00:00), so the earliest date it can understand is 1970-01-01. Since 150 years ago today is before 1970-01-01 strtotime is returning false, which is interpreted as a 0 timestamp by date, resulting in an output of 1970-01-01. To work around this limitation use the DateTime class:

```<code>$date = new DateTime('-150 year');
echo $date->format('Y-m-d');
</code>```

Output (as of 2020-02-19):

```<code>1870-02-19
</code>```

If the code does need to be in one line, you can write:

```<code>$date = (new DateTime('-150 year'))->format('Y-m-d');
</code>```

Demo on 3v4l.org

Title: 150 years ago today in PHP

Body:
I am looking to have a one line return function to get the date 150 years ago from today.

I currently have,

return date('Y-m-d', strtotime('-150 year'));

The problem is this returns 1970-01-01 instead of 150 years ago.

Why is this?

Body:
Your issue is that strtotime returns a unix timestamp (seconds since 1970-01-01 00:00:00), so the earliest date it can understand is 1970-01-01. Since 150 years ago today is before 1970-01-01 strtotime is returning false, which is interpreted as a 0 timestamp by date, resulting in an output of 1970-01-01. To work around this limitation use the DateTime class:

$date = new DateTime('-150 year');
echo $date->format('Y-m-d');

Output (as of 2020-02-19):

1870-02-19

If the code does need to be in one line, you can write:

$date = (new DateTime('-150 year'))->format('Y-m-d');

Demo on 3v4l.org


问:
How do i add all the value of this array
This might be very stupid question but can someone tell me how to sum the following array in karate

simple array [18, 190, 220, 0]

something like this ?

def response = [18, 190, 220, 0]

And assert response == 428

答:
Refer loops: https://github.com/intuit/karate#json-transforms

```<code>* def array = [18, 190, 220, 0]
* def result = 0
* def fun = function(x){ var temp = karate.get('result'); karate.set('result', temp + x )}
* karate.forEach(array, fun)
* match result == 428
</code>```

If the above looks too scary, you can always define it as a re-usable function, or you can use a Java utility you write: https://github.com/intuit/karate#commonly-needed-utilities

Body:
Refer loops: https://github.com/intuit/karate#json-transforms

* def array = [18, 190, 220, 0]
* def result = 0
* def fun = function(x){ var temp = karate.get('result'); karate.set('result', temp + x )}
* karate.forEach(array, fun)
* match result == 428

If the above looks too scary, you can always define it as a re-usable function, or you can use a Java utility you write: https://github.com/intuit/karate#commonly-needed-utilities


问:
passing dynamic data to nested components
i have a main page with a list of orders ('list-orders' component), every time i click an order i open an 'order-details' component via router-outlet.

in the order-details component i have in the html a component selector ('app-list-products'), in that selector i want to pass the data of the products of the order ('order.products')

im using an NgRX state management and get the order data in the 'list-orders' component in the OnInit cycle. i do the same for the 'order-details' component (to get the correct order details).

but every time im changing the order im viewing (choosing from the 'list-orders' view), the products i get
are of the previous order i wanted.

can anyone explain me why does it happen? how can i fix it?

list-order.html:

```<code><ul class="list-group" *ngIf="orders.length">
    <li
      class="list-group-item"
      *ngFor="let order of orders; let i=index">
      <a routerLink='{{i}}'>
        <p>Name: {{ order.name }}</p>
      </a>
    </li>
  </ul>
</code>```

list-order.ts:

```<code>ngOnInit() {
    this.subscription = this.store.select('order')
      .pipe(map(orderState => {
        return orderState.orders;
      }))
      .subscribe(orders=> {
        this.orders = orders;
      });
  }
</code>```

order-details.html:

```<code><div class="row" *ngIf="order">
    <p>name: {{ order.name|| "------" }}</p>
    <app-list-products [orderProducts]="order.products"></app-list-products>
</div>
</code>```

order-details.ts

```<code>order: Order = null;
ngOnInit() {
    let currUrl;
    this.routeSub = this.route.params.pipe(
      switchMap(() => {
        currUrl = this.route.snapshot['_routerState'].url.substring(1).split('/');
        return this.store.select('order')
       }))
      .subscribe(orderState => {
          this.order = orderState['order'][+currUrl[1]];
      });
  }

</code>```

答:
with the help and steps in the questions:

How to re-render a component manually Angular 5

Is there any way I can pass dynamic data to a component in Angular?

solution:

in details-order.ts i added:

private ref: ChangeDetectorRef to the constructor

and called this.ref.detectChanges(); at the end of the subscribe method (after assigning to 'this.order')

Body:
i have a main page with a list of orders ('list-orders' component), every time i click an order i open an 'order-details' component via router-outlet.

in the order-details component i have in the html a component selector ('app-list-products'), in that selector i want to pass the data of the products of the order ('order.products')

im using an NgRX state management and get the order data in the 'list-orders' component in the OnInit cycle. i do the same for the 'order-details' component (to get the correct order details).

but every time im changing the order im viewing (choosing from the 'list-orders' view), the products i get
are of the previous order i wanted.

can anyone explain me why does it happen? how can i fix it?

list-order.html:

Name: {{ order.name }}

list-order.ts:

ngOnInit() {
    this.subscription = this.store.select('order')
      .pipe(map(orderState => {
        return orderState.orders;
      }))
      .subscribe(orders=> {
        this.orders = orders;
      });
  }

order-details.html:

name: {{ order.name|| "------" }}

    <app-list-products [orderProducts]="order.products"></app-list-products>

order-details.ts

order: Order = null;
ngOnInit() {
    let currUrl;
    this.routeSub = this.route.params.pipe(
      switchMap(() => {
        currUrl = this.route.snapshot['_routerState'].url.substring(1).split('/');
        return this.store.select('order')
       }))
      .subscribe(orderState => {
          this.order = orderState['order'][+currUrl[1]];
      });
  }


问:
"${#fields.hasErrors('*')}" always false - Redirect Problem
My controller looks like this:

```<code>    @PostMapping("/event/{id}")
    public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {

        if (!bindingResult.hasErrors()) {
          //No errors
          //No return
        }

        return "redirect:/event/{id}";
    }
</code>```

My @GetMapping is:

```<code> @GetMapping("/event/{id}")
    public ModelAndView eventDetail(@PathVariable("id") long id) {

        ModelAndView model = new ModelAndView("event/details");
        Event event = eventoRepository.findById(id).get();
        model.addObject("event", evento);
        model.addObject("guests", event.getGuests());
        model.addObject("guest",new Guest());

        return model;

    }
</code>```

I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

How return to  this path /event/{id} without redirect?

答:
I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

Right. It looks like you always redirect. Because of that a method annotated with @GetMapping("/event/{id}") is called, the form most likely is reseted to fresh state and there are no more errors making expression always false.

How return to this path /event/{id} without redirect?

Simply return name of the view (template) containing the form. Most likely it's the same what's returned by method annotated with @GetMapping("/event/{id}").

You should follow an approach from this guide. Return without redirect if the form contains error, and redirect otherwise.

Edit:
You should also provide additional objects to the model. Instead of populating model in each method (Get, Post etc.) you may extract common objects to a method annotated with @ModelAttribute. According to javadoc such a method can accept similar parameters as methods annotated with @RequestMapping.

For your case something like this should work fine:

    @ModelAttribute
    void supplyModel(@PathVariable("id") long id, Model model) {
        Event event = eventoRepository.findById(id).get();
        model.addAttribute("event", evento);
        model.addAttribute("guests", event.getGuests());
        model.addAttribute("guest",new Guest());
    }

    @GetMapping("/event/{id}")
    public String eventDetail(@PathVariable("id") long id) {
        return "event/details";

    }

    @PostMapping("/event/{id}")
    public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {

        if (bindingResult.hasErrors()) {
            // Has errors
            return "event/details";
        }

        // No errors
        return "redirect:/event/" + id;
    }
```

Body:
My controller looks like this:

    @PostMapping("/event/{id}")
    public String save(@PathVariable("id") long id, @Valid Form form, BindingResult bindingResult ) {

        if (!bindingResult.hasErrors()) {
          //No errors
          //No return
        }

        return "redirect:/event/{id}";
    }

My @GetMapping is:

 @GetMapping("/event/{id}")
    public ModelAndView eventDetail(@PathVariable("id") long id) {

        ModelAndView model = new ModelAndView("event/details");
        Event event = eventoRepository.findById(id).get();
        model.addObject("event", evento);
        model.addObject("guests", event.getGuests());
        model.addObject("guest",new Guest());

        return model;

    }

I know that "${#fields.hasErrors('*')}" is always false because redirect. (right?)

How return to  this path /event/{id} without redirect?


问:
How do you define an enumeration in 68000 assembly language?
I'm using the assembler that came with the Manx Aztec C compiler (version 5.0) on a Commodore Amiga 500.

I want to code the equivalent of the following C code:

```<code>enum STATUS {
    STATUS_OKAY,
    STATUS_WAITING,
    STATUS_ERROR
};
</code>```

I tried the following—which works—but it seems kind of hokey:

```<code>s_id            set 0
STATUS_OKAY     equ s_id
s_id            set s_id+1
STATUS_WAITING  equ s_id
s_id            equ s_id+1
STATUS_ERROR    equ s_id
</code>```

I know I could do:

```<code>STATUS_OKAY    equ 0
STATUS_WAITING equ 1
STATUS_ERROR   equ 2
</code>```

But I would like to be able to insert and rearrange values without having to manually renumber.

I was thinking I might be able to do something with macros, but I don't have much experience with them.

答:
After Peter Cordes' suggestion, I came up with the following macro, which works great:</p>

```<code>        macro   ENUM
\2      set     \1
\1      set     \1+1
        endm

s_id    set     0
        ENUM    s_id,STATUS_OKAY
        ENUM    s_id,STATUS_WAITING
        ENUM    s_id,STATUS_ERROR
</code>```

Body:
I'm using the assembler that came with the Manx Aztec C compiler (version 5.0) on a Commodore Amiga 500.

I want to code the equivalent of the following C code:

enum STATUS {
    STATUS_OKAY,
    STATUS_WAITING,
    STATUS_ERROR
};

I tried the following—which works—but it seems kind of hokey:

s_id            set 0
STATUS_OKAY     equ s_id
s_id            set s_id+1
STATUS_WAITING  equ s_id
s_id            equ s_id+1
STATUS_ERROR    equ s_id

I know I could do:

STATUS_OKAY    equ 0
STATUS_WAITING equ 1
STATUS_ERROR   equ 2

But I would like to be able to insert and rearrange values without having to manually renumber.

I was thinking I might be able to do something with macros, but I don't have much experience with them.

Body:
After Peter Cordes' suggestion, I came up with the following macro, which works great:

        macro   ENUM
\2      set     \1
\1      set     \1+1
        endm

s_id    set     0
        ENUM    s_id,STATUS_OKAY
        ENUM    s_id,STATUS_WAITING
        ENUM    s_id,STATUS_ERROR